repo_name stringlengths 5 100 | ref stringlengths 12 67 | path stringlengths 4 244 | copies stringlengths 1 8 | content stringlengths 0 1.05M ⌀ |
|---|---|---|---|---|
EdgarSun/Django-Demo | refs/heads/master | django/contrib/gis/geometry/backend/__init__.py | 388 | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
geom_backend = getattr(settings, 'GEOMETRY_BACKEND', 'geos')
try:
module = import_module('.%s' % geom_backend, 'django.contrib.gis.geometry.backend')
except ImportError, e:
try:
module = import_module(geom_backend)
except ImportError, e_user:
raise ImproperlyConfigured('Could not import user-defined GEOMETRY_BACKEND '
'"%s".' % geom_backend)
try:
Geometry = module.Geometry
GeometryException = module.GeometryException
except AttributeError:
raise ImproperlyConfigured('Cannot import Geometry from the "%s" '
'geometry backend.' % geom_backend)
|
dmlc/tvm | refs/heads/main | python/tvm/auto_scheduler/loop_state.py | 4 | # 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.
# pylint: disable=unused-import
"""
The definition of the "state" in the search.
Each LoopState corresponds to a schedule for its ComputeDAG.
A LoopState consists of: 1. a current loop structure; 2. a list of transformation steps used to
construct the loop structure.
The loop structure keeps a preview of how the schedule will finally look like after lowering the
current state (e.g. number of iterators, the extent of each iterator, the compute_at locations
...).
During the schedule search process, the loop structure can provide search policy with necessary
information on how to manipulate the current state.
The transform history is a sequence of `TransformStep` which will finally be mapped to TVM
schedule primitives. The steps are also used for the serialization of a state.
The LoopState can be seen as a lightweight loop structure IR specifically for schedule search.
We don't use the existing TVM IR but to extend a new structure on it is because:
1. We want fast incremental change to the loop structures. The search policy needs to get the
immediate loop structures update rather than after TVM lowering;
2. We want serializable transform history for replay, backtracking, and mutation;
3. We may create some macro schedule primitives that represent the combination of several
TVM schedule primitives.
When the search is finished, we will lower the state to TVM IR with TVM's schedule primitives.
Since we share a lot of common objects during search, the transformation is implemented in
copy on write style. All objects are immutable, which is similar to TVM IR.
"""
import tvm._ffi
from tvm.te.tensor import Operation, Tensor
from tvm.runtime import Object
from . import _ffi_api
@tvm._ffi.register_object("auto_scheduler.Iterator")
class Iterator(Object):
""" A loop iterator structure. """
@tvm._ffi.register_object("auto_scheduler.Stage")
class Stage(Object):
""" A stage in the compute declaration. Similar to tvm.te.schedule.Stage. """
# Static trans table for compute_at location
# This is used to transform the compute_at location to C++ enum
COMPUTE_AT_TRANS_TABLE = {"root": 0, "inlined": 1, "iter": 2}
@tvm._ffi.register_object("auto_scheduler.State")
class StateObject(Object):
""" The internal State object """
def __eq__(self, other):
return _ffi_api.StateEqual(self, other)
class State:
"""
A state in the search process. It consists of the current loop structure
and a list of transformation steps used to construct it.
Each State corresponds to a specific schedule for its ComputeDAG.
Parameters
----------
state_object : StateObject
The StateObject corresponding to C++ internal State object.
dag : ComputeDAG
The original ComputeDAG of this State.
Notes
-----
This is a wrapper class of StateObject to deal with copy-on-write property
"""
# Static trans table for thread bind and annotation
# This is used to transform the annotation name to C++ enum
ANNOTATION_TRANS_TABLE = {
"none": 0,
"unroll": 1,
"vectorize": 2,
"parallel": 3,
"vthread": 4,
"blockIdx.x": 5,
"threadIdx.x": 6,
"blockIdx.y": 7,
"threadIdx.y": 8,
"blockIdx.z": 9,
"threadIdx.z": 10,
"tensorize": 11,
}
def __init__(self, state_object, dag):
self.state_object = state_object
self.compute_dag = dag
self.stage_id_map = {} # A dict maps operation to stage id
self._update_stage_id_map()
@property
def stages(self):
"""
Returns
-------
stages : List[Stage]
"""
return self.state_object.stages
@property
def transform_steps(self):
"""
Returns
-------
transform_steps : List[transform_steps]
"""
return self.state_object.transform_steps
@property
def stage_ops(self):
"""
Returns
-------
ops: List[Operation]
"""
return [stage.op for stage in self.stages]
def bind(self, stage, iterator, thread_name):
"""Schedule primitive corresponding to `te.Stage.bind`.
See also the `te.Stage` for more details.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be binded, which can be specified by the integer index, Operation,
or output tensor of the stage.
iterator : Iterator
The iterator to be binded.
thread_name : str
The thread type to be binded. Candidates:
- vthread
- blockIdx.x
- threadIdx.x
- blockIdx.y
- threadIdx.y
- blockIdx.z
- threadIdx.z
Returns
-------
res_it : Iterator
The binded Iterator.
"""
if not thread_name in State.ANNOTATION_TRANS_TABLE.keys():
raise ValueError("Invalid thread_name: ", thread_name)
self.state_object, res = _ffi_api.StateBind(
self.state_object,
self._resolve_stage_id(stage),
iterator,
State.ANNOTATION_TRANS_TABLE[thread_name],
)
return res
def parallel(self, stage, iterator):
"""Schedule primitive corresponding to `te.Stage.parallel`.
See also the `te.Stage` for more details.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be paralleled, which can be specified by the integer index, Operation,
or output tensor of the stage.
iterator : Iterator
The iterator to be paralleled.
Returns
-------
res_it : Iterator
The paralleled Iterator.
"""
self.state_object, res = _ffi_api.StateParallel(
self.state_object, self._resolve_stage_id(stage), iterator
)
return res
def unroll(self, stage, iterator, max_unroll=None):
"""Schedule primitive corresponding to `te.Stage.unroll`.
See also the `te.Stage` for more details.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be unrolled, which can be specified by the integer index, Operation,
or output tensor of the stage.
iterator : Iterator
The iterator to be unrolled.
max_unroll : Optional[int]
The max unroll limit. Iterator with extent larger than this limit will be skipped.
Returns
-------
res_it : Iterator
The unrolled Iterator.
"""
self.state_object, res = _ffi_api.StateUnroll(
self.state_object,
self._resolve_stage_id(stage),
iterator,
max_unroll if max_unroll else -1,
)
return res
def vectorize(self, stage, iterator):
"""Schedule primitive corresponding to `te.Stage.vectorize`.
See also the `te.Stage` for more details.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be vectorized, which can be specified by the integer index, Operation,
or output tensor of the stage.
iterator : Iterator
The iterator to be vectorized.
Returns
-------
res_it : Iterator
The vectorized Iterator.
"""
self.state_object, res = _ffi_api.StateVectorize(
self.state_object, self._resolve_stage_id(stage), iterator
)
return res
def fuse(self, stage, iters):
"""Schedule primitive corresponding to `te.Stage.fuse`.
See also the `te.Stage` for more details.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be fused, which can be specified by the integer index, Operation,
or output tensor of the stage.
iters : List[Iterator]
The iterators to be fused.
Returns
-------
res_it : Iterator
The fused Iterator.
Notes
-----
If the iterators to be fused have stages attached at them(by compute_at), the fused
result will become the new attach point.
"""
self.state_object, res = _ffi_api.StateFuse(
self.state_object, self._resolve_stage_id(stage), iters
)
return res
def pragma(self, stage, iterator, pragma_type):
"""Schedule primitive corresponding to `te.Stage.pragma`.
See also the `te.Stage` for more details.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to add pragma, which can be specified by the integer index, Operation,
or output tensor of the stage.
iterator : Iterator
The iterator to add pragma.
pragma_type : str
The pragma string.
"""
self.state_object = _ffi_api.StatePragma(
self.state_object, self._resolve_stage_id(stage), iterator, pragma_type
)
def reorder(self, stage, order):
"""Schedule primitive corresponding to `te.Stage.reorder`.
See also the `te.Stage` for more details.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be reordered, which can be specified by the integer index, Operation,
or output tensor of the stage.
order : List[Iterator]
Iterators in the expected order.
"""
self.state_object = _ffi_api.StateReorder(
self.state_object, self._resolve_stage_id(stage), order
)
def split(self, stage, iterator, lengths, inner_to_outer=True):
"""Schedule primitive corresponding to `te.Stage.split`.
See also the `te.Stage` for more details.
This API supports multiple split factors. (e.g. with 2 split factors, the original iterator
will be split to 3 parts, use `inner_to_outer` to control the split order)
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be split, which can be specified by the integer index, Operation,
or output tensor of the stage.
iterator : Iterator
The iterator to be split.
lengths: List[int]
The multiple split factors. Can be None to be filled by search policy.
inner_to_outer: boolean = True
Whether the factor go from inner to outer, or from outer to inner.
Returns
-------
res_its : List[Iterator]
The splitted new Iterators.
Notes
-----
If we do split on an iterator which has stages attached at it(by compute_at), the inner
most iterator of split results will become the new attach point.
"""
self.state_object, res = _ffi_api.StateSplit(
self.state_object, self._resolve_stage_id(stage), iterator, lengths, inner_to_outer
)
return res
def follow_split(self, stage, iterator, src_step_id, n_split):
"""The schedule primitive similar to split, but uses split factors from previous steps.
This step splits the iterator by the same factors as the given SplitStep.
Notes
------
This step is useful in a scenario that we have subgraph Dense -> Relu,
and we want to compute the Dense stage at ReLU. In this case, we need them to have
the same tiling structure of common outer loops.
The follow_split step could be used here to split the Dense stage and makes sure its
splitting factors are the same as the given split step for the ReLU stage.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be split, which can be specified by the integer index, Operation,
or output tensor of the stage.
iterator : Iterator
The iterator to split.
src_step_id : int
The index of the split step to be followed in the history.
n_split : int
The number of split level.
Returns
-------
res_its : List[Iterator]
The splitted new Iterators.
"""
self.state_object, res = _ffi_api.StateFollowSplit(
self.state_object, self._resolve_stage_id(stage), iterator, src_step_id, n_split
)
return res
def follow_fused_split(self, stage, iterator, src_step_ids, level, factor_or_nparts):
"""Schedule primitive extends to split step.
This step is used to split an iterator by the same factors
as the given list of SplitSteps and FuseSteps.
Notes
------
This step is useful in a scenario that we have a subgraph
in GPU schedule: Input -> Dense
for i.0@j.0 = ... : Bind to blockIdx.x
for i.1@j.1 = ... : Bind to threadIdx.x
for i.2@j.2 = ...
Input_shared = Input ...
for k = ...
Dense = ...
We intend to apply cooperative fetching with the input stage, while the threadIdx.x
axis is bound to an iterator generated by split & fuse step.
The follow_fused_step is used split the iterator to 2 parts, while the split factor
matches the final extent of the threadIdx.x bound iterator.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be split, which can be specified by the integer index, Operation,
or output tensor of the stage.
iterator : Iterator
The iterator to split.
src_step_ids : List[int]
The indices of the split steps to be followed in the history.
level : int
Use the length in this split level.
factor_or_nparts : bool
True to use `factor` for split from inner to outer,
False to use `nparts` for split from outer to inner.
Returns
-------
res_its : List[Iterator]
The splitted new Iterators.
"""
self.state_object, res = _ffi_api.StateFollowFusedSplit(
self.state_object,
self._resolve_stage_id(stage),
iterator,
src_step_ids,
level,
factor_or_nparts,
)
return res
def storage_align(self, stage, iterator, factor, offset):
"""Schedule primitive corresponding to `te.Stage.storage_align`.
See also the `te.Stage` for more details.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be storage aligned, which can be specified by the integer index,
Operation, or output tensor of the stage.
iterator : Iterator
The iterator to be aligned.
factor : int
The factor in alignment specification.
offset : int
The offset in the alignment specification.
"""
self.state_object = _ffi_api.StateStorageAlign(
self.state_object, self._resolve_stage_id(stage), iterator, factor, offset
)
def compute_at(self, stage, target_stage, target_iter):
"""Schedule primitive corresponding to `te.Stage.compute_at`.
See also the `te.Stage` for more details.
Parameters
----------
stage : Union[int, Operation, Tensor]
The source Stage of computed at, which can be specified by the integer index,
Operation, or output tensor of the stage.
target_stage : Union[int, Operation, Tensor]
The target stage of compute_at, which can be specified by the integer index, Operation,
or output tensor of the stage.
target_iter : Iterator
The target Iterator of compute_at.
Notes
-----
After compute_at, we need careful dependency analysis to compute the accurate bound
information. However, it is relatively expensive and complicated, so we just fill "None"
as bound for the newly created iterators.
Call ComputeDAG::InferBound on the returned state to get the complete bound information.
"""
self.state_object = _ffi_api.StateComputeAt(
self.state_object,
self._resolve_stage_id(stage),
self._resolve_stage_id(target_stage),
target_iter,
)
def compute_inline(self, stage):
"""Schedule primitive corresponding to `te.Stage.compute_inline`, see also the `te.Stage`
for more details.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be marked compute inlined, which can be specified by the integer index,
Operation, or output tensor of the stage.
"""
self.state_object = _ffi_api.StateComputeInline(
self.state_object, self._resolve_stage_id(stage)
)
def compute_root(self, stage):
"""Schedule primitive corresponding to `te.Stage.compute_root`.
Ssee also the `te.Stage` for more details.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be marked compute at root, which can be specified by the integer index,
Operation, or output tensor of the stage.
Notes
-----
After compute_root, we need careful dependency analysis to compute the accurate bound
information. However, it is relatively expensive and complicated, so we just fill "None"
as bound for the newly created iterators.
Call ComputeDAG::InferBound on the returned state to get the complete bound information.
"""
self.state_object = _ffi_api.StateComputeRoot(
self.state_object, self._resolve_stage_id(stage)
)
def cache_read(self, stage, scope_name, reader_stages):
"""Schedule primitive corresponding to `te.Schedule.cache_read`.
See also the `te.Schedule` for more details.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be cache_read, which can be specified by the integer index, Operation,
or output tensor of the stage.
scope_name : str
The scope name of the newly added read stage.
reader_stages : List[Union[int, Operation, Tensor]]
The reader stages. Each of the list can be specified by the integer index, Operation,
or output tensor of the stage.
Returns
-------
new_stage_op : Operator
The Operator of the new added stage.
Notes
-----
Cache read step will insert an extra stage to the original ComputeDAG (at the back of the
target stage).
"""
reader_stage_ids = [self._resolve_stage_id(i) for i in reader_stages]
self.state_object, new_stage_id = _ffi_api.StateCacheRead(
self.state_object,
self._resolve_stage_id(stage),
scope_name,
reader_stage_ids,
self.compute_dag,
)
# Add a new stage will change all ops behind the added stage. But we still want to keep the
# original ops map, apply stage id offset to stage_id_map to make them work.
self._apply_stage_id_offset(int(new_stage_id))
self._update_stage_id_map()
return self.stages[int(new_stage_id)].op
def cache_write(self, stage, scope_name):
"""Schedule primitive corresponding to `te.Schedule.cache_write`.
See also the `te.Schedule` for more details.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be cache_write, which can be specified by the integer index, Operation,
or output tensor of the stage.
scope_name : str
The scope name of the newly added compute stage.
Returns
-------
new_stage_op : Operator
The Operator of the new added stage.
Notes
-----
Cache write step will insert an extra stage to the original ComputeDAG (in the front of the
target stage).
This step will cache write all output tensors of the target stage.
"""
self.state_object, new_stage_id = _ffi_api.StateCacheWrite(
self.state_object, self._resolve_stage_id(stage), scope_name, self.compute_dag
)
# Add a new stage will change all ops behind the added stage. But we still want to keep the
# original ops map, apply stage id offset to stage_id_map to make them work.
self._apply_stage_id_offset(int(new_stage_id))
self._update_stage_id_map()
return self.stages[int(new_stage_id)].op
def rfactor(self, stage, iterator, factor_iter_id):
"""Schedule primitive corresponding to `te.Schedule.rfactor`.
See also the `te.Schedule` for more details.
Parameters
----------
stage : Union[int, Operation, Tensor]
The Stage to be factored, which can be specified by the integer index, Operation,
or output tensor of the stage.
iterator : Iterator
The reduction iterator to be factored.
factor_iter_id : int
The position where the new iterator is placed.
Returns
-------
new_stage_op : Operator
The Operator of the new added stage.
Notes
-----
Rfactor step will insert an extra stage to the original ComputeDAG (in the front of the
target stage).
"""
self.state_object, new_stage_id = _ffi_api.StateRfactor(
self.state_object,
self._resolve_stage_id(stage),
iterator,
factor_iter_id,
self.compute_dag,
)
# Add a new stage will change all ops behind the added stage. But we still want to keep the
# original ops map, apply stage id offset to stage_id_map to make them work.
self._apply_stage_id_offset(int(new_stage_id))
self._update_stage_id_map()
return self.stages[int(new_stage_id)].op
def copy(self):
""" Do deep copy of this State. """
state = State(self.state_object, self.compute_dag)
state.stage_id_map = self.stage_id_map.copy()
return state
def _resolve_stage_id(self, stage_id):
if isinstance(stage_id, Operation):
return self.stage_id_map[stage_id]
if isinstance(stage_id, Tensor):
return self.stage_id_map[stage_id.op]
if isinstance(stage_id, int):
return stage_id
raise ValueError(
"Invalid stage: " + stage_id + " . Expect to be a int, Operation or Tensor"
)
def _update_stage_id_map(self):
for index, stage in enumerate(self.stages):
self.stage_id_map[stage.op] = index
def _apply_stage_id_offset(self, start_id, offset=1):
for key, value in self.stage_id_map.items():
if value >= start_id:
self.stage_id_map[key] = value + offset
def __getitem__(self, key):
if isinstance(key, Tensor):
key = key.op
if isinstance(key, Operation):
return self.stages[self.stage_id_map[key]]
raise ValueError("Invalid item: " + key + " . Expect to be a Operation or Tensor")
def __str__(self):
return str(self.state_object)
def __eq__(self, other):
return _ffi_api.StateEqual(self.state_object, other.state_object)
|
puzan/ansible | refs/heads/devel | lib/ansible/modules/cloud/ovirt/ovirt_vms_facts.py | 8 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: ovirt_vms_facts
short_description: Retrieve facts about one or more oVirt virtual machines
author: "Ondra Machacek (@machacekondra)"
version_added: "2.3"
description:
- "Retrieve facts about one or more oVirt virtual machines."
notes:
- "This module creates a new top-level C(ovirt_vms) fact, which
contains a list of virtual machines."
options:
pattern:
description:
- "Search term which is accepted by oVirt search backend."
- "For example to search VM X from cluster Y use following pattern:
name=X and cluster=Y"
all_content:
description:
- "If I(true) all the attributes of the virtual machines should be
included in the response."
case_sensitive:
description:
- "If I(true) performed search will take case into account."
max:
description:
- "The maximum number of results to return."
extends_documentation_fragment: ovirt_facts
'''
EXAMPLES = '''
# Examples don't contain auth parameter for simplicity,
# look at ovirt_auth module to see how to reuse authentication:
# Gather facts about all VMs which names start with C(centos) and
# belong to cluster C(west):
- ovirt_vms_facts:
pattern: name=centos* and cluster=west
- debug:
var: ovirt_vms
'''
RETURN = '''
ovirt_vms:
description: "List of dictionaries describing the VMs. VM attribues are mapped to dictionary keys,
all VMs attributes can be found at following url: https://ovirt.example.com/ovirt-engine/api/model#types/vm."
returned: On success.
type: list
'''
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
check_sdk,
create_connection,
get_dict_of_struct,
ovirt_facts_full_argument_spec,
)
def main():
argument_spec = ovirt_facts_full_argument_spec(
pattern=dict(default='', required=False),
all_content=dict(default=False, type='bool'),
case_sensitive=dict(default=True, type='bool'),
max=dict(default=None, type='int'),
)
module = AnsibleModule(argument_spec)
check_sdk(module)
try:
auth = module.params.pop('auth')
connection = create_connection(auth)
vms_service = connection.system_service().vms_service()
vms = vms_service.list(
search=module.params['pattern'],
all_content=module.params['all_content'],
case_sensitive=module.params['case_sensitive'],
max=module.params['max'],
)
module.exit_json(
changed=False,
ansible_facts=dict(
ovirt_vms=[
get_dict_of_struct(
struct=c,
connection=connection,
fetch_nested=module.params.get('fetch_nested'),
attributes=module.params.get('nested_attributes'),
) for c in vms
],
),
)
except Exception as e:
module.fail_json(msg=str(e), exception=traceback.format_exc())
finally:
connection.close(logout=auth.get('token') is None)
if __name__ == '__main__':
main()
|
zhujiangang/shadowsocks | refs/heads/master | tests/graceful_cli.py | 977 | #!/usr/bin/python
import socks
import time
SERVER_IP = '127.0.0.1'
SERVER_PORT = 8001
if __name__ == '__main__':
s = socks.socksocket()
s.set_proxy(socks.SOCKS5, SERVER_IP, 1081)
s.connect((SERVER_IP, SERVER_PORT))
s.send(b'test')
time.sleep(30)
s.close()
|
jonnary/keystone | refs/heads/master | keystone/contrib/endpoint_filter/backends/sql.py | 8 | # Copyright 2013 OpenStack Foundation
#
# 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 keystone.common import sql
from keystone.contrib import endpoint_filter
from keystone import exception
from keystone.i18n import _
class ProjectEndpoint(sql.ModelBase, sql.ModelDictMixin):
"""project-endpoint relationship table."""
__tablename__ = 'project_endpoint'
attributes = ['endpoint_id', 'project_id']
endpoint_id = sql.Column(sql.String(64),
primary_key=True,
nullable=False)
project_id = sql.Column(sql.String(64),
primary_key=True,
nullable=False)
class EndpointGroup(sql.ModelBase, sql.ModelDictMixin):
"""Endpoint Groups table."""
__tablename__ = 'endpoint_group'
attributes = ['id', 'name', 'description', 'filters']
mutable_attributes = frozenset(['name', 'description', 'filters'])
id = sql.Column(sql.String(64), primary_key=True)
name = sql.Column(sql.String(255), nullable=False)
description = sql.Column(sql.Text, nullable=True)
filters = sql.Column(sql.JsonBlob(), nullable=False)
class ProjectEndpointGroupMembership(sql.ModelBase, sql.ModelDictMixin):
"""Project to Endpoint group relationship table."""
__tablename__ = 'project_endpoint_group'
attributes = ['endpoint_group_id', 'project_id']
endpoint_group_id = sql.Column(sql.String(64),
sql.ForeignKey('endpoint_group.id'),
nullable=False)
project_id = sql.Column(sql.String(64), nullable=False)
__table_args__ = (sql.PrimaryKeyConstraint('endpoint_group_id',
'project_id'), {})
class EndpointFilter(endpoint_filter.EndpointFilterDriverV8):
@sql.handle_conflicts(conflict_type='project_endpoint')
def add_endpoint_to_project(self, endpoint_id, project_id):
session = sql.get_session()
with session.begin():
endpoint_filter_ref = ProjectEndpoint(endpoint_id=endpoint_id,
project_id=project_id)
session.add(endpoint_filter_ref)
def _get_project_endpoint_ref(self, session, endpoint_id, project_id):
endpoint_filter_ref = session.query(ProjectEndpoint).get(
(endpoint_id, project_id))
if endpoint_filter_ref is None:
msg = _('Endpoint %(endpoint_id)s not found in project '
'%(project_id)s') % {'endpoint_id': endpoint_id,
'project_id': project_id}
raise exception.NotFound(msg)
return endpoint_filter_ref
def check_endpoint_in_project(self, endpoint_id, project_id):
session = sql.get_session()
self._get_project_endpoint_ref(session, endpoint_id, project_id)
def remove_endpoint_from_project(self, endpoint_id, project_id):
session = sql.get_session()
endpoint_filter_ref = self._get_project_endpoint_ref(
session, endpoint_id, project_id)
with session.begin():
session.delete(endpoint_filter_ref)
def list_endpoints_for_project(self, project_id):
session = sql.get_session()
query = session.query(ProjectEndpoint)
query = query.filter_by(project_id=project_id)
endpoint_filter_refs = query.all()
return [ref.to_dict() for ref in endpoint_filter_refs]
def list_projects_for_endpoint(self, endpoint_id):
session = sql.get_session()
query = session.query(ProjectEndpoint)
query = query.filter_by(endpoint_id=endpoint_id)
endpoint_filter_refs = query.all()
return [ref.to_dict() for ref in endpoint_filter_refs]
def delete_association_by_endpoint(self, endpoint_id):
session = sql.get_session()
with session.begin():
query = session.query(ProjectEndpoint)
query = query.filter_by(endpoint_id=endpoint_id)
query.delete(synchronize_session=False)
def delete_association_by_project(self, project_id):
session = sql.get_session()
with session.begin():
query = session.query(ProjectEndpoint)
query = query.filter_by(project_id=project_id)
query.delete(synchronize_session=False)
def create_endpoint_group(self, endpoint_group_id, endpoint_group):
session = sql.get_session()
with session.begin():
endpoint_group_ref = EndpointGroup.from_dict(endpoint_group)
session.add(endpoint_group_ref)
return endpoint_group_ref.to_dict()
def _get_endpoint_group(self, session, endpoint_group_id):
endpoint_group_ref = session.query(EndpointGroup).get(
endpoint_group_id)
if endpoint_group_ref is None:
raise exception.EndpointGroupNotFound(
endpoint_group_id=endpoint_group_id)
return endpoint_group_ref
def get_endpoint_group(self, endpoint_group_id):
session = sql.get_session()
endpoint_group_ref = self._get_endpoint_group(session,
endpoint_group_id)
return endpoint_group_ref.to_dict()
def update_endpoint_group(self, endpoint_group_id, endpoint_group):
session = sql.get_session()
with session.begin():
endpoint_group_ref = self._get_endpoint_group(session,
endpoint_group_id)
old_endpoint_group = endpoint_group_ref.to_dict()
old_endpoint_group.update(endpoint_group)
new_endpoint_group = EndpointGroup.from_dict(old_endpoint_group)
for attr in EndpointGroup.mutable_attributes:
setattr(endpoint_group_ref, attr,
getattr(new_endpoint_group, attr))
return endpoint_group_ref.to_dict()
def delete_endpoint_group(self, endpoint_group_id):
session = sql.get_session()
endpoint_group_ref = self._get_endpoint_group(session,
endpoint_group_id)
with session.begin():
self._delete_endpoint_group_association_by_endpoint_group(
session, endpoint_group_id)
session.delete(endpoint_group_ref)
def get_endpoint_group_in_project(self, endpoint_group_id, project_id):
session = sql.get_session()
ref = self._get_endpoint_group_in_project(session,
endpoint_group_id,
project_id)
return ref.to_dict()
@sql.handle_conflicts(conflict_type='project_endpoint_group')
def add_endpoint_group_to_project(self, endpoint_group_id, project_id):
session = sql.get_session()
with session.begin():
# Create a new Project Endpoint group entity
endpoint_group_project_ref = ProjectEndpointGroupMembership(
endpoint_group_id=endpoint_group_id, project_id=project_id)
session.add(endpoint_group_project_ref)
def _get_endpoint_group_in_project(self, session,
endpoint_group_id, project_id):
endpoint_group_project_ref = session.query(
ProjectEndpointGroupMembership).get((endpoint_group_id,
project_id))
if endpoint_group_project_ref is None:
msg = _('Endpoint Group Project Association not found')
raise exception.NotFound(msg)
else:
return endpoint_group_project_ref
def list_endpoint_groups(self):
session = sql.get_session()
query = session.query(EndpointGroup)
endpoint_group_refs = query.all()
return [e.to_dict() for e in endpoint_group_refs]
def list_endpoint_groups_for_project(self, project_id):
session = sql.get_session()
query = session.query(ProjectEndpointGroupMembership)
query = query.filter_by(project_id=project_id)
endpoint_group_refs = query.all()
return [ref.to_dict() for ref in endpoint_group_refs]
def remove_endpoint_group_from_project(self, endpoint_group_id,
project_id):
session = sql.get_session()
endpoint_group_project_ref = self._get_endpoint_group_in_project(
session, endpoint_group_id, project_id)
with session.begin():
session.delete(endpoint_group_project_ref)
def list_projects_associated_with_endpoint_group(self, endpoint_group_id):
session = sql.get_session()
query = session.query(ProjectEndpointGroupMembership)
query = query.filter_by(endpoint_group_id=endpoint_group_id)
endpoint_group_refs = query.all()
return [ref.to_dict() for ref in endpoint_group_refs]
def _delete_endpoint_group_association_by_endpoint_group(
self, session, endpoint_group_id):
query = session.query(ProjectEndpointGroupMembership)
query = query.filter_by(endpoint_group_id=endpoint_group_id)
query.delete()
def delete_endpoint_group_association_by_project(self, project_id):
session = sql.get_session()
with session.begin():
query = session.query(ProjectEndpointGroupMembership)
query = query.filter_by(project_id=project_id)
query.delete()
|
frederick-masterton/django | refs/heads/master | django/contrib/auth/tests/utils.py | 220 | from unittest import skipIf
from django.conf import settings
def skipIfCustomUser(test_func):
"""
Skip a test if a custom user model is in use.
"""
return skipIf(settings.AUTH_USER_MODEL != 'auth.User', 'Custom user model in use')(test_func)
|
adw0rd/lettuce | refs/heads/master | tests/integration/lib/Django-1.3/tests/regressiontests/file_uploads/models.py | 110 | import tempfile
import os
from django.db import models
from django.core.files.storage import FileSystemStorage
temp_storage = FileSystemStorage(tempfile.mkdtemp())
UPLOAD_TO = os.path.join(temp_storage.location, 'test_upload')
class FileModel(models.Model):
testfile = models.FileField(storage=temp_storage, upload_to='test_upload')
|
uskudnik/ggrc-core | refs/heads/develop | src/tests/ggrc/converters/helpers.py | 2 | import csv
from StringIO import StringIO
CREATED_HEADER_STRING = 'Created'
UPDATED_HEADER_STRING = 'Updated'
HEADER_ROW_INDEX = 4
class AbstractCSV(object):
def __init__(self, s):
# (nested) list representation of csv object
csv_obj = csv.reader(StringIO(s))
self.list_rep = [line for line in csv_obj]
created_col = self.list_rep[HEADER_ROW_INDEX].index(
CREATED_HEADER_STRING)
updated_col = self.list_rep[HEADER_ROW_INDEX].index(
UPDATED_HEADER_STRING)
# columns to ignore
self.excludes = (created_col, updated_col)
def compare_csvs(abs_csv1, abs_csv2):
for x, row in enumerate(abs_csv1.list_rep):
for y, cell in enumerate(row):
# check for match if not in one of the excluded columns
if y not in abs_csv1.excludes:
cell1 = abs_csv1.list_rep[x][y]
try:
row2 = abs_csv2.list_rep[x]
except IndexError:
# second sheet must be missing row
return ("Row {0}".format(x), None)
try:
cell2 = row2[y]
except IndexError:
# second sheet must be missing column
return ((x, y), None)
if cell1 != cell2:
return (cell1, cell2)
return True
|
onecodex/onecodex | refs/heads/master | onecodex/vendored/potion_client/auth.py | 2 | from requests.auth import AuthBase
class HTTPBearerAuth(AuthBase):
"""Attaches HTTP Basic Authentication to the given Request object."""
def __init__(self, token):
self.token = token
def __call__(self, r):
r.headers['Authorization'] = 'Bearer {}'.format(self.token)
return r
|
thaim/ansible | refs/heads/fix-broken-link | lib/ansible/modules/network/aos/_aos_blueprint.py | 348 | #!/usr/bin/python
#
# (c) 2017 Apstra Inc, <community@apstra.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['removed'],
'supported_by': 'community'}
from ansible.module_utils.common.removed import removed_module
if __name__ == '__main__':
removed_module(removed_in='2.9')
|
sogelink/ansible | refs/heads/devel | lib/ansible/modules/windows/win_eventlog_entry.py | 47 | #!/usr/bin/python
# (c) 2017, Andrew Saraceni <andrew.saraceni@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_eventlog_entry
version_added: "2.4"
short_description: Write entries to Windows event logs
description:
- Write log entries to a given event log from a specified source.
options:
log:
description:
- Name of the event log to write an entry to.
required: true
source:
description:
- Name of the log source to indicate where the entry is from.
required: true
event_id:
description:
- The numeric event identifier for the entry.
- Value must be between 0 and 65535.
required: true
message:
description:
- The message for the given log entry.
required: true
entry_type:
description:
- Indicates the entry being written to the log is of a specific type.
choices:
- Error
- FailureAudit
- Information
- SuccessAudit
- Warning
category:
description:
- A numeric task category associated with the category message file for the log source.
raw_data:
description:
- Binary data associated with the log entry.
- Value must be a comma-separated array of 8-bit unsigned integers (0 to 255).
notes:
- This module will always report a change when writing an event entry.
author:
- Andrew Saraceni (@andrewsaraceni)
'''
EXAMPLES = r'''
- name: Write an entry to a Windows event log
win_eventlog_entry:
log: MyNewLog
source: NewLogSource1
event_id: 1234
message: This is a test log entry.
- name: Write another entry to a different Windows event log
win_eventlog_entry:
log: AnotherLog
source: MyAppSource
event_id: 5000
message: An error has occurred.
entry_type: Error
category: 5
raw_data: 10,20
'''
RETURN = r'''
# Default return values
'''
|
sabi0/intellij-community | refs/heads/master | python/lib/Lib/site-packages/django/contrib/gis/db/models/sql/where.py | 309 | from django.db.models.fields import Field, FieldDoesNotExist
from django.db.models.sql.constants import LOOKUP_SEP
from django.db.models.sql.expressions import SQLEvaluator
from django.db.models.sql.where import Constraint, WhereNode
from django.contrib.gis.db.models.fields import GeometryField
class GeoConstraint(Constraint):
"""
This subclass overrides `process` to better handle geographic SQL
construction.
"""
def __init__(self, init_constraint):
self.alias = init_constraint.alias
self.col = init_constraint.col
self.field = init_constraint.field
def process(self, lookup_type, value, connection):
if isinstance(value, SQLEvaluator):
# Make sure the F Expression destination field exists, and
# set an `srid` attribute with the same as that of the
# destination.
geo_fld = GeoWhereNode._check_geo_field(value.opts, value.expression.name)
if not geo_fld:
raise ValueError('No geographic field found in expression.')
value.srid = geo_fld.srid
db_type = self.field.db_type(connection=connection)
params = self.field.get_db_prep_lookup(lookup_type, value, connection=connection)
return (self.alias, self.col, db_type), params
class GeoWhereNode(WhereNode):
"""
Used to represent the SQL where-clause for spatial databases --
these are tied to the GeoQuery class that created it.
"""
def add(self, data, connector):
if isinstance(data, (list, tuple)):
obj, lookup_type, value = data
if ( isinstance(obj, Constraint) and
isinstance(obj.field, GeometryField) ):
data = (GeoConstraint(obj), lookup_type, value)
super(GeoWhereNode, self).add(data, connector)
def make_atom(self, child, qn, connection):
lvalue, lookup_type, value_annot, params_or_value = child
if isinstance(lvalue, GeoConstraint):
data, params = lvalue.process(lookup_type, params_or_value, connection)
spatial_sql = connection.ops.spatial_lookup_sql(data, lookup_type, params_or_value, lvalue.field, qn)
return spatial_sql, params
else:
return super(GeoWhereNode, self).make_atom(child, qn, connection)
@classmethod
def _check_geo_field(cls, opts, lookup):
"""
Utility for checking the given lookup with the given model options.
The lookup is a string either specifying the geographic field, e.g.
'point, 'the_geom', or a related lookup on a geographic field like
'address__point'.
If a GeometryField exists according to the given lookup on the model
options, it will be returned. Otherwise returns None.
"""
# This takes into account the situation where the lookup is a
# lookup to a related geographic field, e.g., 'address__point'.
field_list = lookup.split(LOOKUP_SEP)
# Reversing so list operates like a queue of related lookups,
# and popping the top lookup.
field_list.reverse()
fld_name = field_list.pop()
try:
geo_fld = opts.get_field(fld_name)
# If the field list is still around, then it means that the
# lookup was for a geometry field across a relationship --
# thus we keep on getting the related model options and the
# model field associated with the next field in the list
# until there's no more left.
while len(field_list):
opts = geo_fld.rel.to._meta
geo_fld = opts.get_field(field_list.pop())
except (FieldDoesNotExist, AttributeError):
return False
# Finally, make sure we got a Geographic field and return.
if isinstance(geo_fld, GeometryField):
return geo_fld
else:
return False
|
ofir123/CouchPotatoServer | refs/heads/master | libs/pyutil/scripts/time_comparisons.py | 92 | # If you run this file, it will make up a random secret and then crack it
# using timing information from a string comparison function. Maybe--if it
# gets lucky. It takes a long, long time to work.
# So, the thing I need help with is statistics. The way this thing works is
# extremely stupid. Suppose you want to know which function invocation takes
# longer: comparison(secret, guess1) or comparison(secret, guess2)?
# If you can correctly determine that one of them takes longer than the
# other, then (a) you can use that to crack the secret, and (b) this is a
# unit test demonstrating that comparison() is not timing-safe.
# So how does this script do it? Extremely stupidly. First of all, you can't
# reliably measure tiny times, so to measure the time that a function takes,
# we run that function 10,000 times in a row, measure how long that took, and
# divide by 10,000 to estimate how long any one run would have taken.
# Then, we do that 100 times in a row, and take the fastest of 100 runs. (I
# also experimented with taking the mean of 100 runs instead of the fastest.)
# Then, we just say whichever comparison took longer (for its fastest run of
# 100 runs of 10,000 executions per run) is the one we think is a closer
# guess to the secret.
# Now I would *like* to think that there is some kind of statistical analysis
# more sophisticated than "take the slowest of the fastest of 100 runs of
# 10,000 executions". Such improved statistical analysis would hopefully be
# able to answer these two questions:
# 1. Are these two function calls -- comparison(secret, guess1) and
# comparison(secret, guess2) -- drawing from the same distribution or
# different? If you can answer that question, then you've answered the
# question of whether "comparison" is timing-safe or not.
# And, this would also allow the cracker to recover from a false step. If it
# incorrectly decides the the prefix of the secret is ABCX, when the real
# secret is ABCD, then after that every next step it takes will be the
# "drawing from the same distribution" kind -- any difference between ABCXQ
# and ABCXR will be just due to noise, since both are equally far from the
# correct answer, which startsw with ABCD. If it could realize that there is
# no real difference between the distributions, then it could back-track and
# recover.
# 2. Giving the ability to measure, noisily, the time taken by comparison(),
# how can you most efficiently figure out which guess takes the longest? If
# you can do that more efficiently, you can crack secrets more efficiently.
# The script takes two arguments. The first is how many symbols in the
# secret, and the second is how big the alphabet from which the symbols are
# drawn. To prove that this script can *ever* work, try passing length 5 and
# alphabet size 2. Also try editing the code to let is use sillycomp. That'll
# definitely make it work. If you can improve this script (as per the thing
# above about "needing better statistics") to the degree that it can crack a
# secret with length 32 and alphabet size 256, then that would be awesome.
# See the result of this commandline:
# $ python -c 'import time_comparisons ; time_comparisons.print_measurements()'
from pyutil import benchutil
import hashlib, random, os
from decimal import Decimal
D=Decimal
p1 = 'a'*32
p1a = 'a'*32
p2 = 'a'*31+'b' # close, but no cigar
p3 = 'b'*32 # different in the first byte
def randstr(n, alphabetsize):
alphabet = [ chr(x) for x in range(alphabetsize) ]
return ''.join([random.choice(alphabet) for i in range(n)])
def compare(n, f, a, b):
for i in xrange(n):
f(a, b)
def eqeqcomp(a, b):
return a == b
def sillycomp(a, b):
# This exposes a lot of information in its timing about how many leading bytes match.
for i in range(len(a)):
if a[i] != b[i]:
return False
for i in xrange(2**9):
pass
if len(a) == len(b):
return True
else:
return False
def hashcomp(a, b):
# Brian Warner invented this for Tahoe-LAFS. It seems like it should be very safe agaist timing leakage of any kind, because of the inclusion of a new random randkey every time. Note that exposing the value of the hash (i.e. the output of md5(randkey+secret)) is *not* a security problem. You can post that on your web site and let all attackers have it, no problem. (Provided that the value of "randkey" remains secret.)
randkey = os.urandom(32)
return hashlib.md5(randkey+ a).digest() == hashlib.md5(randkey+b).digest()
def xorcomp(a, b):
# This appears to be the most popular timing-insensitive string comparison function. I'm not completely sure it is fully timing-insensitive. (There are all sorts of funny things inside Python, such as caching of integer objects < 100...)
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
def print_measurements():
N=10**4
REPS=10**2
print "all times are in nanoseconds per comparison (in scientific notation)"
print
for comparator in [eqeqcomp, hashcomp, xorcomp, sillycomp]:
print "using comparator ", comparator
# for (a, b, desc) in [(p1, p1a, 'same'), (p1, p2, 'close'), (p1, p3, 'far')]:
trials = [(p1, p1a, 'same'), (p1, p2, 'close'), (p1, p3, 'far')]
random.shuffle(trials)
for (a, b, desc) in trials:
print "comparing two strings that are %s to each other" % (desc,)
def f(n):
compare(n, comparator, a, b)
benchutil.rep_bench(f, N, UNITS_PER_SECOND=10**9, MAXREPS=REPS)
print
def try_to_crack_secret(cracker, comparator, secretlen, alphabetsize):
secret = randstr(secretlen, alphabetsize)
def test_guess(x):
return comparator(secret, x)
print "Giving cracker %s a chance to figure out the secret. Don't tell him, but the secret is %s. Whenever he makes a guess, we'll use comparator %s to decide if his guess is right ..." % (cracker, secret.encode('hex'), comparator,)
guess = cracker(test_guess, secretlen, alphabetsize)
print "Cracker %s guessed %r" % (cracker, guess,)
if guess == secret:
print "HE FIGURED IT OUT!? HOW DID HE DO THAT."
else:
print "HAHA. Our secret is safe."
def byte_at_a_time_cracker(test_guess, secretlen, alphabetsize):
# If we were cleverer, we'd add some backtracking behaviour where, if we can't find any x such that ABCx stands out from the crowd as taking longer than all the other ABCy's, then we start to think that we've taken a wrong step and we go back to trying ABy's. Make sense? But we're not that clever. Once we take a step, we don't backtrack.
print
guess=[]
while len(guess) < secretlen:
best_next_byte = None
best_next_byte_time = None
# For each possible byte...
for next_byte in range(alphabetsize):
c = chr(next_byte)
# Construct a guess with our best candidate so far...
candidate_guess = guess[:]
# Plus that byte...
candidate_guess.append(c)
s = ''.join(candidate_guess)
# Plus random bytes...
s += os.urandom(32 - len(s))
# And see how long it takes the test_guess to consider it...
def f(n):
for i in xrange(n):
test_guess(s)
times = benchutil.rep_bench(f, 10**7, MAXREPS=10**3, quiet=True)
fastesttime = times['mean']
print "%s..."%(c.encode('hex'),),
if best_next_byte is None or fastesttime > best_next_byte_time:
print "new candidate for slowest next-char: %s, took: %s" % (c.encode('hex'), fastesttime,),
best_next_byte_time = fastesttime
best_next_byte = c
# Okay we've tried all possible next bytes. Our guess is this one (the one that took longest to be tested by test_guess):
guess.append(best_next_byte)
print "SLOWEST next-char %s! Current guess at secret: %s" % (best_next_byte.encode('hex'), ''.join(guess).encode('hex'),)
guess = ''.join(guess)
print "Our guess for the secret: %r" % (guess,)
return guess
if __name__ == '__main__':
import sys
secretlen = int(sys.argv[1])
alphabetsize = int(sys.argv[2])
if alphabetsize > 256:
raise Exception("We assume we can fit one element of the alphabet into a byte.")
print "secretlen: %d, alphabetsize: %d" % (secretlen, alphabetsize,)
# try_to_crack_secret(byte_at_a_time_cracker, sillycomp, secretlen, alphabetsize)
try_to_crack_secret(byte_at_a_time_cracker, eqeqcomp, secretlen, alphabetsize)
|
PowerDNS/exabgp | refs/heads/master | lib/exabgp/bgp/message/update/nlri/evpn/multicast.py | 2 | """
multicast.py
Created by Thomas Morin on 2014-06-23.
Copyright (c) 2014-2014 Orange. All rights reserved.
"""
from exabgp.protocol.ip import IP
from exabgp.bgp.message.update.nlri.qualifier.rd import RouteDistinguisher
from exabgp.bgp.message.update.nlri.qualifier.etag import EthernetTag
from exabgp.bgp.message.update.nlri.evpn.nlri import EVPN
# ===================================================================== EVPNNLRI
# +---------------------------------------+
# | RD (8 octets) |
# +---------------------------------------+
# | Ethernet Tag ID (4 octets) |
# +---------------------------------------+
# | IP Address Length (1 octet) |
# +---------------------------------------+
# | Originating Router's IP Addr |
# | (4 or 16 octets) |
# +---------------------------------------+
class Multicast (EVPN):
CODE = 3
NAME = "Inclusive Multicast Ethernet Tag"
SHORT_NAME = "Multicast"
def __init__(self,rd,etag,ip):
self.rd = rd
self.etag = etag
self.ip = ip
EVPN.__init__(self,self.pack())
def __str__ (self):
return "%s:%s:%s:%s" % (
self._prefix(),
self.rd,
self.etag,
self.ip,
)
def __cmp__(self,other):
if not isinstance(other,self.__class__):
return -1
if self.rd != other.rd:
return -1
if self.etag != other.etag:
return -1
if self.ip != other.ip:
return -1
return 0
# XXX: FIXME: improve for better performance?
def __hash__(self):
return hash("%s:%s:%s:%s:%s:%s" % (self.afi,self.safi,self.subtype,self.rd,self.etag,self.ip))
def pack (self):
ip = self.ip.pack()
return '%s%s%s%s' % (
self.rd.pack(),
self.etag.pack(),
chr(len(ip)),
ip
)
@classmethod
def unpack(cls,data):
rd = RouteDistinguisher.unpack(data[:8])
etag = EthernetTag.unpack(data[8:12])
iplen = ord(data[12])
ip = IP.unpack(data[12:12+iplen])
if iplen not in (4,16):
raise Exception("IP len is %d, but EVPN route currently support only IPv4" % iplen)
return cls(rd,etag,ip)
Multicast.register_evpn()
|
kierangraham/dotfiles | refs/heads/master | Sublime/Packages/SublimeCodeIntel/libs/codeintel2/util.py | 6 | #!python
# encoding: utf-8
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is Komodo code.
#
# The Initial Developer of the Original Code is ActiveState Software Inc.
# Portions created by ActiveState Software Inc are Copyright (C) 2000-2007
# ActiveState Software Inc. All Rights Reserved.
#
# Contributor(s):
# ActiveState Software Inc
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
"""Code Intelligence: utility functions"""
import bisect
import os
from os.path import basename
import sys
import re
import stat
import textwrap
import logging
import types
from pprint import pprint, pformat
import time
import codecs
# Global dict for holding specific hotshot profilers
hotshotProfilers = {}
#---- general stuff
def isident(char):
char = ord(char)
return ord('a') <= char <= ord('z') or ord('A') <= char <= ord('Z') or char == ord('_')
def isdigit(char):
char = ord(char)
return ord('0') <= char <= ord('9')
# A "safe" language name for the given language where safe generally
# means safe for a file path.
_safe_lang_from_lang_cache = {
"C++": "cpp",
}
def safe_lang_from_lang(lang):
global _safe_lang_from_lang_cache
try:
return _safe_lang_from_lang_cache[lang]
except KeyError:
safe_lang = lang.lower().replace(' ', '_')
_safe_lang_from_lang_cache[lang] = safe_lang
return safe_lang
# @deprecated: Manager.buf_from_path now uses textinfo to guess lang.
def guess_lang_from_path(path):
lang_from_ext = {
".py": "Python",
".pl": "Perl",
".pm": "Perl",
".tcl": "Tcl",
".php": "PHP",
".inc": "PHP",
".rb": "Ruby",
".rhtml": "RHTML",
".html.erb": "RHTML",
".js": "JavaScript",
".java": "Java",
".css": "CSS",
".xul": "XUL",
".xbl": "XBL",
".html": "HTML",
".xml": "XML",
".tpl": "Smarty",
".django.html": "Django",
".mason.html": "Mason",
".ttkt.html": "TemplateToolkit",
".cxx": "C++",
}
idx = 0
base = basename(path)
while base.find('.', idx) != -1:
idx = base.find('.', idx)
if idx == -1:
break
ext = base[idx:]
if ext in lang_from_ext:
return lang_from_ext[ext]
idx += 1
from codeintel2.common import CodeIntelError
raise CodeIntelError("couldn't guess lang for `%s'" % path)
def gen_dirs_under_dirs(dirs, max_depth, interesting_file_patterns=None,
skip_scc_control_dirs=True):
"""Generate all dirs under the given dirs (including the given dirs
themselves).
"max_depth" is an integer maximum number of sub-directories that
this method with recurse.
"file_patterns", if given, is a sequence of glob patterns for
"interesting" files. Directories with no interesting files are
not included (though sub-directories of these may be).
"skip_scc_control_dirs" is a boolean (default True) indicating if
svn and cvs control dirs should be skipped.
"""
from os.path import normpath, abspath, expanduser
from fnmatch import fnmatch
dirs_to_skip = (skip_scc_control_dirs
and ["CVS", ".svn", ".hg", ".git", ".bzr"] or [])
# We must keep track of the directories we have walked, as the list of dirs
# can overlap - bug 90289.
walked_these_dirs = {}
for dir in dirs:
norm_dir = normpath(abspath(expanduser(dir)))
LEN_DIR = len(norm_dir)
for dirpath, dirnames, filenames in walk2(norm_dir):
if dirpath in walked_these_dirs:
dirnames[:] = [] # Already walked - no need to do it again.
continue
if dirpath[LEN_DIR:].count(os.sep) >= max_depth:
dirnames[:] = [] # hit max_depth
else:
walked_these_dirs[dirpath] = True
for dir_to_skip in dirs_to_skip:
if dir_to_skip in dirnames:
dirnames.remove(dir_to_skip)
if interesting_file_patterns:
for pat, filename in (
(p, f) for p in interesting_file_patterns
for f in filenames):
if fnmatch(filename, pat):
break
else:
# No interesting files in this dir.
continue
yield dirpath
#---- standard module/class/function doc parsing
LINE_LIMIT = 5 # limit full number of lines this number
LINE_WIDTH = 60 # wrap doc summaries to this width
# Examples matches to this pattern:
# foo(args)
# foo(args) -> retval
# foo(args) -- description
# retval = foo(args)
# retval = foo(args) -- description
_gPySigLinePat = re.compile(
r"^((?P<retval>[^=]+?)\s*=|class)?\s*(?P<head>[\w\.]+\s?\(.*?\))\s*(?P<sep>[:<>=-]*)\s*(?P<tail>.*)$")
_gSentenceSepPat = re.compile(r"(?<=\.)\s+", re.M) # split on sentence bndry
def parseDocSummary(doclines, limit=LINE_LIMIT, width=LINE_WIDTH):
"""Parse out a short summary from the given doclines.
"doclines" is a list of lines (without trailing newlines) to parse.
"limit" is the number of lines to which to limit the summary.
The "short summary" is the first sentence limited by (1) the "limit"
number of lines and (2) one paragraph. If the first *two* sentences fit
on the first line, then use both. Returns a list of summary lines.
"""
# Skip blank lines.
start = 0
while start < len(doclines):
if doclines[start].strip():
break
start += 1
desclines = []
for i in range(start, len(doclines)):
if len(desclines) >= limit:
break
stripped = doclines[i].strip()
if not stripped:
break
sentences = _gSentenceSepPat.split(stripped)
if sentences and not sentences[-1].endswith('.'):
del sentences[-1] # last bit might not be a complete sentence
if not sentences:
desclines.append(stripped + ' ')
continue
elif i == start and len(sentences) > 1:
desclines.append(' '.join([s.strip() for s in sentences[:2]]))
else:
desclines.append(sentences[0].strip())
break
if desclines:
if desclines[-1][-1] == ' ':
# If terminated at non-sentence boundary then have extraneous
# trailing space.
desclines[-1] = desclines[-1][:-1]
desclines = textwrap.wrap(''.join(desclines), width)
return desclines
def parsePyFuncDoc(doc, fallbackCallSig=None, scope="?", funcname="?"):
"""Parse the given Python function/method doc-string into call-signature
and description bits.
"doc" is the function doc string.
"fallbackCallSig" (optional) is a list of call signature lines to
fallback to if one cannot be determined from the doc string.
"scope" (optional) is the module/class parent scope name. This
is just used for better error/log reporting.
"funcname" (optional) is the function name. This is just used for
better error/log reporting.
Examples of doc strings with call-signature info:
close(): explicitly release resources held.
x.__repr__() <==> repr(x)
read([s]) -- Read s characters, or the rest of the string
recv(buffersize[, flags]) -> data
replace (str, old, new[, maxsplit]) -> string
class StringIO([buffer])
Returns a 2-tuple: (<call-signature-lines>, <description-lines>)
"""
if doc is None or not doc.strip():
return ([], [])
limit = LINE_LIMIT
if not isinstance(doc, str):
# try to convert from utf8 to unicode; if we fail, too bad.
try:
doc = codecs.utf_8_decode(doc)[0]
except UnicodeDecodeError:
pass
doclines = doc.splitlines(0)
index = 0
siglines = []
desclines = []
# Skip leading blank lines.
while index < len(doclines):
if doclines[index].strip():
break
index += 1
# Parse out the call signature block, if it looks like there is one.
if index >= len(doclines):
match = None
else:
first = doclines[index].strip()
match = _gPySigLinePat.match(first)
if match:
# The 'doc' looks like it starts with a call signature block.
for i, line in enumerate(doclines[index:]):
if len(siglines) >= limit:
index = i
break
stripped = line.strip()
if not stripped:
index = i
break
match = _gPySigLinePat.match(stripped)
if not match:
index = i
break
# Now parse off what may be description content on the same line.
# ":", "-" or "--" separator: tail is description
# "-->" or "->" separator: tail if part of call sig
# "<==>" separator: tail if part of call sig
# other separtor: leave as part of call sig for now
descSeps = ("-", "--", ":")
groupd = match.groupdict()
retval, head, sep, tail = (
groupd.get("retval"), groupd.get("head"),
groupd.get("sep"), groupd.get("tail"))
if retval:
siglines.append(head + " -> " + retval)
if tail and sep in descSeps:
desclines.append(tail)
elif tail and sep in descSeps:
siglines.append(head)
desclines.append(tail)
else:
siglines.append(stripped)
else:
index = len(doclines)
if not siglines and fallbackCallSig:
siglines = fallbackCallSig
# Parse out the description block.
if desclines:
# Use what we have already. Just need to wrap it.
desclines = textwrap.wrap(' '.join(desclines), LINE_WIDTH)
else:
doclines = doclines[index:]
# strip leading empty lines
while len(doclines) > 0 and not doclines[0].rstrip():
del doclines[0]
try:
skip_first_line = (doclines[0][0] not in (" \t"))
except IndexError:
skip_first_line = False # no lines, or first line is empty
desclines = dedent("\n".join(
doclines), skip_first_line=skip_first_line)
desclines = desclines.splitlines(0)
## debug logging
# f = open("parsePyFuncDoc.log", "a")
# if 0:
# f.write("\n---- %s:\n" % funcname)
# f.write(pformat(siglines)+"\n")
# f.write(pformat(desclines)+"\n")
# else:
# f.write("\n")
# if siglines:
# f.write("\n".join(siglines)+"\n")
# else:
# f.write("<no signature for '%s.%s'>\n" % (scope, funcname))
# for descline in desclines:
# f.write("\t%s\n" % descline)
# f.close()
return (siglines, desclines)
#---- debugging utilities
def unmark_text(markedup_text):
"""Parse text with potential markup as follows and return
(<text>, <data-dict>).
"<|>" indicates the current position (pos), defaults to the end
of the text.
"<+>" indicates the trigger position (trg_pos), if present.
"<$>" indicates the start position (start_pos) for some kind of
of processing, if present.
"<N>" is a numbered marker. N can be any of 0-99. These positions
are returned as the associate number key in <data-dict>.
Note that the positions are in UTF-8 byte counts, not character counts.
This matches the behaviour of Scintilla positions.
E.g.:
>>> unmark_text('foo.<|>')
('foo.', {'pos': 4})
>>> unmark_text('foo.<|><+>')
('foo.', {'trg_pos': 4, 'pos': 4})
>>> unmark_text('foo.<+>ba<|>')
('foo.ba', {'trg_pos': 4, 'pos': 6})
>>> unmark_text('fo<|>o.<+>ba')
('foo.ba', {'trg_pos': 4, 'pos': 2})
>>> unmark_text('os.path.join<$>(<|>')
('os.path.join(', {'pos': 13, 'start_pos': 12})
>>> unmark_text('abc<3>defghi<2>jk<4>lm<1>nopqrstuvwxyz')
('abcdefghijklmnopqrstuvwxyz', {1: 13, 2: 9, 3: 3, 4: 11, 'pos': 26})
>>> unmark_text('Ůɳíčóďé<|>')
('Ůɳíčóďé', {'pos': 14})
See the matching markup_text() below.
"""
splitter = re.compile(r"(<(?:[\|\+\$\[\]<]|\d+)>)")
text = "" if isinstance(markup_text, str) else ""
data = {}
posNameFromSymbol = {
"<|>": "pos",
"<+>": "trg_pos",
"<$>": "start_pos",
"<[>": "start_selection",
"<]>": "end_selection",
}
def byte_length(text):
if isinstance(text, str):
return len(text.encode("utf-8"))
return len(text)
bracketed_digits_re = re.compile(r'<\d+>$')
for token in splitter.split(markedup_text):
if token in posNameFromSymbol:
data[posNameFromSymbol[token]] = byte_length(text)
elif token == "<<>": # escape sequence
text += "<"
elif bracketed_digits_re.match(token):
data[int(token[1:-1])] = byte_length(text)
else:
text += token
if "pos" not in data:
data["pos"] = byte_length(text)
# sys.stderr.write(">> text:%r, data:%s\n" % (text, data))
return text, data
def markup_text(text, pos=None, trg_pos=None, start_pos=None):
"""Markup text with position markers.
See the matching unmark_text() above.
"""
positions_and_markers = []
if pos is not None:
positions_and_markers.append((pos, '<|>'))
if trg_pos is not None:
positions_and_markers.append((trg_pos, '<+>'))
if start_pos is not None:
positions_and_markers.append((start_pos, '<$>'))
positions_and_markers.sort()
if not isinstance(text, bytes):
text = text.encode("utf-8")
m_text = ""
m_pos = 0
for position, marker in positions_and_markers:
m_text += text[m_pos:position].decode('utf-8', 'ignore') + marker
m_pos = position
m_text += text[m_pos:].decode('utf-8', 'ignore')
return m_text
def lines_from_pos(unmarked_text, positions):
"""Get 1-based line numbers from positions
@param unmarked_text {str} The text to examine
@param positions {dict or list of int} Byte positions to look up
@returns {dict or list of int} Matching line numbers (1-based)
Given some text and either a list of positions, or a dict containing
positions as values, return a matching data structure with positions
replaced with the line number of the lines the positions are on. Positions
after the last line are assumed to be on a hypothetical line.
E.g.:
Assuming the following text with \n line endings, where each line is
exactly 20 characters long:
>>> text = '''
... line one
... line two
... line three
... '''.lstrip()
>>> lines_from_pos(text, [5, 15, 25, 55, 999])
[1, 1, 2, 3, 4]
>>> lines_from_pos(text, {"hello": 10, "moo": 20, "not": "an int"})
{'moo': 1, 'hello': 1}
"""
lines = str(unmarked_text).splitlines(True)
offsets = [0]
for line in lines:
offsets.append(offsets[-1] + len(line.encode("utf-8")))
try:
# assume a dict
keys = iter(positions.keys())
values = {}
except AttributeError:
# assume a list/tuple
keys = list(range(len(positions)))
values = []
for key in keys:
try:
position = positions[key] - 0
except TypeError:
continue # not a number
line_no = bisect.bisect_left(offsets, position)
try:
values[key] = line_no
except IndexError:
if key == len(values):
values.append(line_no)
else:
raise
return values
# Recipe: banner (1.0.1) in C:\trentm\tm\recipes\cookbook
def banner(text, ch='=', length=78):
"""Return a banner line centering the given text.
"text" is the text to show in the banner. None can be given to have
no text.
"ch" (optional, default '=') is the banner line character (can
also be a short string to repeat).
"length" (optional, default 78) is the length of banner to make.
Examples:
>>> banner("Peggy Sue")
'================================= Peggy Sue =================================='
>>> banner("Peggy Sue", ch='-', length=50)
'------------------- Peggy Sue --------------------'
>>> banner("Pretty pretty pretty pretty Peggy Sue", length=40)
'Pretty pretty pretty pretty Peggy Sue'
"""
if text is None:
return ch * length
elif len(text) + 2 + len(ch) * 2 > length:
# Not enough space for even one line char (plus space) around text.
return text
else:
remain = length - (len(text) + 2)
prefix_len = remain // 2
suffix_len = remain - prefix_len
if len(ch) == 1:
prefix = ch * prefix_len
suffix = ch * suffix_len
else:
prefix = ch * (prefix_len // len(ch)) + ch[:prefix_len % len(ch)]
suffix = ch * (suffix_len // len(ch)) + ch[:suffix_len % len(ch)]
return prefix + ' ' + text + ' ' + suffix
# Recipe: dedent (0.1.2) in C:\trentm\tm\recipes\cookbook
def _dedentlines(lines, tabsize=8, skip_first_line=False):
"""_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines
"lines" is a list of lines to dedent.
"tabsize" is the tab width to use for indent width calculations.
"skip_first_line" is a boolean indicating if the first line should
be skipped for calculating the indent width and for dedenting.
This is sometimes useful for docstrings and similar.
Same as dedent() except operates on a sequence of lines. Note: the
lines list is modified **in-place**.
"""
DEBUG = False
if DEBUG:
print("dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\
% (tabsize, skip_first_line))
indents = []
margin = None
for i, line in enumerate(lines):
if i == 0 and skip_first_line:
continue
indent = 0
for ch in line:
if ch == ' ':
indent += 1
elif ch == '\t':
indent += tabsize - (indent % tabsize)
elif ch in '\r\n':
continue # skip all-whitespace lines
else:
break
else:
continue # skip all-whitespace lines
if DEBUG:
print("dedent: indent=%d: %r" % (indent, line))
if margin is None:
margin = indent
else:
margin = min(margin, indent)
if DEBUG:
print("dedent: margin=%r" % margin)
if margin is not None and margin > 0:
for i, line in enumerate(lines):
if i == 0 and skip_first_line:
continue
removed = 0
for j, ch in enumerate(line):
if ch == ' ':
removed += 1
elif ch == '\t':
removed += tabsize - (removed % tabsize)
elif ch in '\r\n':
if DEBUG:
print("dedent: %r: EOL -> strip up to EOL" % line)
lines[i] = lines[i][j:]
break
else:
raise ValueError("unexpected non-whitespace char %r in "
"line %r while removing %d-space margin"
% (ch, line, margin))
if DEBUG:
print("dedent: %r: %r -> removed %d/%d"\
% (line, ch, removed, margin))
if removed == margin:
lines[i] = lines[i][j+1:]
break
elif removed > margin:
lines[i] = ' '*(removed-margin) + lines[i][j+1:]
break
else:
if removed:
lines[i] = lines[i][removed:]
return lines
def dedent(text, tabsize=8, skip_first_line=False):
"""dedent(text, tabsize=8, skip_first_line=False) -> dedented text
"text" is the text to dedent.
"tabsize" is the tab width to use for indent width calculations.
"skip_first_line" is a boolean indicating if the first line should
be skipped for calculating the indent width and for dedenting.
This is sometimes useful for docstrings and similar.
textwrap.dedent(s), but don't expand tabs to spaces
"""
lines = text.splitlines(1)
_dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line)
return ''.join(lines)
# Recipe: indent (0.2.1) in C:\trentm\tm\recipes\cookbook
def indent(s, width=4, skip_first_line=False):
"""indent(s, [width=4]) -> 's' indented by 'width' spaces
The optional "skip_first_line" argument is a boolean (default False)
indicating if the first line should NOT be indented.
"""
lines = s.splitlines(1)
indentstr = ' '*width
if skip_first_line:
return indentstr.join(lines)
else:
return indentstr + indentstr.join(lines)
def walk2(top, topdown=True, onerror=None, followlinks=False,
ondecodeerror=None):
"""A version of `os.walk` that adds support for handling errors for
files that cannot be decoded with the default encoding. (See bug 82268.)
By default `UnicodeDecodeError`s from the os.listdir() call are
ignored. If optional arg 'ondecodeerror' is specified, it should be a
function; it will be called with one argument, the `UnicodeDecodeError`
instance. It can report the error to continue with the walk, or
raise the exception to abort the walk.
"""
from os.path import join, isdir, islink
# We may not have read permission for top, in which case we can't
# get a list of the files the directory contains. os.path.walk
# always suppressed the exception then, rather than blow up for a
# minor reason when (say) a thousand readable directories are still
# left to visit. That logic is copied here.
try:
# Note that listdir and error are globals in this module due
# to earlier import-*.
names = os.listdir(top)
except os.error as err:
if onerror is not None:
onerror(err)
return
dirs, nondirs = [], []
for name in names:
try:
if isdir(join(top, name)):
dirs.append(name)
else:
nondirs.append(name)
except UnicodeDecodeError as err:
if ondecodeerror is not None:
ondecodeerror(err)
if topdown:
yield top, dirs, nondirs
for name in dirs:
path = join(top, name)
if followlinks or not islink(path):
for x in walk2(path, topdown, onerror, followlinks):
yield x
if not topdown:
yield top, dirs, nondirs
# Decorators useful for timing and profiling specific functions.
#
# timeit usage:
# Decorate the desired function and you'll get a print for how long
# each call to the function took.
#
# hotspotit usage:
# 1. decorate the desired function
# 2. run your code
# 3. run:
# python .../codeintel/support/show_stats.py .../<funcname>.prof
#
def timeit(func):
clock = (sys.platform == "win32" and time.clock or time.time)
def wrapper(*args, **kw):
start_time = clock()
try:
return func(*args, **kw)
finally:
total_time = clock() - start_time
print("%s took %.3fs" % (func.__name__, total_time))
return wrapper
def hotshotit(func):
def wrapper(*args, **kw):
import hotshot
global hotshotProfilers
prof_name = func.__name__+".prof"
profiler = hotshotProfilers.get(prof_name)
if profiler is None:
profiler = hotshot.Profile(prof_name)
hotshotProfilers[prof_name] = profiler
return profiler.runcall(func, *args, **kw)
return wrapper
_koCProfiler = None
def getProfiler():
global _koCProfiler
if _koCProfiler is None:
class _KoCProfileManager(object):
def __init__(self):
import atexit
import cProfile
from codeintel2.common import _xpcom_
self.prof = cProfile.Profile()
if _xpcom_:
from xpcom import components
_KoCProfileManager._com_interfaces_ = [
components.interfaces.nsIObserver]
obsSvc = components.classes["@mozilla.org/observer-service;1"].\
getService(
components.interfaces.nsIObserverService)
obsSvc.addObserver(self, 'xpcom-shutdown', False)
else:
atexit.register(self.atexit_handler)
def atexit_handler(self):
self.prof.print_stats(sort="time")
def observe(self, subject, topic, data):
if topic == "xpcom-shutdown":
self.atexit_handler()
_koCProfiler = _KoCProfileManager()
return _koCProfiler.prof
def profile_method(func):
def wrapper(*args, **kw):
return getProfiler().runcall(func, *args, **kw)
return wrapper
# Utility functions to perform sorting the same way as scintilla does it
# for the code-completion list.
def OrdPunctLast(value):
result = []
value = value.upper()
for ch in value:
i = ord(ch)
if i >= 0x21 and i <= 0x2F: # ch >= '!' && ch <= '/'
result.append(chr(i - ord("!") + ord('['))) # ch - '!' + '['
elif i >= 0x3A and i <= 0x40: # ch >= ':' && ch <= '@'
result.append(chr(i - ord(":") + ord('['))) # ch - ':' + '['
else:
result.append(ch)
return "".join(result)
def CompareNPunctLast(value1, value2):
# value 1 is smaller, return negative
# value 1 is equal, return 0
# value 1 is larger, return positive
return cmp(OrdPunctLast(value1), OrdPunctLast(value2))
# Utility function to make a lookup dictionary
def make_short_name_dict(names, length=3):
outdict = {}
for name in names:
if len(name) >= length:
shortname = name[:length]
l = outdict.get(shortname)
if not l:
outdict[shortname] = [name]
else:
l.append(name)
# pprint(outdict)
for values in list(outdict.values()):
values.sort(key=OrdPunctLast)
return outdict
def makePerformantLogger(logger):
"""Replaces the info() and debug() methods with dummy methods.
Assumes that the logging level does not change during runtime.
"""
if not logger.isEnabledFor(logging.INFO):
def _log_ignore(self, *args, **kwargs):
pass
logger.info = _log_ignore
if not logger.isEnabledFor(logging.DEBUG):
logger.debug = _log_ignore
#---- mainline self-test
if __name__ == "__main__":
import doctest
doctest.testmod()
|
Drooids/odoo | refs/heads/8.0 | addons/gamification/tests/__init__.py | 268 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (c) 2013 OpenERP S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import test_challenge
|
faunalia/rt_geosisma_offline | refs/heads/master | Utils.py | 1 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : Omero RT
Description : Omero plugin
Date : August 15, 2010
copyright : (C) 2010 by Giuseppe Sucameli (Faunalia)
email : sucameli@faunalia.it
***************************************************************************/
This code has been extracted and adapted from rt_omero plugin to be resused
in rt_geosisma_offline plugin
Works done from Faunalia (http://www.faunalia.it) with funding from Regione
Toscana - Servizio Sismico (http://www.rete.toscana.it/sett/pta/sismica/)
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
import qgis.gui
class MapTool(QObject):
canvas = None
registeredToolStatusMsg = {}
def __init__(self, mapToolClass, canvas=None):
QObject.__init__(self)
if canvas == None:
if MapTool.canvas == None:
raise Exception( "MapTool.canvas is None" )
else:
self.canvas = MapTool.canvas
else:
self.canvas = canvas
if MapTool.canvas == None:
MapTool.canvas = canvas
self.tool = mapToolClass( self.canvas )
QObject.connect(self.tool, SIGNAL( "geometryDrawingEnded" ), self.onEnd)
def deleteLater(self):
self.unregisterStatusMsg()
self.stopCapture()
self.tool.deleteLater()
del self.tool
return QObject.deleteLater(self)
def registerStatusMsg(self, statusMessage):
MapTool.registeredToolStatusMsg[self] = statusMessage
def unregisterStatusMsg(self):
if not MapTool.registeredToolStatusMsg.has_key( self ):
return
del MapTool.registeredToolStatusMsg[self]
def onEnd(self, geometry):
self.stopCapture()
if geometry == None:
return
self.emit( SIGNAL( "geometryEmitted" ), geometry )
def isActive(self):
return self.canvas != None and self.canvas.mapTool() == self.tool
def startCapture(self):
self.canvas.setMapTool( self.tool )
def stopCapture(self):
self.canvas.unsetMapTool( self.tool )
class Drawer(qgis.gui.QgsMapToolEmitPoint):
def __init__(self, canvas, isPolygon=False):
self.canvas = canvas
self.isPolygon = isPolygon
qgis.gui.QgsMapToolEmitPoint.__init__(self, self.canvas)
self.rubberBand = qgis.gui.QgsRubberBand( self.canvas, self.isPolygon )
self.rubberBand.setColor( Qt.red )
self.rubberBand.setBrushStyle(Qt.DiagCrossPattern)
self.rubberBand.setWidth( 1 )
# imposta lo snap a snap to vertex with tollerance 0.9 map units
customSnapOptions = { 'mode' : "to vertex", 'tolerance' : 0.3, 'unit' : 0 }
self.oldSnapOptions = self.customizeSnapping( customSnapOptions )
self.snapper = qgis.gui.QgsMapCanvasSnapper( self.canvas )
self.isEmittingPoints = False
def __del__(self):
if self.oldSnapOptions:
self.customizeSnapping( self.oldSnapOptions )
del self.rubberBand
del self.snapper
self.deleteLater()
def reset(self):
self.isEmittingPoints = False
self.rubberBand.reset( self.isPolygon )
def customizeSnapping(self, option):
oldSnap = {}
settings = QSettings()
oldSnap['mode'] = settings.value( "/Qgis/digitizing/default_snap_mode", "to vertex", type=str)
oldSnap['tolerance'] = settings.value( "/Qgis/digitizing/default_snapping_tolerance", 0, type=float)
oldSnap['unit'] = settings.value( "/Qgis/digitizing/default_snapping_tolerance_unit", 1, type=int )
settings.setValue( "/Qgis/digitizing/default_snap_mode", option['mode'] )
settings.setValue( "/Qgis/digitizing/default_snapping_tolerance", option['tolerance'] )
settings.setValue( "/Qgis/digitizing/default_snapping_tolerance_unit", option['unit'] )
return oldSnap
def canvasPressEvent(self, e):
if e.button() == Qt.RightButton:
self.isEmittingPoints = False
self.emit( SIGNAL("geometryDrawingEnded"), self.geometry() )
return
if e.button() == Qt.LeftButton:
self.isEmittingPoints = True
else:
return
point = self.toMapCoordinates( e.pos() )
self.rubberBand.addPoint( point, True ) # true to update canvas
self.rubberBand.show()
def canvasMoveEvent(self, e):
if not self.isEmittingPoints:
return
retval, snapResults = self.snapper.snapToBackgroundLayers( e.pos() )
if retval == 0 and len(snapResults) > 0:
point = snapResults[0].snappedVertex
else:
point = self.toMapCoordinates( e.pos() )
self.rubberBand.movePoint( point )
def isValid(self):
return self.rubberBand.numberOfVertices() > 0
def geometry(self):
if not self.isValid():
return None
geom = self.rubberBand.asGeometry()
if geom == None:
return
return QgsGeometry.fromWkt( geom.exportToWkt() )
def deactivate(self):
qgis.gui.QgsMapTool.deactivate(self)
self.reset()
self.emit(SIGNAL("deactivated()"))
class FeatureFinder(MapTool):
def __init__(self, canvas=None):
MapTool.__init__(self, qgis.gui.QgsMapToolEmitPoint, canvas=canvas)
QObject.connect(self.tool, SIGNAL( "canvasClicked(const QgsPoint &, Qt::MouseButton)" ), self.onEnd)
def onEnd(self, point, button):
self.stopCapture()
self.emit( SIGNAL("pointEmitted"), point, button )
@classmethod
def findAtPoint(self, layer, point, onlyTheClosestOne=True, onlyIds=False):
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
try:
point = MapTool.canvas.mapSettings().mapToLayerCoordinates(layer, point)
except:
point = MapTool.canvas.mapRenderer().mapToLayerCoordinates(layer, point)
# recupera il valore del raggio di ricerca
settings = QSettings()
radius = settings.value( "/Map/identifyRadius", QGis.DEFAULT_IDENTIFY_RADIUS, float )
if radius <= 0:
# XXX: in QGis 1.8 QGis.DEFAULT_IDENTIFY_RADIUS is 0,
# this cause the rectangle is empty and the select
# returns all the features...
radius = 0.5 # it means 0.50% of the canvas extent
radius = MapTool.canvas.extent().width() * radius/100.0
# crea il rettangolo da usare per la ricerca
rect = QgsRectangle()
rect.setXMinimum(point.x() - radius)
rect.setXMaximum(point.x() + radius)
rect.setYMinimum(point.y() - radius)
rect.setYMaximum(point.y() + radius)
# recupera le feature che intersecano il rettangolo
#layer.select([], rect, True, True)
layer.select( rect, True )
ret = None
if onlyTheClosestOne:
minDist = -1
featureId = None
rect2 = QgsGeometry.fromRect(rect)
for f in layer.getFeatures(QgsFeatureRequest(rect)):
if onlyTheClosestOne:
geom = f.geometry()
distance = geom.distance(rect2)
if minDist < 0 or distance < minDist:
minDist = distance
featureId = f.id()
if onlyIds:
ret = featureId
elif featureId != None:
f = layer.getFeatures(QgsFeatureRequest().setFilterFid( featureId ))
ret = f.next()
else:
IDs = [f.id() for f in layer.getFeatures(QgsFeatureRequest(rect))]
if onlyIds:
ret = IDs
else:
ret = []
for featureId in IDs:
f = layer.getFeatures(QgsFeatureRequest().setFilterFid( featureId ))
ret.append( f )
QApplication.restoreOverrideCursor()
return ret
class PolygonDrawer(MapTool):
class PolygonDrawer(MapTool.Drawer):
def __init__(self, canvas):
MapTool.Drawer.__init__(self, canvas, QGis.Polygon)
def __init__(self, canvas=None):
MapTool.__init__(self, self.PolygonDrawer, canvas)
class LineDrawer(MapTool):
class LineDrawer(MapTool.Drawer):
def __init__(self, canvas):
MapTool.Drawer.__init__(self, canvas, QGis.Line)
def __init__(self, canvas=None):
MapTool.__init__(self, self.LineDrawer, canvas) |
fujita-shintaro/readthedocs.org | refs/heads/master | readthedocs/rtd_tests/tests/test_api_version_compare.py | 34 | from django.test import TestCase
from readthedocs.builds.constants import LATEST
from readthedocs.projects.models import Project
from readthedocs.restapi.views.footer_views import get_version_compare_data
class VersionCompareTests(TestCase):
fixtures = ['eric.json', 'test_data.json']
def test_not_highest(self):
project = Project.objects.get(slug='read-the-docs')
version = project.versions.get(slug='0.2.1')
data = get_version_compare_data(project, version)
self.assertEqual(data['is_highest'], False)
def test_latest_version_highest(self):
project = Project.objects.get(slug='read-the-docs')
data = get_version_compare_data(project)
self.assertEqual(data['is_highest'], True)
version = project.versions.get(slug=LATEST)
data = get_version_compare_data(project, version)
self.assertEqual(data['is_highest'], True)
def test_real_highest(self):
project = Project.objects.get(slug='read-the-docs')
version = project.versions.get(slug='0.2.2')
data = get_version_compare_data(project, version)
self.assertEqual(data['is_highest'], True)
|
silentfuzzle/calibre | refs/heads/master | src/calibre/ebooks/conversion/plugins/fb2_input.py | 14 | from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2008, Anatoly Shipitsin <norguhtar at gmail.com>'
"""
Convert .fb2 files to .lrf
"""
import os, re
from calibre.customize.conversion import InputFormatPlugin, OptionRecommendation
from calibre import guess_type
FB2NS = 'http://www.gribuser.ru/xml/fictionbook/2.0'
FB21NS = 'http://www.gribuser.ru/xml/fictionbook/2.1'
class FB2Input(InputFormatPlugin):
name = 'FB2 Input'
author = 'Anatoly Shipitsin'
description = 'Convert FB2 files to HTML'
file_types = set(['fb2'])
recommendations = set([
('level1_toc', '//h:h1', OptionRecommendation.MED),
('level2_toc', '//h:h2', OptionRecommendation.MED),
('level3_toc', '//h:h3', OptionRecommendation.MED),
])
options = set([
OptionRecommendation(name='no_inline_fb2_toc',
recommended_value=False, level=OptionRecommendation.LOW,
help=_('Do not insert a Table of Contents at the beginning of the book.'
)
),
])
def convert(self, stream, options, file_ext, log,
accelerators):
from lxml import etree
from calibre.ebooks.metadata.fb2 import ensure_namespace
from calibre.ebooks.metadata.opf2 import OPFCreator
from calibre.ebooks.metadata.meta import get_metadata
from calibre.ebooks.oeb.base import XLINK_NS, XHTML_NS, RECOVER_PARSER
from calibre.ebooks.chardet import xml_to_unicode
self.log = log
log.debug('Parsing XML...')
raw = stream.read().replace('\0', '')
raw = xml_to_unicode(raw, strip_encoding_pats=True,
assume_utf8=True, resolve_entities=True)[0]
try:
doc = etree.fromstring(raw)
except etree.XMLSyntaxError:
try:
doc = etree.fromstring(raw, parser=RECOVER_PARSER)
if doc is None:
raise Exception('parse failed')
except:
doc = etree.fromstring(raw.replace('& ', '&'),
parser=RECOVER_PARSER)
if doc is None:
raise ValueError('The FB2 file is not valid XML')
doc = ensure_namespace(doc)
try:
fb_ns = doc.nsmap[doc.prefix]
except Exception:
fb_ns = FB2NS
NAMESPACES = {'f':fb_ns, 'l':XLINK_NS}
stylesheets = doc.xpath('//*[local-name() = "stylesheet" and @type="text/css"]')
css = ''
for s in stylesheets:
css += etree.tostring(s, encoding=unicode, method='text',
with_tail=False) + '\n\n'
if css:
import cssutils, logging
parser = cssutils.CSSParser(fetcher=None,
log=logging.getLogger('calibre.css'))
XHTML_CSS_NAMESPACE = '@namespace "%s";\n' % XHTML_NS
text = XHTML_CSS_NAMESPACE + css
log.debug('Parsing stylesheet...')
stylesheet = parser.parseString(text)
stylesheet.namespaces['h'] = XHTML_NS
css = unicode(stylesheet.cssText).replace('h|style', 'h|span')
css = re.sub(r'name\s*=\s*', 'class=', css)
self.extract_embedded_content(doc)
log.debug('Converting XML to HTML...')
ss = open(P('templates/fb2.xsl'), 'rb').read()
ss = ss.replace("__FB_NS__", fb_ns)
if options.no_inline_fb2_toc:
log('Disabling generation of inline FB2 TOC')
ss = re.compile(r'<!-- BUILD TOC -->.*<!-- END BUILD TOC -->',
re.DOTALL).sub('', ss)
styledoc = etree.fromstring(ss)
transform = etree.XSLT(styledoc)
result = transform(doc)
# Handle links of type note and cite
notes = {a.get('href')[1:]: a for a in result.xpath('//a[@link_note and @href]') if a.get('href').startswith('#')}
cites = {a.get('link_cite'): a for a in result.xpath('//a[@link_cite]') if not a.get('href', '')}
all_ids = {x for x in result.xpath('//*/@id')}
for cite, a in cites.iteritems():
note = notes.get(cite, None)
if note:
c = 1
while 'cite%d' % c in all_ids:
c += 1
if not note.get('id', None):
note.set('id', 'cite%d' % c)
all_ids.add(note.get('id'))
a.set('href', '#%s' % note.get('id'))
for x in result.xpath('//*[@link_note or @link_cite]'):
x.attrib.pop('link_note', None)
x.attrib.pop('link_cite', None)
for img in result.xpath('//img[@src]'):
src = img.get('src')
img.set('src', self.binary_map.get(src, src))
index = transform.tostring(result)
open(u'index.xhtml', 'wb').write(index)
open(u'inline-styles.css', 'wb').write(css)
stream.seek(0)
mi = get_metadata(stream, 'fb2')
if not mi.title:
mi.title = _('Unknown')
if not mi.authors:
mi.authors = [_('Unknown')]
cpath = None
if mi.cover_data and mi.cover_data[1]:
with open(u'fb2_cover_calibre_mi.jpg', 'wb') as f:
f.write(mi.cover_data[1])
cpath = os.path.abspath(u'fb2_cover_calibre_mi.jpg')
else:
for img in doc.xpath('//f:coverpage/f:image', namespaces=NAMESPACES):
href = img.get('{%s}href'%XLINK_NS, img.get('href', None))
if href is not None:
if href.startswith('#'):
href = href[1:]
cpath = os.path.abspath(href)
break
opf = OPFCreator(os.getcwdu(), mi)
entries = [(f2, guess_type(f2)[0]) for f2 in os.listdir(u'.')]
opf.create_manifest(entries)
opf.create_spine([u'index.xhtml'])
if cpath:
opf.guide.set_cover(cpath)
with open(u'metadata.opf', 'wb') as f:
opf.render(f)
return os.path.join(os.getcwdu(), u'metadata.opf')
def extract_embedded_content(self, doc):
from calibre.ebooks.fb2 import base64_decode
self.binary_map = {}
for elem in doc.xpath('./*'):
if elem.text and 'binary' in elem.tag and 'id' in elem.attrib:
ct = elem.get('content-type', '')
fname = elem.attrib['id']
ext = ct.rpartition('/')[-1].lower()
if ext in ('png', 'jpeg', 'jpg'):
if fname.lower().rpartition('.')[-1] not in {'jpg', 'jpeg',
'png'}:
fname += '.' + ext
self.binary_map[elem.get('id')] = fname
raw = elem.text.strip()
try:
data = base64_decode(raw)
except TypeError:
self.log.exception('Binary data with id=%s is corrupted, ignoring'%(
elem.get('id')))
else:
with open(fname, 'wb') as f:
f.write(data)
|
scalable-networks/ext | refs/heads/master | gnuradio-3.7.0.1/gr-filter/examples/synth_filter.py | 58 | #!/usr/bin/env python
#
# Copyright 2010,2012,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr
from gnuradio import filter
from gnuradio import blocks
import sys
try:
from gnuradio import analog
except ImportError:
sys.stderr.write("Error: Program requires gr-analog.\n")
sys.exit(1)
try:
import scipy
except ImportError:
sys.stderr.write("Error: Program requires scipy (see: www.scipy.org).\n")
sys.exit(1)
try:
import pylab
except ImportError:
sys.stderr.write("Error: Program requires matplotlib (see: matplotlib.sourceforge.net).\n")
sys.exit(1)
def main():
N = 1000000
fs = 8000
freqs = [100, 200, 300, 400, 500]
nchans = 7
sigs = list()
for fi in freqs:
s = analog.sig_source_c(fs, analog.GR_SIN_WAVE, fi, 1)
sigs.append(s)
taps = filter.firdes.low_pass_2(len(freqs), fs,
fs/float(nchans)/2, 100, 100)
print "Num. Taps = %d (taps per filter = %d)" % (len(taps),
len(taps)/nchans)
filtbank = filter.pfb_synthesizer_ccf(nchans, taps)
head = blocks.head(gr.sizeof_gr_complex, N)
snk = blocks.vector_sink_c()
tb = gr.top_block()
tb.connect(filtbank, head, snk)
for i,si in enumerate(sigs):
tb.connect(si, (filtbank, i))
tb.run()
if 1:
f1 = pylab.figure(1)
s1 = f1.add_subplot(1,1,1)
s1.plot(snk.data()[1000:])
fftlen = 2048
f2 = pylab.figure(2)
s2 = f2.add_subplot(1,1,1)
winfunc = scipy.blackman
s2.psd(snk.data()[10000:], NFFT=fftlen,
Fs = nchans*fs,
noverlap=fftlen/4,
window = lambda d: d*winfunc(fftlen))
pylab.show()
if __name__ == "__main__":
main()
|
AgentN/namebench | refs/heads/master | nb_third_party/jinja2/pkg_resources.py | 245 | """Package resource API
--------------------
A resource is a logical file contained within a package, or a logical
subdirectory thereof. The package resource API expects resource names
to have their path parts separated with ``/``, *not* whatever the local
path separator is. Do not use os.path operations to manipulate resource
names being passed into the API.
The package resource API is designed to work with normal filesystem packages,
.egg files, and unpacked .egg files. It can also work in a limited way with
.zip files and with custom PEP 302 loaders that support the ``get_data()``
method.
"""
import sys, os, zipimport, time, re, imp, new
try:
frozenset
except NameError:
from sets import ImmutableSet as frozenset
from os import utime, rename, unlink # capture these to bypass sandboxing
from os import open as os_open
def get_supported_platform():
"""Return this platform's maximum compatible version.
distutils.util.get_platform() normally reports the minimum version
of Mac OS X that would be required to *use* extensions produced by
distutils. But what we want when checking compatibility is to know the
version of Mac OS X that we are *running*. To allow usage of packages that
explicitly require a newer version of Mac OS X, we must also know the
current version of the OS.
If this condition occurs for any other platform with a version in its
platform strings, this function should be extended accordingly.
"""
plat = get_build_platform(); m = macosVersionString.match(plat)
if m is not None and sys.platform == "darwin":
try:
plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3))
except ValueError:
pass # not Mac OS X
return plat
__all__ = [
# Basic resource access and distribution/entry point discovery
'require', 'run_script', 'get_provider', 'get_distribution',
'load_entry_point', 'get_entry_map', 'get_entry_info', 'iter_entry_points',
'resource_string', 'resource_stream', 'resource_filename',
'resource_listdir', 'resource_exists', 'resource_isdir',
# Environmental control
'declare_namespace', 'working_set', 'add_activation_listener',
'find_distributions', 'set_extraction_path', 'cleanup_resources',
'get_default_cache',
# Primary implementation classes
'Environment', 'WorkingSet', 'ResourceManager',
'Distribution', 'Requirement', 'EntryPoint',
# Exceptions
'ResolutionError','VersionConflict','DistributionNotFound','UnknownExtra',
'ExtractionError',
# Parsing functions and string utilities
'parse_requirements', 'parse_version', 'safe_name', 'safe_version',
'get_platform', 'compatible_platforms', 'yield_lines', 'split_sections',
'safe_extra', 'to_filename',
# filesystem utilities
'ensure_directory', 'normalize_path',
# Distribution "precedence" constants
'EGG_DIST', 'BINARY_DIST', 'SOURCE_DIST', 'CHECKOUT_DIST', 'DEVELOP_DIST',
# "Provider" interfaces, implementations, and registration/lookup APIs
'IMetadataProvider', 'IResourceProvider', 'FileMetadata',
'PathMetadata', 'EggMetadata', 'EmptyProvider', 'empty_provider',
'NullProvider', 'EggProvider', 'DefaultProvider', 'ZipProvider',
'register_finder', 'register_namespace_handler', 'register_loader_type',
'fixup_namespace_packages', 'get_importer',
# Deprecated/backward compatibility only
'run_main', 'AvailableDistributions',
]
class ResolutionError(Exception):
"""Abstract base for dependency resolution errors"""
def __repr__(self): return self.__class__.__name__+repr(self.args)
class VersionConflict(ResolutionError):
"""An already-installed version conflicts with the requested version"""
class DistributionNotFound(ResolutionError):
"""A requested distribution was not found"""
class UnknownExtra(ResolutionError):
"""Distribution doesn't have an "extra feature" of the given name"""
_provider_factories = {}
PY_MAJOR = sys.version[:3]
EGG_DIST = 3
BINARY_DIST = 2
SOURCE_DIST = 1
CHECKOUT_DIST = 0
DEVELOP_DIST = -1
def register_loader_type(loader_type, provider_factory):
"""Register `provider_factory` to make providers for `loader_type`
`loader_type` is the type or class of a PEP 302 ``module.__loader__``,
and `provider_factory` is a function that, passed a *module* object,
returns an ``IResourceProvider`` for that module.
"""
_provider_factories[loader_type] = provider_factory
def get_provider(moduleOrReq):
"""Return an IResourceProvider for the named module or requirement"""
if isinstance(moduleOrReq,Requirement):
return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
try:
module = sys.modules[moduleOrReq]
except KeyError:
__import__(moduleOrReq)
module = sys.modules[moduleOrReq]
loader = getattr(module, '__loader__', None)
return _find_adapter(_provider_factories, loader)(module)
def _macosx_vers(_cache=[]):
if not _cache:
info = os.popen('/usr/bin/sw_vers').read().splitlines()
for line in info:
key, value = line.split(None, 1)
if key == 'ProductVersion:':
_cache.append(value.strip().split("."))
break
else:
raise ValueError, "What?!"
return _cache[0]
def _macosx_arch(machine):
return {'PowerPC':'ppc', 'Power_Macintosh':'ppc'}.get(machine,machine)
def get_build_platform():
"""Return this platform's string for platform-specific distributions
XXX Currently this is the same as ``distutils.util.get_platform()``, but it
needs some hacks for Linux and Mac OS X.
"""
from distutils.util import get_platform
plat = get_platform()
if sys.platform == "darwin" and not plat.startswith('macosx-'):
try:
version = _macosx_vers()
machine = os.uname()[4].replace(" ", "_")
return "macosx-%d.%d-%s" % (int(version[0]), int(version[1]),
_macosx_arch(machine))
except ValueError:
# if someone is running a non-Mac darwin system, this will fall
# through to the default implementation
pass
return plat
macosVersionString = re.compile(r"macosx-(\d+)\.(\d+)-(.*)")
darwinVersionString = re.compile(r"darwin-(\d+)\.(\d+)\.(\d+)-(.*)")
get_platform = get_build_platform # XXX backward compat
def compatible_platforms(provided,required):
"""Can code for the `provided` platform run on the `required` platform?
Returns true if either platform is ``None``, or the platforms are equal.
XXX Needs compatibility checks for Linux and other unixy OSes.
"""
if provided is None or required is None or provided==required:
return True # easy case
# Mac OS X special cases
reqMac = macosVersionString.match(required)
if reqMac:
provMac = macosVersionString.match(provided)
# is this a Mac package?
if not provMac:
# this is backwards compatibility for packages built before
# setuptools 0.6. All packages built after this point will
# use the new macosx designation.
provDarwin = darwinVersionString.match(provided)
if provDarwin:
dversion = int(provDarwin.group(1))
macosversion = "%s.%s" % (reqMac.group(1), reqMac.group(2))
if dversion == 7 and macosversion >= "10.3" or \
dversion == 8 and macosversion >= "10.4":
#import warnings
#warnings.warn("Mac eggs should be rebuilt to "
# "use the macosx designation instead of darwin.",
# category=DeprecationWarning)
return True
return False # egg isn't macosx or legacy darwin
# are they the same major version and machine type?
if provMac.group(1) != reqMac.group(1) or \
provMac.group(3) != reqMac.group(3):
return False
# is the required OS major update >= the provided one?
if int(provMac.group(2)) > int(reqMac.group(2)):
return False
return True
# XXX Linux and other platforms' special cases should go here
return False
def run_script(dist_spec, script_name):
"""Locate distribution `dist_spec` and run its `script_name` script"""
ns = sys._getframe(1).f_globals
name = ns['__name__']
ns.clear()
ns['__name__'] = name
require(dist_spec)[0].run_script(script_name, ns)
run_main = run_script # backward compatibility
def get_distribution(dist):
"""Return a current distribution object for a Requirement or string"""
if isinstance(dist,basestring): dist = Requirement.parse(dist)
if isinstance(dist,Requirement): dist = get_provider(dist)
if not isinstance(dist,Distribution):
raise TypeError("Expected string, Requirement, or Distribution", dist)
return dist
def load_entry_point(dist, group, name):
"""Return `name` entry point of `group` for `dist` or raise ImportError"""
return get_distribution(dist).load_entry_point(group, name)
def get_entry_map(dist, group=None):
"""Return the entry point map for `group`, or the full entry map"""
return get_distribution(dist).get_entry_map(group)
def get_entry_info(dist, group, name):
"""Return the EntryPoint object for `group`+`name`, or ``None``"""
return get_distribution(dist).get_entry_info(group, name)
class IMetadataProvider:
def has_metadata(name):
"""Does the package's distribution contain the named metadata?"""
def get_metadata(name):
"""The named metadata resource as a string"""
def get_metadata_lines(name):
"""Yield named metadata resource as list of non-blank non-comment lines
Leading and trailing whitespace is stripped from each line, and lines
with ``#`` as the first non-blank character are omitted."""
def metadata_isdir(name):
"""Is the named metadata a directory? (like ``os.path.isdir()``)"""
def metadata_listdir(name):
"""List of metadata names in the directory (like ``os.listdir()``)"""
def run_script(script_name, namespace):
"""Execute the named script in the supplied namespace dictionary"""
class IResourceProvider(IMetadataProvider):
"""An object that provides access to package resources"""
def get_resource_filename(manager, resource_name):
"""Return a true filesystem path for `resource_name`
`manager` must be an ``IResourceManager``"""
def get_resource_stream(manager, resource_name):
"""Return a readable file-like object for `resource_name`
`manager` must be an ``IResourceManager``"""
def get_resource_string(manager, resource_name):
"""Return a string containing the contents of `resource_name`
`manager` must be an ``IResourceManager``"""
def has_resource(resource_name):
"""Does the package contain the named resource?"""
def resource_isdir(resource_name):
"""Is the named resource a directory? (like ``os.path.isdir()``)"""
def resource_listdir(resource_name):
"""List of resource names in the directory (like ``os.listdir()``)"""
class WorkingSet(object):
"""A collection of active distributions on sys.path (or a similar list)"""
def __init__(self, entries=None):
"""Create working set from list of path entries (default=sys.path)"""
self.entries = []
self.entry_keys = {}
self.by_key = {}
self.callbacks = []
if entries is None:
entries = sys.path
for entry in entries:
self.add_entry(entry)
def add_entry(self, entry):
"""Add a path item to ``.entries``, finding any distributions on it
``find_distributions(entry,False)`` is used to find distributions
corresponding to the path entry, and they are added. `entry` is
always appended to ``.entries``, even if it is already present.
(This is because ``sys.path`` can contain the same value more than
once, and the ``.entries`` of the ``sys.path`` WorkingSet should always
equal ``sys.path``.)
"""
self.entry_keys.setdefault(entry, [])
self.entries.append(entry)
for dist in find_distributions(entry, True):
self.add(dist, entry, False)
def __contains__(self,dist):
"""True if `dist` is the active distribution for its project"""
return self.by_key.get(dist.key) == dist
def find(self, req):
"""Find a distribution matching requirement `req`
If there is an active distribution for the requested project, this
returns it as long as it meets the version requirement specified by
`req`. But, if there is an active distribution for the project and it
does *not* meet the `req` requirement, ``VersionConflict`` is raised.
If there is no active distribution for the requested project, ``None``
is returned.
"""
dist = self.by_key.get(req.key)
if dist is not None and dist not in req:
raise VersionConflict(dist,req) # XXX add more info
else:
return dist
def iter_entry_points(self, group, name=None):
"""Yield entry point objects from `group` matching `name`
If `name` is None, yields all entry points in `group` from all
distributions in the working set, otherwise only ones matching
both `group` and `name` are yielded (in distribution order).
"""
for dist in self:
entries = dist.get_entry_map(group)
if name is None:
for ep in entries.values():
yield ep
elif name in entries:
yield entries[name]
def run_script(self, requires, script_name):
"""Locate distribution for `requires` and run `script_name` script"""
ns = sys._getframe(1).f_globals
name = ns['__name__']
ns.clear()
ns['__name__'] = name
self.require(requires)[0].run_script(script_name, ns)
def __iter__(self):
"""Yield distributions for non-duplicate projects in the working set
The yield order is the order in which the items' path entries were
added to the working set.
"""
seen = {}
for item in self.entries:
for key in self.entry_keys[item]:
if key not in seen:
seen[key]=1
yield self.by_key[key]
def add(self, dist, entry=None, insert=True):
"""Add `dist` to working set, associated with `entry`
If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
On exit from this routine, `entry` is added to the end of the working
set's ``.entries`` (if it wasn't already present).
`dist` is only added to the working set if it's for a project that
doesn't already have a distribution in the set. If it's added, any
callbacks registered with the ``subscribe()`` method will be called.
"""
if insert:
dist.insert_on(self.entries, entry)
if entry is None:
entry = dist.location
keys = self.entry_keys.setdefault(entry,[])
keys2 = self.entry_keys.setdefault(dist.location,[])
if dist.key in self.by_key:
return # ignore hidden distros
self.by_key[dist.key] = dist
if dist.key not in keys:
keys.append(dist.key)
if dist.key not in keys2:
keys2.append(dist.key)
self._added_new(dist)
def resolve(self, requirements, env=None, installer=None):
"""List all distributions needed to (recursively) meet `requirements`
`requirements` must be a sequence of ``Requirement`` objects. `env`,
if supplied, should be an ``Environment`` instance. If
not supplied, it defaults to all distributions available within any
entry or distribution in the working set. `installer`, if supplied,
will be invoked with each requirement that cannot be met by an
already-installed distribution; it should return a ``Distribution`` or
``None``.
"""
requirements = list(requirements)[::-1] # set up the stack
processed = {} # set of processed requirements
best = {} # key -> dist
to_activate = []
while requirements:
req = requirements.pop(0) # process dependencies breadth-first
if req in processed:
# Ignore cyclic or redundant dependencies
continue
dist = best.get(req.key)
if dist is None:
# Find the best distribution and add it to the map
dist = self.by_key.get(req.key)
if dist is None:
if env is None:
env = Environment(self.entries)
dist = best[req.key] = env.best_match(req, self, installer)
if dist is None:
raise DistributionNotFound(req) # XXX put more info here
to_activate.append(dist)
if dist not in req:
# Oops, the "best" so far conflicts with a dependency
raise VersionConflict(dist,req) # XXX put more info here
requirements.extend(dist.requires(req.extras)[::-1])
processed[req] = True
return to_activate # return list of distros to activate
def find_plugins(self,
plugin_env, full_env=None, installer=None, fallback=True
):
"""Find all activatable distributions in `plugin_env`
Example usage::
distributions, errors = working_set.find_plugins(
Environment(plugin_dirlist)
)
map(working_set.add, distributions) # add plugins+libs to sys.path
print "Couldn't load", errors # display errors
The `plugin_env` should be an ``Environment`` instance that contains
only distributions that are in the project's "plugin directory" or
directories. The `full_env`, if supplied, should be an ``Environment``
contains all currently-available distributions. If `full_env` is not
supplied, one is created automatically from the ``WorkingSet`` this
method is called on, which will typically mean that every directory on
``sys.path`` will be scanned for distributions.
`installer` is a standard installer callback as used by the
``resolve()`` method. The `fallback` flag indicates whether we should
attempt to resolve older versions of a plugin if the newest version
cannot be resolved.
This method returns a 2-tuple: (`distributions`, `error_info`), where
`distributions` is a list of the distributions found in `plugin_env`
that were loadable, along with any other distributions that are needed
to resolve their dependencies. `error_info` is a dictionary mapping
unloadable plugin distributions to an exception instance describing the
error that occurred. Usually this will be a ``DistributionNotFound`` or
``VersionConflict`` instance.
"""
plugin_projects = list(plugin_env)
plugin_projects.sort() # scan project names in alphabetic order
error_info = {}
distributions = {}
if full_env is None:
env = Environment(self.entries)
env += plugin_env
else:
env = full_env + plugin_env
shadow_set = self.__class__([])
map(shadow_set.add, self) # put all our entries in shadow_set
for project_name in plugin_projects:
for dist in plugin_env[project_name]:
req = [dist.as_requirement()]
try:
resolvees = shadow_set.resolve(req, env, installer)
except ResolutionError,v:
error_info[dist] = v # save error info
if fallback:
continue # try the next older version of project
else:
break # give up on this project, keep going
else:
map(shadow_set.add, resolvees)
distributions.update(dict.fromkeys(resolvees))
# success, no need to try any more versions of this project
break
distributions = list(distributions)
distributions.sort()
return distributions, error_info
def require(self, *requirements):
"""Ensure that distributions matching `requirements` are activated
`requirements` must be a string or a (possibly-nested) sequence
thereof, specifying the distributions and versions required. The
return value is a sequence of the distributions that needed to be
activated to fulfill the requirements; all relevant distributions are
included, even if they were already activated in this working set.
"""
needed = self.resolve(parse_requirements(requirements))
for dist in needed:
self.add(dist)
return needed
def subscribe(self, callback):
"""Invoke `callback` for all distributions (including existing ones)"""
if callback in self.callbacks:
return
self.callbacks.append(callback)
for dist in self:
callback(dist)
def _added_new(self, dist):
for callback in self.callbacks:
callback(dist)
class Environment(object):
"""Searchable snapshot of distributions on a search path"""
def __init__(self, search_path=None, platform=get_supported_platform(), python=PY_MAJOR):
"""Snapshot distributions available on a search path
Any distributions found on `search_path` are added to the environment.
`search_path` should be a sequence of ``sys.path`` items. If not
supplied, ``sys.path`` is used.
`platform` is an optional string specifying the name of the platform
that platform-specific distributions must be compatible with. If
unspecified, it defaults to the current platform. `python` is an
optional string naming the desired version of Python (e.g. ``'2.4'``);
it defaults to the current version.
You may explicitly set `platform` (and/or `python`) to ``None`` if you
wish to map *all* distributions, not just those compatible with the
running platform or Python version.
"""
self._distmap = {}
self._cache = {}
self.platform = platform
self.python = python
self.scan(search_path)
def can_add(self, dist):
"""Is distribution `dist` acceptable for this environment?
The distribution must match the platform and python version
requirements specified when this environment was created, or False
is returned.
"""
return (self.python is None or dist.py_version is None
or dist.py_version==self.python) \
and compatible_platforms(dist.platform,self.platform)
def remove(self, dist):
"""Remove `dist` from the environment"""
self._distmap[dist.key].remove(dist)
def scan(self, search_path=None):
"""Scan `search_path` for distributions usable in this environment
Any distributions found are added to the environment.
`search_path` should be a sequence of ``sys.path`` items. If not
supplied, ``sys.path`` is used. Only distributions conforming to
the platform/python version defined at initialization are added.
"""
if search_path is None:
search_path = sys.path
for item in search_path:
for dist in find_distributions(item):
self.add(dist)
def __getitem__(self,project_name):
"""Return a newest-to-oldest list of distributions for `project_name`
"""
try:
return self._cache[project_name]
except KeyError:
project_name = project_name.lower()
if project_name not in self._distmap:
return []
if project_name not in self._cache:
dists = self._cache[project_name] = self._distmap[project_name]
_sort_dists(dists)
return self._cache[project_name]
def add(self,dist):
"""Add `dist` if we ``can_add()`` it and it isn't already added"""
if self.can_add(dist) and dist.has_version():
dists = self._distmap.setdefault(dist.key,[])
if dist not in dists:
dists.append(dist)
if dist.key in self._cache:
_sort_dists(self._cache[dist.key])
def best_match(self, req, working_set, installer=None):
"""Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitable version of the project is already
active in the specified `working_set`.) If a suitable distribution
isn't active, this method returns the newest distribution in the
environment that meets the ``Requirement`` in `req`. If no suitable
distribution is found, and `installer` is supplied, then the result of
calling the environment's ``obtain(req, installer)`` method will be
returned.
"""
dist = working_set.find(req)
if dist is not None:
return dist
for dist in self[req.key]:
if dist in req:
return dist
return self.obtain(req, installer) # try and download/install
def obtain(self, requirement, installer=None):
"""Obtain a distribution matching `requirement` (e.g. via download)
Obtain a distro that matches requirement (e.g. via download). In the
base ``Environment`` class, this routine just returns
``installer(requirement)``, unless `installer` is None, in which case
None is returned instead. This method is a hook that allows subclasses
to attempt other ways of obtaining a distribution before falling back
to the `installer` argument."""
if installer is not None:
return installer(requirement)
def __iter__(self):
"""Yield the unique project names of the available distributions"""
for key in self._distmap.keys():
if self[key]: yield key
def __iadd__(self, other):
"""In-place addition of a distribution or environment"""
if isinstance(other,Distribution):
self.add(other)
elif isinstance(other,Environment):
for project in other:
for dist in other[project]:
self.add(dist)
else:
raise TypeError("Can't add %r to environment" % (other,))
return self
def __add__(self, other):
"""Add an environment or distribution to an environment"""
new = self.__class__([], platform=None, python=None)
for env in self, other:
new += env
return new
AvailableDistributions = Environment # XXX backward compatibility
class ExtractionError(RuntimeError):
"""An error occurred extracting a resource
The following attributes are available from instances of this exception:
manager
The resource manager that raised this exception
cache_path
The base directory for resource extraction
original_error
The exception instance that caused extraction to fail
"""
class ResourceManager:
"""Manage resource extraction and packages"""
extraction_path = None
def __init__(self):
self.cached_files = {}
def resource_exists(self, package_or_requirement, resource_name):
"""Does the named resource exist?"""
return get_provider(package_or_requirement).has_resource(resource_name)
def resource_isdir(self, package_or_requirement, resource_name):
"""Is the named resource an existing directory?"""
return get_provider(package_or_requirement).resource_isdir(
resource_name
)
def resource_filename(self, package_or_requirement, resource_name):
"""Return a true filesystem path for specified resource"""
return get_provider(package_or_requirement).get_resource_filename(
self, resource_name
)
def resource_stream(self, package_or_requirement, resource_name):
"""Return a readable file-like object for specified resource"""
return get_provider(package_or_requirement).get_resource_stream(
self, resource_name
)
def resource_string(self, package_or_requirement, resource_name):
"""Return specified resource as a string"""
return get_provider(package_or_requirement).get_resource_string(
self, resource_name
)
def resource_listdir(self, package_or_requirement, resource_name):
"""List the contents of the named resource directory"""
return get_provider(package_or_requirement).resource_listdir(
resource_name
)
def extraction_error(self):
"""Give an error message for problems extracting file(s)"""
old_exc = sys.exc_info()[1]
cache_path = self.extraction_path or get_default_cache()
err = ExtractionError("""Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
%s
The Python egg cache directory is currently set to:
%s
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory.
""" % (old_exc, cache_path)
)
err.manager = self
err.cache_path = cache_path
err.original_error = old_exc
raise err
def get_cache_path(self, archive_name, names=()):
"""Return absolute location in cache for `archive_name` and `names`
The parent directory of the resulting path will be created if it does
not already exist. `archive_name` should be the base filename of the
enclosing egg (which may not be the name of the enclosing zipfile!),
including its ".egg" extension. `names`, if provided, should be a
sequence of path name parts "under" the egg's extraction location.
This method should only be called by resource providers that need to
obtain an extraction location, and only for names they intend to
extract, as it tracks the generated names for possible cleanup later.
"""
extract_path = self.extraction_path or get_default_cache()
target_path = os.path.join(extract_path, archive_name+'-tmp', *names)
try:
ensure_directory(target_path)
except:
self.extraction_error()
self.cached_files[target_path] = 1
return target_path
def postprocess(self, tempname, filename):
"""Perform any platform-specific postprocessing of `tempname`
This is where Mac header rewrites should be done; other platforms don't
have anything special they should do.
Resource providers should call this method ONLY after successfully
extracting a compressed resource. They must NOT call it on resources
that are already in the filesystem.
`tempname` is the current (temporary) name of the file, and `filename`
is the name it will be renamed to by the caller after this routine
returns.
"""
if os.name == 'posix':
# Make the resource executable
mode = ((os.stat(tempname).st_mode) | 0555) & 07777
os.chmod(tempname, mode)
def set_extraction_path(self, path):
"""Set the base path where resources will be extracted to, if needed.
If you do not call this routine before any extractions take place, the
path defaults to the return value of ``get_default_cache()``. (Which
is based on the ``PYTHON_EGG_CACHE`` environment variable, with various
platform-specific fallbacks. See that routine's documentation for more
details.)
Resources are extracted to subdirectories of this path based upon
information given by the ``IResourceProvider``. You may set this to a
temporary directory, but then you must call ``cleanup_resources()`` to
delete the extracted files when done. There is no guarantee that
``cleanup_resources()`` will be able to remove all extracted files.
(Note: you may not change the extraction path for a given resource
manager once resources have been extracted, unless you first call
``cleanup_resources()``.)
"""
if self.cached_files:
raise ValueError(
"Can't change extraction path, files already extracted"
)
self.extraction_path = path
def cleanup_resources(self, force=False):
"""
Delete all extracted resource files and directories, returning a list
of the file and directory names that could not be successfully removed.
This function does not have any concurrency protection, so it should
generally only be called when the extraction path is a temporary
directory exclusive to a single process. This method is not
automatically called; you must call it explicitly or register it as an
``atexit`` function if you wish to ensure cleanup of a temporary
directory used for extractions.
"""
# XXX
def get_default_cache():
"""Determine the default cache location
This returns the ``PYTHON_EGG_CACHE`` environment variable, if set.
Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the
"Application Data" directory. On all other systems, it's "~/.python-eggs".
"""
try:
return os.environ['PYTHON_EGG_CACHE']
except KeyError:
pass
if os.name!='nt':
return os.path.expanduser('~/.python-eggs')
app_data = 'Application Data' # XXX this may be locale-specific!
app_homes = [
(('APPDATA',), None), # best option, should be locale-safe
(('USERPROFILE',), app_data),
(('HOMEDRIVE','HOMEPATH'), app_data),
(('HOMEPATH',), app_data),
(('HOME',), None),
(('WINDIR',), app_data), # 95/98/ME
]
for keys, subdir in app_homes:
dirname = ''
for key in keys:
if key in os.environ:
dirname = os.path.join(dirname, os.environ[key])
else:
break
else:
if subdir:
dirname = os.path.join(dirname,subdir)
return os.path.join(dirname, 'Python-Eggs')
else:
raise RuntimeError(
"Please set the PYTHON_EGG_CACHE enviroment variable"
)
def safe_name(name):
"""Convert an arbitrary string to a standard distribution name
Any runs of non-alphanumeric/. characters are replaced with a single '-'.
"""
return re.sub('[^A-Za-z0-9.]+', '-', name)
def safe_version(version):
"""Convert an arbitrary string to a standard version string
Spaces become dots, and all other non-alphanumeric characters become
dashes, with runs of multiple dashes condensed to a single dash.
"""
version = version.replace(' ','.')
return re.sub('[^A-Za-z0-9.]+', '-', version)
def safe_extra(extra):
"""Convert an arbitrary string to a standard 'extra' name
Any runs of non-alphanumeric characters are replaced with a single '_',
and the result is always lowercased.
"""
return re.sub('[^A-Za-z0-9.]+', '_', extra).lower()
def to_filename(name):
"""Convert a project or version name to its filename-escaped form
Any '-' characters are currently replaced with '_'.
"""
return name.replace('-','_')
class NullProvider:
"""Try to implement resources and metadata for arbitrary PEP 302 loaders"""
egg_name = None
egg_info = None
loader = None
def __init__(self, module):
self.loader = getattr(module, '__loader__', None)
self.module_path = os.path.dirname(getattr(module, '__file__', ''))
def get_resource_filename(self, manager, resource_name):
return self._fn(self.module_path, resource_name)
def get_resource_stream(self, manager, resource_name):
return StringIO(self.get_resource_string(manager, resource_name))
def get_resource_string(self, manager, resource_name):
return self._get(self._fn(self.module_path, resource_name))
def has_resource(self, resource_name):
return self._has(self._fn(self.module_path, resource_name))
def has_metadata(self, name):
return self.egg_info and self._has(self._fn(self.egg_info,name))
def get_metadata(self, name):
if not self.egg_info:
return ""
return self._get(self._fn(self.egg_info,name))
def get_metadata_lines(self, name):
return yield_lines(self.get_metadata(name))
def resource_isdir(self,resource_name):
return self._isdir(self._fn(self.module_path, resource_name))
def metadata_isdir(self,name):
return self.egg_info and self._isdir(self._fn(self.egg_info,name))
def resource_listdir(self,resource_name):
return self._listdir(self._fn(self.module_path,resource_name))
def metadata_listdir(self,name):
if self.egg_info:
return self._listdir(self._fn(self.egg_info,name))
return []
def run_script(self,script_name,namespace):
script = 'scripts/'+script_name
if not self.has_metadata(script):
raise ResolutionError("No script named %r" % script_name)
script_text = self.get_metadata(script).replace('\r\n','\n')
script_text = script_text.replace('\r','\n')
script_filename = self._fn(self.egg_info,script)
namespace['__file__'] = script_filename
if os.path.exists(script_filename):
execfile(script_filename, namespace, namespace)
else:
from linecache import cache
cache[script_filename] = (
len(script_text), 0, script_text.split('\n'), script_filename
)
script_code = compile(script_text,script_filename,'exec')
exec script_code in namespace, namespace
def _has(self, path):
raise NotImplementedError(
"Can't perform this operation for unregistered loader type"
)
def _isdir(self, path):
raise NotImplementedError(
"Can't perform this operation for unregistered loader type"
)
def _listdir(self, path):
raise NotImplementedError(
"Can't perform this operation for unregistered loader type"
)
def _fn(self, base, resource_name):
return os.path.join(base, *resource_name.split('/'))
def _get(self, path):
if hasattr(self.loader, 'get_data'):
return self.loader.get_data(path)
raise NotImplementedError(
"Can't perform this operation for loaders without 'get_data()'"
)
register_loader_type(object, NullProvider)
class EggProvider(NullProvider):
"""Provider based on a virtual filesystem"""
def __init__(self,module):
NullProvider.__init__(self,module)
self._setup_prefix()
def _setup_prefix(self):
# we assume here that our metadata may be nested inside a "basket"
# of multiple eggs; that's why we use module_path instead of .archive
path = self.module_path
old = None
while path!=old:
if path.lower().endswith('.egg'):
self.egg_name = os.path.basename(path)
self.egg_info = os.path.join(path, 'EGG-INFO')
self.egg_root = path
break
old = path
path, base = os.path.split(path)
class DefaultProvider(EggProvider):
"""Provides access to package resources in the filesystem"""
def _has(self, path):
return os.path.exists(path)
def _isdir(self,path):
return os.path.isdir(path)
def _listdir(self,path):
return os.listdir(path)
def get_resource_stream(self, manager, resource_name):
return open(self._fn(self.module_path, resource_name), 'rb')
def _get(self, path):
stream = open(path, 'rb')
try:
return stream.read()
finally:
stream.close()
register_loader_type(type(None), DefaultProvider)
class EmptyProvider(NullProvider):
"""Provider that returns nothing for all requests"""
_isdir = _has = lambda self,path: False
_get = lambda self,path: ''
_listdir = lambda self,path: []
module_path = None
def __init__(self):
pass
empty_provider = EmptyProvider()
class ZipProvider(EggProvider):
"""Resource support for zips and eggs"""
eagers = None
def __init__(self, module):
EggProvider.__init__(self,module)
self.zipinfo = zipimport._zip_directory_cache[self.loader.archive]
self.zip_pre = self.loader.archive+os.sep
def _zipinfo_name(self, fspath):
# Convert a virtual filename (full path to file) into a zipfile subpath
# usable with the zipimport directory cache for our target archive
if fspath.startswith(self.zip_pre):
return fspath[len(self.zip_pre):]
raise AssertionError(
"%s is not a subpath of %s" % (fspath,self.zip_pre)
)
def _parts(self,zip_path):
# Convert a zipfile subpath into an egg-relative path part list
fspath = self.zip_pre+zip_path # pseudo-fs path
if fspath.startswith(self.egg_root+os.sep):
return fspath[len(self.egg_root)+1:].split(os.sep)
raise AssertionError(
"%s is not a subpath of %s" % (fspath,self.egg_root)
)
def get_resource_filename(self, manager, resource_name):
if not self.egg_name:
raise NotImplementedError(
"resource_filename() only supported for .egg, not .zip"
)
# no need to lock for extraction, since we use temp names
zip_path = self._resource_to_zip(resource_name)
eagers = self._get_eager_resources()
if '/'.join(self._parts(zip_path)) in eagers:
for name in eagers:
self._extract_resource(manager, self._eager_to_zip(name))
return self._extract_resource(manager, zip_path)
def _extract_resource(self, manager, zip_path):
if zip_path in self._index():
for name in self._index()[zip_path]:
last = self._extract_resource(
manager, os.path.join(zip_path, name)
)
return os.path.dirname(last) # return the extracted directory name
zip_stat = self.zipinfo[zip_path]
t,d,size = zip_stat[5], zip_stat[6], zip_stat[3]
date_time = (
(d>>9)+1980, (d>>5)&0xF, d&0x1F, # ymd
(t&0xFFFF)>>11, (t>>5)&0x3F, (t&0x1F) * 2, 0, 0, -1 # hms, etc.
)
timestamp = time.mktime(date_time)
try:
real_path = manager.get_cache_path(
self.egg_name, self._parts(zip_path)
)
if os.path.isfile(real_path):
stat = os.stat(real_path)
if stat.st_size==size and stat.st_mtime==timestamp:
# size and stamp match, don't bother extracting
return real_path
outf, tmpnam = _mkstemp(".$extract", dir=os.path.dirname(real_path))
os.write(outf, self.loader.get_data(zip_path))
os.close(outf)
utime(tmpnam, (timestamp,timestamp))
manager.postprocess(tmpnam, real_path)
try:
rename(tmpnam, real_path)
except os.error:
if os.path.isfile(real_path):
stat = os.stat(real_path)
if stat.st_size==size and stat.st_mtime==timestamp:
# size and stamp match, somebody did it just ahead of
# us, so we're done
return real_path
elif os.name=='nt': # Windows, del old file and retry
unlink(real_path)
rename(tmpnam, real_path)
return real_path
raise
except os.error:
manager.extraction_error() # report a user-friendly error
return real_path
def _get_eager_resources(self):
if self.eagers is None:
eagers = []
for name in ('native_libs.txt', 'eager_resources.txt'):
if self.has_metadata(name):
eagers.extend(self.get_metadata_lines(name))
self.eagers = eagers
return self.eagers
def _index(self):
try:
return self._dirindex
except AttributeError:
ind = {}
for path in self.zipinfo:
parts = path.split(os.sep)
while parts:
parent = os.sep.join(parts[:-1])
if parent in ind:
ind[parent].append(parts[-1])
break
else:
ind[parent] = [parts.pop()]
self._dirindex = ind
return ind
def _has(self, fspath):
zip_path = self._zipinfo_name(fspath)
return zip_path in self.zipinfo or zip_path in self._index()
def _isdir(self,fspath):
return self._zipinfo_name(fspath) in self._index()
def _listdir(self,fspath):
return list(self._index().get(self._zipinfo_name(fspath), ()))
def _eager_to_zip(self,resource_name):
return self._zipinfo_name(self._fn(self.egg_root,resource_name))
def _resource_to_zip(self,resource_name):
return self._zipinfo_name(self._fn(self.module_path,resource_name))
register_loader_type(zipimport.zipimporter, ZipProvider)
class FileMetadata(EmptyProvider):
"""Metadata handler for standalone PKG-INFO files
Usage::
metadata = FileMetadata("/path/to/PKG-INFO")
This provider rejects all data and metadata requests except for PKG-INFO,
which is treated as existing, and will be the contents of the file at
the provided location.
"""
def __init__(self,path):
self.path = path
def has_metadata(self,name):
return name=='PKG-INFO'
def get_metadata(self,name):
if name=='PKG-INFO':
return open(self.path,'rU').read()
raise KeyError("No metadata except PKG-INFO is available")
def get_metadata_lines(self,name):
return yield_lines(self.get_metadata(name))
class PathMetadata(DefaultProvider):
"""Metadata provider for egg directories
Usage::
# Development eggs:
egg_info = "/path/to/PackageName.egg-info"
base_dir = os.path.dirname(egg_info)
metadata = PathMetadata(base_dir, egg_info)
dist_name = os.path.splitext(os.path.basename(egg_info))[0]
dist = Distribution(basedir,project_name=dist_name,metadata=metadata)
# Unpacked egg directories:
egg_path = "/path/to/PackageName-ver-pyver-etc.egg"
metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))
dist = Distribution.from_filename(egg_path, metadata=metadata)
"""
def __init__(self, path, egg_info):
self.module_path = path
self.egg_info = egg_info
class EggMetadata(ZipProvider):
"""Metadata provider for .egg files"""
def __init__(self, importer):
"""Create a metadata provider from a zipimporter"""
self.zipinfo = zipimport._zip_directory_cache[importer.archive]
self.zip_pre = importer.archive+os.sep
self.loader = importer
if importer.prefix:
self.module_path = os.path.join(importer.archive, importer.prefix)
else:
self.module_path = importer.archive
self._setup_prefix()
class ImpWrapper:
"""PEP 302 Importer that wraps Python's "normal" import algorithm"""
def __init__(self, path=None):
self.path = path
def find_module(self, fullname, path=None):
subname = fullname.split(".")[-1]
if subname != fullname and self.path is None:
return None
if self.path is None:
path = None
else:
path = [self.path]
try:
file, filename, etc = imp.find_module(subname, path)
except ImportError:
return None
return ImpLoader(file, filename, etc)
class ImpLoader:
"""PEP 302 Loader that wraps Python's "normal" import algorithm"""
def __init__(self, file, filename, etc):
self.file = file
self.filename = filename
self.etc = etc
def load_module(self, fullname):
try:
mod = imp.load_module(fullname, self.file, self.filename, self.etc)
finally:
if self.file: self.file.close()
# Note: we don't set __loader__ because we want the module to look
# normal; i.e. this is just a wrapper for standard import machinery
return mod
def get_importer(path_item):
"""Retrieve a PEP 302 "importer" for the given path item
If there is no importer, this returns a wrapper around the builtin import
machinery. The returned importer is only cached if it was created by a
path hook.
"""
try:
importer = sys.path_importer_cache[path_item]
except KeyError:
for hook in sys.path_hooks:
try:
importer = hook(path_item)
except ImportError:
pass
else:
break
else:
importer = None
sys.path_importer_cache.setdefault(path_item,importer)
if importer is None:
try:
importer = ImpWrapper(path_item)
except ImportError:
pass
return importer
try:
from pkgutil import get_importer, ImpImporter
except ImportError:
pass # Python 2.3 or 2.4, use our own implementation
else:
ImpWrapper = ImpImporter # Python 2.5, use pkgutil's implementation
del ImpLoader, ImpImporter
_distribution_finders = {}
def register_finder(importer_type, distribution_finder):
"""Register `distribution_finder` to find distributions in sys.path items
`importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
handler), and `distribution_finder` is a callable that, passed a path
item and the importer instance, yields ``Distribution`` instances found on
that path item. See ``pkg_resources.find_on_path`` for an example."""
_distribution_finders[importer_type] = distribution_finder
def find_distributions(path_item, only=False):
"""Yield distributions accessible via `path_item`"""
importer = get_importer(path_item)
finder = _find_adapter(_distribution_finders, importer)
return finder(importer, path_item, only)
def find_in_zip(importer, path_item, only=False):
metadata = EggMetadata(importer)
if metadata.has_metadata('PKG-INFO'):
yield Distribution.from_filename(path_item, metadata=metadata)
if only:
return # don't yield nested distros
for subitem in metadata.resource_listdir('/'):
if subitem.endswith('.egg'):
subpath = os.path.join(path_item, subitem)
for dist in find_in_zip(zipimport.zipimporter(subpath), subpath):
yield dist
register_finder(zipimport.zipimporter, find_in_zip)
def StringIO(*args, **kw):
"""Thunk to load the real StringIO on demand"""
global StringIO
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
return StringIO(*args,**kw)
def find_nothing(importer, path_item, only=False):
return ()
register_finder(object,find_nothing)
def find_on_path(importer, path_item, only=False):
"""Yield distributions accessible on a sys.path directory"""
path_item = _normalize_cached(path_item)
if os.path.isdir(path_item):
if path_item.lower().endswith('.egg'):
# unpacked egg
yield Distribution.from_filename(
path_item, metadata=PathMetadata(
path_item, os.path.join(path_item,'EGG-INFO')
)
)
else:
# scan for .egg and .egg-info in directory
for entry in os.listdir(path_item):
lower = entry.lower()
if lower.endswith('.egg-info'):
fullpath = os.path.join(path_item, entry)
if os.path.isdir(fullpath):
# egg-info directory, allow getting metadata
metadata = PathMetadata(path_item, fullpath)
else:
metadata = FileMetadata(fullpath)
yield Distribution.from_location(
path_item,entry,metadata,precedence=DEVELOP_DIST
)
elif not only and lower.endswith('.egg'):
for dist in find_distributions(os.path.join(path_item, entry)):
yield dist
elif not only and lower.endswith('.egg-link'):
for line in file(os.path.join(path_item, entry)):
if not line.strip(): continue
for item in find_distributions(os.path.join(path_item,line.rstrip())):
yield item
break
register_finder(ImpWrapper,find_on_path)
_namespace_handlers = {}
_namespace_packages = {}
def register_namespace_handler(importer_type, namespace_handler):
"""Register `namespace_handler` to declare namespace packages
`importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
handler), and `namespace_handler` is a callable like this::
def namespace_handler(importer,path_entry,moduleName,module):
# return a path_entry to use for child packages
Namespace handlers are only called if the importer object has already
agreed that it can handle the relevant path item, and they should only
return a subpath if the module __path__ does not already contain an
equivalent subpath. For an example namespace handler, see
``pkg_resources.file_ns_handler``.
"""
_namespace_handlers[importer_type] = namespace_handler
def _handle_ns(packageName, path_item):
"""Ensure that named package includes a subpath of path_item (if needed)"""
importer = get_importer(path_item)
if importer is None:
return None
loader = importer.find_module(packageName)
if loader is None:
return None
module = sys.modules.get(packageName)
if module is None:
module = sys.modules[packageName] = new.module(packageName)
module.__path__ = []; _set_parent_ns(packageName)
elif not hasattr(module,'__path__'):
raise TypeError("Not a package:", packageName)
handler = _find_adapter(_namespace_handlers, importer)
subpath = handler(importer,path_item,packageName,module)
if subpath is not None:
path = module.__path__; path.append(subpath)
loader.load_module(packageName); module.__path__ = path
return subpath
def declare_namespace(packageName):
"""Declare that package 'packageName' is a namespace package"""
imp.acquire_lock()
try:
if packageName in _namespace_packages:
return
path, parent = sys.path, None
if '.' in packageName:
parent = '.'.join(packageName.split('.')[:-1])
declare_namespace(parent)
__import__(parent)
try:
path = sys.modules[parent].__path__
except AttributeError:
raise TypeError("Not a package:", parent)
# Track what packages are namespaces, so when new path items are added,
# they can be updated
_namespace_packages.setdefault(parent,[]).append(packageName)
_namespace_packages.setdefault(packageName,[])
for path_item in path:
# Ensure all the parent's path items are reflected in the child,
# if they apply
_handle_ns(packageName, path_item)
finally:
imp.release_lock()
def fixup_namespace_packages(path_item, parent=None):
"""Ensure that previously-declared namespace packages include path_item"""
imp.acquire_lock()
try:
for package in _namespace_packages.get(parent,()):
subpath = _handle_ns(package, path_item)
if subpath: fixup_namespace_packages(subpath,package)
finally:
imp.release_lock()
def file_ns_handler(importer, path_item, packageName, module):
"""Compute an ns-package subpath for a filesystem or zipfile importer"""
subpath = os.path.join(path_item, packageName.split('.')[-1])
normalized = _normalize_cached(subpath)
for item in module.__path__:
if _normalize_cached(item)==normalized:
break
else:
# Only return the path if it's not already there
return subpath
register_namespace_handler(ImpWrapper,file_ns_handler)
register_namespace_handler(zipimport.zipimporter,file_ns_handler)
def null_ns_handler(importer, path_item, packageName, module):
return None
register_namespace_handler(object,null_ns_handler)
def normalize_path(filename):
"""Normalize a file/dir name for comparison purposes"""
return os.path.normcase(os.path.realpath(filename))
def _normalize_cached(filename,_cache={}):
try:
return _cache[filename]
except KeyError:
_cache[filename] = result = normalize_path(filename)
return result
def _set_parent_ns(packageName):
parts = packageName.split('.')
name = parts.pop()
if parts:
parent = '.'.join(parts)
setattr(sys.modules[parent], name, sys.modules[packageName])
def yield_lines(strs):
"""Yield non-empty/non-comment lines of a ``basestring`` or sequence"""
if isinstance(strs,basestring):
for s in strs.splitlines():
s = s.strip()
if s and not s.startswith('#'): # skip blank lines/comments
yield s
else:
for ss in strs:
for s in yield_lines(ss):
yield s
LINE_END = re.compile(r"\s*(#.*)?$").match # whitespace and comment
CONTINUE = re.compile(r"\s*\\\s*(#.*)?$").match # line continuation
DISTRO = re.compile(r"\s*((\w|[-.])+)").match # Distribution or extra
VERSION = re.compile(r"\s*(<=?|>=?|==|!=)\s*((\w|[-.])+)").match # ver. info
COMMA = re.compile(r"\s*,").match # comma between items
OBRACKET = re.compile(r"\s*\[").match
CBRACKET = re.compile(r"\s*\]").match
MODULE = re.compile(r"\w+(\.\w+)*$").match
EGG_NAME = re.compile(
r"(?P<name>[^-]+)"
r"( -(?P<ver>[^-]+) (-py(?P<pyver>[^-]+) (-(?P<plat>.+))? )? )?",
re.VERBOSE | re.IGNORECASE
).match
component_re = re.compile(r'(\d+ | [a-z]+ | \.| -)', re.VERBOSE)
replace = {'pre':'c', 'preview':'c','-':'final-','rc':'c','dev':'@'}.get
def _parse_version_parts(s):
for part in component_re.split(s):
part = replace(part,part)
if not part or part=='.':
continue
if part[:1] in '0123456789':
yield part.zfill(8) # pad for numeric comparison
else:
yield '*'+part
yield '*final' # ensure that alpha/beta/candidate are before final
def parse_version(s):
"""Convert a version string to a chronologically-sortable key
This is a rough cross between distutils' StrictVersion and LooseVersion;
if you give it versions that would work with StrictVersion, then it behaves
the same; otherwise it acts like a slightly-smarter LooseVersion. It is
*possible* to create pathological version coding schemes that will fool
this parser, but they should be very rare in practice.
The returned value will be a tuple of strings. Numeric portions of the
version are padded to 8 digits so they will compare numerically, but
without relying on how numbers compare relative to strings. Dots are
dropped, but dashes are retained. Trailing zeros between alpha segments
or dashes are suppressed, so that e.g. "2.4.0" is considered the same as
"2.4". Alphanumeric parts are lower-cased.
The algorithm assumes that strings like "-" and any alpha string that
alphabetically follows "final" represents a "patch level". So, "2.4-1"
is assumed to be a branch or patch of "2.4", and therefore "2.4.1" is
considered newer than "2.4-1", whic in turn is newer than "2.4".
Strings like "a", "b", "c", "alpha", "beta", "candidate" and so on (that
come before "final" alphabetically) are assumed to be pre-release versions,
so that the version "2.4" is considered newer than "2.4a1".
Finally, to handle miscellaneous cases, the strings "pre", "preview", and
"rc" are treated as if they were "c", i.e. as though they were release
candidates, and therefore are not as new as a version string that does not
contain them.
"""
parts = []
for part in _parse_version_parts(s.lower()):
if part.startswith('*'):
if part<'*final': # remove '-' before a prerelease tag
while parts and parts[-1]=='*final-': parts.pop()
# remove trailing zeros from each series of numeric parts
while parts and parts[-1]=='00000000':
parts.pop()
parts.append(part)
return tuple(parts)
class EntryPoint(object):
"""Object representing an advertised importable object"""
def __init__(self, name, module_name, attrs=(), extras=(), dist=None):
if not MODULE(module_name):
raise ValueError("Invalid module name", module_name)
self.name = name
self.module_name = module_name
self.attrs = tuple(attrs)
self.extras = Requirement.parse(("x[%s]" % ','.join(extras))).extras
self.dist = dist
def __str__(self):
s = "%s = %s" % (self.name, self.module_name)
if self.attrs:
s += ':' + '.'.join(self.attrs)
if self.extras:
s += ' [%s]' % ','.join(self.extras)
return s
def __repr__(self):
return "EntryPoint.parse(%r)" % str(self)
def load(self, require=True, env=None, installer=None):
if require: self.require(env, installer)
entry = __import__(self.module_name, globals(),globals(), ['__name__'])
for attr in self.attrs:
try:
entry = getattr(entry,attr)
except AttributeError:
raise ImportError("%r has no %r attribute" % (entry,attr))
return entry
def require(self, env=None, installer=None):
if self.extras and not self.dist:
raise UnknownExtra("Can't require() without a distribution", self)
map(working_set.add,
working_set.resolve(self.dist.requires(self.extras),env,installer))
#@classmethod
def parse(cls, src, dist=None):
"""Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1,extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional
"""
try:
attrs = extras = ()
name,value = src.split('=',1)
if '[' in value:
value,extras = value.split('[',1)
req = Requirement.parse("x["+extras)
if req.specs: raise ValueError
extras = req.extras
if ':' in value:
value,attrs = value.split(':',1)
if not MODULE(attrs.rstrip()):
raise ValueError
attrs = attrs.rstrip().split('.')
except ValueError:
raise ValueError(
"EntryPoint must be in 'name=module:attrs [extras]' format",
src
)
else:
return cls(name.strip(), value.strip(), attrs, extras, dist)
parse = classmethod(parse)
#@classmethod
def parse_group(cls, group, lines, dist=None):
"""Parse an entry point group"""
if not MODULE(group):
raise ValueError("Invalid group name", group)
this = {}
for line in yield_lines(lines):
ep = cls.parse(line, dist)
if ep.name in this:
raise ValueError("Duplicate entry point", group, ep.name)
this[ep.name]=ep
return this
parse_group = classmethod(parse_group)
#@classmethod
def parse_map(cls, data, dist=None):
"""Parse a map of entry point groups"""
if isinstance(data,dict):
data = data.items()
else:
data = split_sections(data)
maps = {}
for group, lines in data:
if group is None:
if not lines:
continue
raise ValueError("Entry points must be listed in groups")
group = group.strip()
if group in maps:
raise ValueError("Duplicate group name", group)
maps[group] = cls.parse_group(group, lines, dist)
return maps
parse_map = classmethod(parse_map)
class Distribution(object):
"""Wrap an actual or potential sys.path entry w/metadata"""
def __init__(self,
location=None, metadata=None, project_name=None, version=None,
py_version=PY_MAJOR, platform=None, precedence = EGG_DIST
):
self.project_name = safe_name(project_name or 'Unknown')
if version is not None:
self._version = safe_version(version)
self.py_version = py_version
self.platform = platform
self.location = location
self.precedence = precedence
self._provider = metadata or empty_provider
#@classmethod
def from_location(cls,location,basename,metadata=None,**kw):
project_name, version, py_version, platform = [None]*4
basename, ext = os.path.splitext(basename)
if ext.lower() in (".egg",".egg-info"):
match = EGG_NAME(basename)
if match:
project_name, version, py_version, platform = match.group(
'name','ver','pyver','plat'
)
return cls(
location, metadata, project_name=project_name, version=version,
py_version=py_version, platform=platform, **kw
)
from_location = classmethod(from_location)
hashcmp = property(
lambda self: (
getattr(self,'parsed_version',()), self.precedence, self.key,
-len(self.location or ''), self.location, self.py_version,
self.platform
)
)
def __cmp__(self, other): return cmp(self.hashcmp, other)
def __hash__(self): return hash(self.hashcmp)
# These properties have to be lazy so that we don't have to load any
# metadata until/unless it's actually needed. (i.e., some distributions
# may not know their name or version without loading PKG-INFO)
#@property
def key(self):
try:
return self._key
except AttributeError:
self._key = key = self.project_name.lower()
return key
key = property(key)
#@property
def parsed_version(self):
try:
return self._parsed_version
except AttributeError:
self._parsed_version = pv = parse_version(self.version)
return pv
parsed_version = property(parsed_version)
#@property
def version(self):
try:
return self._version
except AttributeError:
for line in self._get_metadata('PKG-INFO'):
if line.lower().startswith('version:'):
self._version = safe_version(line.split(':',1)[1].strip())
return self._version
else:
raise ValueError(
"Missing 'Version:' header and/or PKG-INFO file", self
)
version = property(version)
#@property
def _dep_map(self):
try:
return self.__dep_map
except AttributeError:
dm = self.__dep_map = {None: []}
for name in 'requires.txt', 'depends.txt':
for extra,reqs in split_sections(self._get_metadata(name)):
if extra: extra = safe_extra(extra)
dm.setdefault(extra,[]).extend(parse_requirements(reqs))
return dm
_dep_map = property(_dep_map)
def requires(self,extras=()):
"""List of Requirements needed for this distro if `extras` are used"""
dm = self._dep_map
deps = []
deps.extend(dm.get(None,()))
for ext in extras:
try:
deps.extend(dm[safe_extra(ext)])
except KeyError:
raise UnknownExtra(
"%s has no such extra feature %r" % (self, ext)
)
return deps
def _get_metadata(self,name):
if self.has_metadata(name):
for line in self.get_metadata_lines(name):
yield line
def activate(self,path=None):
"""Ensure distribution is importable on `path` (default=sys.path)"""
if path is None: path = sys.path
self.insert_on(path)
if path is sys.path:
fixup_namespace_packages(self.location)
map(declare_namespace, self._get_metadata('namespace_packages.txt'))
def egg_name(self):
"""Return what this distribution's standard .egg filename should be"""
filename = "%s-%s-py%s" % (
to_filename(self.project_name), to_filename(self.version),
self.py_version or PY_MAJOR
)
if self.platform:
filename += '-'+self.platform
return filename
def __repr__(self):
if self.location:
return "%s (%s)" % (self,self.location)
else:
return str(self)
def __str__(self):
try: version = getattr(self,'version',None)
except ValueError: version = None
version = version or "[unknown version]"
return "%s %s" % (self.project_name,version)
def __getattr__(self,attr):
"""Delegate all unrecognized public attributes to .metadata provider"""
if attr.startswith('_'):
raise AttributeError,attr
return getattr(self._provider, attr)
#@classmethod
def from_filename(cls,filename,metadata=None, **kw):
return cls.from_location(
_normalize_cached(filename), os.path.basename(filename), metadata,
**kw
)
from_filename = classmethod(from_filename)
def as_requirement(self):
"""Return a ``Requirement`` that matches this distribution exactly"""
return Requirement.parse('%s==%s' % (self.project_name, self.version))
def load_entry_point(self, group, name):
"""Return the `name` entry point of `group` or raise ImportError"""
ep = self.get_entry_info(group,name)
if ep is None:
raise ImportError("Entry point %r not found" % ((group,name),))
return ep.load()
def get_entry_map(self, group=None):
"""Return the entry point map for `group`, or the full entry map"""
try:
ep_map = self._ep_map
except AttributeError:
ep_map = self._ep_map = EntryPoint.parse_map(
self._get_metadata('entry_points.txt'), self
)
if group is not None:
return ep_map.get(group,{})
return ep_map
def get_entry_info(self, group, name):
"""Return the EntryPoint object for `group`+`name`, or ``None``"""
return self.get_entry_map(group).get(name)
def insert_on(self, path, loc = None):
"""Insert self.location in path before its nearest parent directory"""
loc = loc or self.location
if not loc:
return
if path is sys.path:
self.check_version_conflict()
nloc = _normalize_cached(loc)
bdir = os.path.dirname(nloc)
npath= map(_normalize_cached, path)
bp = None
for p, item in enumerate(npath):
if item==nloc:
break
elif item==bdir and self.precedence==EGG_DIST:
# if it's an .egg, give it precedence over its directory
path.insert(p, loc)
npath.insert(p, nloc)
break
else:
path.append(loc)
return
# p is the spot where we found or inserted loc; now remove duplicates
while 1:
try:
np = npath.index(nloc, p+1)
except ValueError:
break
else:
del npath[np], path[np]
p = np # ha!
return
def check_version_conflict(self):
if self.key=='setuptools':
return # ignore the inevitable setuptools self-conflicts :(
nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))
loc = normalize_path(self.location)
for modname in self._get_metadata('top_level.txt'):
if (modname not in sys.modules or modname in nsp
or modname in _namespace_packages
):
continue
fn = getattr(sys.modules[modname], '__file__', None)
if fn and normalize_path(fn).startswith(loc):
continue
issue_warning(
"Module %s was already imported from %s, but %s is being added"
" to sys.path" % (modname, fn, self.location),
)
def has_version(self):
try:
self.version
except ValueError:
issue_warning("Unbuilt egg for "+repr(self))
return False
return True
def clone(self,**kw):
"""Copy this distribution, substituting in any changed keyword args"""
for attr in (
'project_name', 'version', 'py_version', 'platform', 'location',
'precedence'
):
kw.setdefault(attr, getattr(self,attr,None))
kw.setdefault('metadata', self._provider)
return self.__class__(**kw)
#@property
def extras(self):
return [dep for dep in self._dep_map if dep]
extras = property(extras)
def issue_warning(*args,**kw):
level = 1
g = globals()
try:
# find the first stack frame that is *not* code in
# the pkg_resources module, to use for the warning
while sys._getframe(level).f_globals is g:
level += 1
except ValueError:
pass
from warnings import warn
warn(stacklevel = level+1, *args, **kw)
def parse_requirements(strs):
"""Yield ``Requirement`` objects for each specification in `strs`
`strs` must be an instance of ``basestring``, or a (possibly-nested)
iterable thereof.
"""
# create a steppable iterator, so we can handle \-continuations
lines = iter(yield_lines(strs))
def scan_list(ITEM,TERMINATOR,line,p,groups,item_name):
items = []
while not TERMINATOR(line,p):
if CONTINUE(line,p):
try:
line = lines.next(); p = 0
except StopIteration:
raise ValueError(
"\\ must not appear on the last nonblank line"
)
match = ITEM(line,p)
if not match:
raise ValueError("Expected "+item_name+" in",line,"at",line[p:])
items.append(match.group(*groups))
p = match.end()
match = COMMA(line,p)
if match:
p = match.end() # skip the comma
elif not TERMINATOR(line,p):
raise ValueError(
"Expected ',' or end-of-list in",line,"at",line[p:]
)
match = TERMINATOR(line,p)
if match: p = match.end() # skip the terminator, if any
return line, p, items
for line in lines:
match = DISTRO(line)
if not match:
raise ValueError("Missing distribution spec", line)
project_name = match.group(1)
p = match.end()
extras = []
match = OBRACKET(line,p)
if match:
p = match.end()
line, p, extras = scan_list(
DISTRO, CBRACKET, line, p, (1,), "'extra' name"
)
line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec")
specs = [(op,safe_version(val)) for op,val in specs]
yield Requirement(project_name, specs, extras)
def _sort_dists(dists):
tmp = [(dist.hashcmp,dist) for dist in dists]
tmp.sort()
dists[::-1] = [d for hc,d in tmp]
class Requirement:
def __init__(self, project_name, specs, extras):
"""DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!"""
self.unsafe_name, project_name = project_name, safe_name(project_name)
self.project_name, self.key = project_name, project_name.lower()
index = [(parse_version(v),state_machine[op],op,v) for op,v in specs]
index.sort()
self.specs = [(op,ver) for parsed,trans,op,ver in index]
self.index, self.extras = index, tuple(map(safe_extra,extras))
self.hashCmp = (
self.key, tuple([(op,parsed) for parsed,trans,op,ver in index]),
frozenset(self.extras)
)
self.__hash = hash(self.hashCmp)
def __str__(self):
specs = ','.join([''.join(s) for s in self.specs])
extras = ','.join(self.extras)
if extras: extras = '[%s]' % extras
return '%s%s%s' % (self.project_name, extras, specs)
def __eq__(self,other):
return isinstance(other,Requirement) and self.hashCmp==other.hashCmp
def __contains__(self,item):
if isinstance(item,Distribution):
if item.key <> self.key: return False
if self.index: item = item.parsed_version # only get if we need it
elif isinstance(item,basestring):
item = parse_version(item)
last = None
for parsed,trans,op,ver in self.index:
action = trans[cmp(item,parsed)]
if action=='F': return False
elif action=='T': return True
elif action=='+': last = True
elif action=='-' or last is None: last = False
if last is None: last = True # no rules encountered
return last
def __hash__(self):
return self.__hash
def __repr__(self): return "Requirement.parse(%r)" % str(self)
#@staticmethod
def parse(s):
reqs = list(parse_requirements(s))
if reqs:
if len(reqs)==1:
return reqs[0]
raise ValueError("Expected only one requirement", s)
raise ValueError("No requirements found", s)
parse = staticmethod(parse)
state_machine = {
# =><
'<' : '--T',
'<=': 'T-T',
'>' : 'F+F',
'>=': 'T+F',
'==': 'T..',
'!=': 'F++',
}
def _get_mro(cls):
"""Get an mro for a type or classic class"""
if not isinstance(cls,type):
class cls(cls,object): pass
return cls.__mro__[1:]
return cls.__mro__
def _find_adapter(registry, ob):
"""Return an adapter factory for `ob` from `registry`"""
for t in _get_mro(getattr(ob, '__class__', type(ob))):
if t in registry:
return registry[t]
def ensure_directory(path):
"""Ensure that the parent directory of `path` exists"""
dirname = os.path.dirname(path)
if not os.path.isdir(dirname):
os.makedirs(dirname)
def split_sections(s):
"""Split a string or iterable thereof into (section,content) pairs
Each ``section`` is a stripped version of the section header ("[section]")
and each ``content`` is a list of stripped lines excluding blank lines and
comment-only lines. If there are any such lines before the first section
header, they're returned in a first ``section`` of ``None``.
"""
section = None
content = []
for line in yield_lines(s):
if line.startswith("["):
if line.endswith("]"):
if section or content:
yield section, content
section = line[1:-1].strip()
content = []
else:
raise ValueError("Invalid section heading", line)
else:
content.append(line)
# wrap up last segment
yield section, content
def _mkstemp(*args,**kw):
from tempfile import mkstemp
old_open = os.open
try:
os.open = os_open # temporarily bypass sandboxing
return mkstemp(*args,**kw)
finally:
os.open = old_open # and then put it back
# Set up global resource manager
_manager = ResourceManager()
def _initialize(g):
for name in dir(_manager):
if not name.startswith('_'):
g[name] = getattr(_manager, name)
_initialize(globals())
# Prepare the master working set and make the ``require()`` API available
working_set = WorkingSet()
try:
# Does the main program list any requirements?
from __main__ import __requires__
except ImportError:
pass # No: just use the default working set based on sys.path
else:
# Yes: ensure the requirements are met, by prefixing sys.path if necessary
try:
working_set.require(__requires__)
except VersionConflict: # try it without defaults already on sys.path
working_set = WorkingSet([]) # by starting with an empty path
for dist in working_set.resolve(
parse_requirements(__requires__), Environment()
):
working_set.add(dist)
for entry in sys.path: # add any missing entries from sys.path
if entry not in working_set.entries:
working_set.add_entry(entry)
sys.path[:] = working_set.entries # then copy back to sys.path
require = working_set.require
iter_entry_points = working_set.iter_entry_points
add_activation_listener = working_set.subscribe
run_script = working_set.run_script
run_main = run_script # backward compatibility
# Activate all distributions already on sys.path, and ensure that
# all distributions added to the working set in the future (e.g. by
# calling ``require()``) will get activated as well.
add_activation_listener(lambda dist: dist.activate())
working_set.entries=[]; map(working_set.add_entry,sys.path) # match order
|
Ernesto99/odoo | refs/heads/8.0 | addons/hr_timesheet_invoice/wizard/hr_timesheet_invoice_create.py | 337 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
from openerp.tools.translate import _
class hr_timesheet_invoice_create(osv.osv_memory):
_name = 'hr.timesheet.invoice.create'
_description = 'Create invoice from timesheet'
_columns = {
'date': fields.boolean('Date', help='The real date of each work will be displayed on the invoice'),
'time': fields.boolean('Time spent', help='The time of each work done will be displayed on the invoice'),
'name': fields.boolean('Description', help='The detail of each work done will be displayed on the invoice'),
'price': fields.boolean('Cost', help='The cost of each work done will be displayed on the invoice. You probably don\'t want to check this'),
'product': fields.many2one('product.product', 'Force Product', help='Fill this field only if you want to force to use a specific product. Keep empty to use the real product that comes from the cost.'),
}
_defaults = {
'date': 1,
'name': 1,
}
def view_init(self, cr, uid, fields, context=None):
"""
This function checks for precondition before wizard executes
@param self: The object pointer
@param cr: the current row, from the database cursor,
@param uid: the current user’s ID for security checks,
@param fields: List of fields for default value
@param context: A standard dictionary for contextual values
"""
analytic_obj = self.pool.get('account.analytic.line')
data = context and context.get('active_ids', [])
for analytic in analytic_obj.browse(cr, uid, data, context=context):
if analytic.invoice_id:
raise osv.except_osv(_('Warning!'), _("Invoice is already linked to some of the analytic line(s)!"))
def do_create(self, cr, uid, ids, context=None):
data = self.read(cr, uid, ids, context=context)[0]
# Create an invoice based on selected timesheet lines
invs = self.pool.get('account.analytic.line').invoice_cost_create(cr, uid, context['active_ids'], data, context=context)
mod_obj = self.pool.get('ir.model.data')
act_obj = self.pool.get('ir.actions.act_window')
mod_ids = mod_obj.search(cr, uid, [('name', '=', 'action_invoice_tree1')], context=context)
res_id = mod_obj.read(cr, uid, mod_ids, ['res_id'], context=context)[0]['res_id']
act_win = act_obj.read(cr, uid, [res_id], context=context)[0]
act_win['domain'] = [('id','in',invs),('type','=','out_invoice')]
act_win['name'] = _('Invoices')
return act_win
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
epssy/hue | refs/heads/master | desktop/core/ext-py/markdown/markdown/extensions/codehilite.py | 130 | #!/usr/bin/python
"""
CodeHilite Extension for Python-Markdown
========================================
Adds code/syntax highlighting to standard Python-Markdown code blocks.
Copyright 2006-2008 [Waylan Limberg](http://achinghead.com/).
Project website: <http://www.freewisdom.org/project/python-markdown/CodeHilite>
Contact: markdown@freewisdom.org
License: BSD (see ../docs/LICENSE for details)
Dependencies:
* [Python 2.3+](http://python.org/)
* [Markdown 2.0+](http://www.freewisdom.org/projects/python-markdown/)
* [Pygments](http://pygments.org/)
"""
import markdown
# --------------- CONSTANTS YOU MIGHT WANT TO MODIFY -----------------
try:
TAB_LENGTH = markdown.TAB_LENGTH
except AttributeError:
TAB_LENGTH = 4
# ------------------ The Main CodeHilite Class ----------------------
class CodeHilite:
"""
Determine language of source code, and pass it into the pygments hilighter.
Basic Usage:
>>> code = CodeHilite(src = 'some text')
>>> html = code.hilite()
* src: Source string or any object with a .readline attribute.
* linenos: (Boolen) Turn line numbering 'on' or 'off' (off by default).
* css_class: Set class name of wrapper div ('codehilite' by default).
Low Level Usage:
>>> code = CodeHilite()
>>> code.src = 'some text' # String or anything with a .readline attr.
>>> code.linenos = True # True or False; Turns line numbering on or of.
>>> html = code.hilite()
"""
def __init__(self, src=None, linenos=False, css_class="codehilite"):
self.src = src
self.lang = None
self.linenos = linenos
self.css_class = css_class
def hilite(self):
"""
Pass code to the [Pygments](http://pygments.pocoo.org/) highliter with
optional line numbers. The output should then be styled with css to
your liking. No styles are applied by default - only styling hooks
(i.e.: <span class="k">).
returns : A string of html.
"""
self.src = self.src.strip('\n')
self._getLang()
try:
from pygments import highlight
from pygments.lexers import get_lexer_by_name, guess_lexer, \
TextLexer
from pygments.formatters import HtmlFormatter
except ImportError:
# just escape and pass through
txt = self._escape(self.src)
if self.linenos:
txt = self._number(txt)
else :
txt = '<div class="%s"><pre>%s</pre></div>\n'% \
(self.css_class, txt)
return txt
else:
try:
lexer = get_lexer_by_name(self.lang)
except ValueError:
try:
lexer = guess_lexer(self.src)
except ValueError:
lexer = TextLexer()
formatter = HtmlFormatter(linenos=self.linenos,
cssclass=self.css_class)
return highlight(self.src, lexer, formatter)
def _escape(self, txt):
""" basic html escaping """
txt = txt.replace('&', '&')
txt = txt.replace('<', '<')
txt = txt.replace('>', '>')
txt = txt.replace('"', '"')
return txt
def _number(self, txt):
""" Use <ol> for line numbering """
# Fix Whitespace
txt = txt.replace('\t', ' '*TAB_LENGTH)
txt = txt.replace(" "*4, " ")
txt = txt.replace(" "*3, " ")
txt = txt.replace(" "*2, " ")
# Add line numbers
lines = txt.splitlines()
txt = '<div class="codehilite"><pre><ol>\n'
for line in lines:
txt += '\t<li>%s</li>\n'% line
txt += '</ol></pre></div>\n'
return txt
def _getLang(self):
"""
Determines language of a code block from shebang lines and whether said
line should be removed or left in place. If the sheband line contains a
path (even a single /) then it is assumed to be a real shebang lines and
left alone. However, if no path is given (e.i.: #!python or :::python)
then it is assumed to be a mock shebang for language identifitation of a
code fragment and removed from the code block prior to processing for
code highlighting. When a mock shebang (e.i: #!python) is found, line
numbering is turned on. When colons are found in place of a shebang
(e.i.: :::python), line numbering is left in the current state - off
by default.
"""
import re
#split text into lines
lines = self.src.split("\n")
#pull first line to examine
fl = lines.pop(0)
c = re.compile(r'''
(?:(?:::+)|(?P<shebang>[#]!)) # Shebang or 2 or more colons.
(?P<path>(?:/\w+)*[/ ])? # Zero or 1 path
(?P<lang>[\w+-]*) # The language
''', re.VERBOSE)
# search first line for shebang
m = c.search(fl)
if m:
# we have a match
try:
self.lang = m.group('lang').lower()
except IndexError:
self.lang = None
if m.group('path'):
# path exists - restore first line
lines.insert(0, fl)
if m.group('shebang'):
# shebang exists - use line numbers
self.linenos = True
else:
# No match
lines.insert(0, fl)
self.src = "\n".join(lines).strip("\n")
# ------------------ The Markdown Extension -------------------------------
class HiliteTreeprocessor(markdown.treeprocessors.Treeprocessor):
""" Hilight source code in code blocks. """
def run(self, root):
""" Find code blocks and store in htmlStash. """
blocks = root.getiterator('pre')
for block in blocks:
children = block.getchildren()
if len(children) == 1 and children[0].tag == 'code':
code = CodeHilite(children[0].text,
linenos=self.config['force_linenos'][0],
css_class=self.config['css_class'][0])
placeholder = self.markdown.htmlStash.store(code.hilite(),
safe=True)
# Clear codeblock in etree instance
block.clear()
# Change to p element which will later
# be removed when inserting raw html
block.tag = 'p'
block.text = placeholder
class CodeHiliteExtension(markdown.Extension):
""" Add source code hilighting to markdown codeblocks. """
def __init__(self, configs):
# define default configs
self.config = {
'force_linenos' : [False, "Force line numbers - Default: False"],
'css_class' : ["codehilite",
"Set class name for wrapper <div> - Default: codehilite"],
}
# Override defaults with user settings
for key, value in configs:
self.setConfig(key, value)
def extendMarkdown(self, md, md_globals):
""" Add HilitePostprocessor to Markdown instance. """
hiliter = HiliteTreeprocessor(md)
hiliter.config = self.config
md.treeprocessors.add("hilite", hiliter, "_begin")
def makeExtension(configs={}):
return CodeHiliteExtension(configs=configs)
|
formstack/datadog-gearman_mysql | refs/heads/master | checks.d/gearman_mysql.py | 1 | """
The MIT License (MIT)
Copyright (c) 2016 Formstack, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import pymysql
from checks import AgentCheck
from collections import defaultdict
from contextlib import closing, contextmanager
class GearmanMySQLCheck(AgentCheck):
SERVICE_CHECK_NAME = 'gearman_mysql.can_connect'
def __init__(self, name, init_config, agentConfig, instances=None):
AgentCheck.__init__(self, name, init_config, agentConfig, instances)
def check(self, instance):
collected_metrics = None
host, user, password, database, table, port, whitelist = \
self._get_config(instance)
if (not host or not user):
raise Exception("mysql_host and mysql_user are needed.")
with self._connect(host, user, password, port, database) as db:
try:
collected_metrics = self._collect_queue_metrics(db)
except Exception:
self.log.exception("error!")
# Queues in the whitelist are assigned 0 for each priority
# It is overwritten later if there are jobs in the queue for that priority
# This way we do not return no data for these queues, which can lead to misleading graphs
queues = defaultdict(lambda: defaultdict(dict, {0:0, 1:0, 2:0}))
for queue in whitelist:
for priority in [0, 1, 2]:
queues[queue][priority] = 0
for collected_metric in collected_metrics:
queues[collected_metric['function_name']][collected_metric['priority']] = collected_metric['cnt']
for queue in queues:
for priority in [0, 1, 2]:
gauge_tags = [
'queue:%s' % queue,
'priority:%s' % priority,
]
self.gauge('gearman_mysql.queue',
queues[queue][priority],
gauge_tags)
def _get_config(self, instance):
self.host = instance.get('mysql_host', '')
self.user = instance.get('mysql_user', '')
self.password = instance.get('mysql_password', '')
self.database = instance.get('mysql_database', 'gearmand')
self.table = instance.get('mysql_table', 'gearman_queue')
self.port = instance.get('mysql_port', 3306)
self.whitelist = instance.get('whitelist', [])
return (self.host, self.user, self.password, self.database,
self.table, self.port, self.whitelist)
@contextmanager
def _connect(self, host, user, password, port, database):
self.service_check_tags = [
'server:%s' % host,
'port:%s' % port
]
db = None
try:
db = pymysql.connect(
host=host,
port=port,
user=user,
passwd=password,
db=database,
)
self.log.debug("Connected to MySQL")
self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.OK,
tags=self.service_check_tags)
yield db
except Exception:
self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL,
tags=self.service_check_tags)
raise
finally:
if db:
db.close()
def _collect_queue_metrics(self, db):
with closing(db.cursor(pymysql.cursors.DictCursor)) as cursor:
cursor.execute("SELECT function_name, priority, count(*) AS cnt "
"FROM " + self.table + " "
"GROUP BY function_name, priority")
results = cursor.fetchall()
return results
|
Brett55/moto | refs/heads/master | moto/dynamodb2/urls.py | 18 | from __future__ import unicode_literals
from .responses import DynamoHandler
url_bases = [
"https?://dynamodb.(.+).amazonaws.com"
]
url_paths = {
"{0}/": DynamoHandler.dispatch,
}
|
orione7/plugin.video.streamondemand-pureita | refs/heads/master | lib/mechanize/_mozillacookiejar.py | 149 | """Mozilla / Netscape cookie loading / saving.
Copyright 2002-2006 John J Lee <jjl@pobox.com>
Copyright 1997-1999 Gisle Aas (original libwww-perl code)
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD or ZPL 2.1 licenses (see the file
COPYING.txt included with the distribution).
"""
import re, time, logging
from _clientcookie import reraise_unmasked_exceptions, FileCookieJar, Cookie, \
MISSING_FILENAME_TEXT, LoadError
debug = logging.getLogger("ClientCookie").debug
class MozillaCookieJar(FileCookieJar):
"""
WARNING: you may want to backup your browser's cookies file if you use
this class to save cookies. I *think* it works, but there have been
bugs in the past!
This class differs from CookieJar only in the format it uses to save and
load cookies to and from a file. This class uses the Mozilla/Netscape
`cookies.txt' format. lynx uses this file format, too.
Don't expect cookies saved while the browser is running to be noticed by
the browser (in fact, Mozilla on unix will overwrite your saved cookies if
you change them on disk while it's running; on Windows, you probably can't
save at all while the browser is running).
Note that the Mozilla/Netscape format will downgrade RFC2965 cookies to
Netscape cookies on saving.
In particular, the cookie version and port number information is lost,
together with information about whether or not Path, Port and Discard were
specified by the Set-Cookie2 (or Set-Cookie) header, and whether or not the
domain as set in the HTTP header started with a dot (yes, I'm aware some
domains in Netscape files start with a dot and some don't -- trust me, you
really don't want to know any more about this).
Note that though Mozilla and Netscape use the same format, they use
slightly different headers. The class saves cookies using the Netscape
header by default (Mozilla can cope with that).
"""
magic_re = "#( Netscape)? HTTP Cookie File"
header = """\
# Netscape HTTP Cookie File
# http://www.netscape.com/newsref/std/cookie_spec.html
# This is a generated file! Do not edit.
"""
def _really_load(self, f, filename, ignore_discard, ignore_expires):
now = time.time()
magic = f.readline()
if not re.search(self.magic_re, magic):
f.close()
raise LoadError(
"%s does not look like a Netscape format cookies file" %
filename)
try:
while 1:
line = f.readline()
if line == "": break
# last field may be absent, so keep any trailing tab
if line.endswith("\n"): line = line[:-1]
# skip comments and blank lines XXX what is $ for?
if (line.strip().startswith("#") or
line.strip().startswith("$") or
line.strip() == ""):
continue
domain, domain_specified, path, secure, expires, name, value = \
line.split("\t", 6)
secure = (secure == "TRUE")
domain_specified = (domain_specified == "TRUE")
if name == "":
name = value
value = None
initial_dot = domain.startswith(".")
if domain_specified != initial_dot:
raise LoadError("domain and domain specified flag don't "
"match in %s: %s" % (filename, line))
discard = False
if expires == "":
expires = None
discard = True
# assume path_specified is false
c = Cookie(0, name, value,
None, False,
domain, domain_specified, initial_dot,
path, False,
secure,
expires,
discard,
None,
None,
{})
if not ignore_discard and c.discard:
continue
if not ignore_expires and c.is_expired(now):
continue
self.set_cookie(c)
except:
reraise_unmasked_exceptions((IOError, LoadError))
raise LoadError("invalid Netscape format file %s: %s" %
(filename, line))
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
if filename is None:
if self.filename is not None: filename = self.filename
else: raise ValueError(MISSING_FILENAME_TEXT)
f = open(filename, "w")
try:
debug("Saving Netscape cookies.txt file")
f.write(self.header)
now = time.time()
for cookie in self:
if not ignore_discard and cookie.discard:
debug(" Not saving %s: marked for discard", cookie.name)
continue
if not ignore_expires and cookie.is_expired(now):
debug(" Not saving %s: expired", cookie.name)
continue
if cookie.secure: secure = "TRUE"
else: secure = "FALSE"
if cookie.domain.startswith("."): initial_dot = "TRUE"
else: initial_dot = "FALSE"
if cookie.expires is not None:
expires = str(cookie.expires)
else:
expires = ""
if cookie.value is None:
# cookies.txt regards 'Set-Cookie: foo' as a cookie
# with no name, whereas cookielib regards it as a
# cookie with no value.
name = ""
value = cookie.name
else:
name = cookie.name
value = cookie.value
f.write(
"\t".join([cookie.domain, initial_dot, cookie.path,
secure, expires, name, value])+
"\n")
finally:
f.close()
|
drpaneas/linuxed.gr | refs/heads/master | lib/python2.7/site-packages/pip/_vendor/requests/compat.py | 571 | # -*- coding: utf-8 -*-
"""
pythoncompat
"""
from .packages import chardet
import sys
# -------
# Pythons
# -------
# Syntax sugar.
_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)
#: Python 3.x?
is_py3 = (_ver[0] == 3)
#: Python 3.0.x
is_py30 = (is_py3 and _ver[1] == 0)
#: Python 3.1.x
is_py31 = (is_py3 and _ver[1] == 1)
#: Python 3.2.x
is_py32 = (is_py3 and _ver[1] == 2)
#: Python 3.3.x
is_py33 = (is_py3 and _ver[1] == 3)
#: Python 3.4.x
is_py34 = (is_py3 and _ver[1] == 4)
#: Python 2.7.x
is_py27 = (is_py2 and _ver[1] == 7)
#: Python 2.6.x
is_py26 = (is_py2 and _ver[1] == 6)
#: Python 2.5.x
is_py25 = (is_py2 and _ver[1] == 5)
#: Python 2.4.x
is_py24 = (is_py2 and _ver[1] == 4) # I'm assuming this is not by choice.
# ---------
# Platforms
# ---------
# Syntax sugar.
_ver = sys.version.lower()
is_pypy = ('pypy' in _ver)
is_jython = ('jython' in _ver)
is_ironpython = ('iron' in _ver)
# Assume CPython, if nothing else.
is_cpython = not any((is_pypy, is_jython, is_ironpython))
# Windows-based system.
is_windows = 'win32' in str(sys.platform).lower()
# Standard Linux 2+ system.
is_linux = ('linux' in str(sys.platform).lower())
is_osx = ('darwin' in str(sys.platform).lower())
is_hpux = ('hpux' in str(sys.platform).lower()) # Complete guess.
is_solaris = ('solar==' in str(sys.platform).lower()) # Complete guess.
try:
import simplejson as json
except ImportError:
import json
# ---------
# Specifics
# ---------
if is_py2:
from urllib import quote, unquote, quote_plus, unquote_plus, urlencode, getproxies, proxy_bypass
from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag
from urllib2 import parse_http_list
import cookielib
from Cookie import Morsel
from StringIO import StringIO
from .packages.urllib3.packages.ordered_dict import OrderedDict
from httplib import IncompleteRead
builtin_str = str
bytes = str
str = unicode
basestring = basestring
numeric_types = (int, long, float)
elif is_py3:
from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag
from urllib.request import parse_http_list, getproxies, proxy_bypass
from http import cookiejar as cookielib
from http.cookies import Morsel
from io import StringIO
from collections import OrderedDict
from http.client import IncompleteRead
builtin_str = str
str = str
bytes = bytes
basestring = (str, bytes)
numeric_types = (int, float)
|
sachintaware/sublime-wakatime | refs/heads/master | packages/wakatime/packages/requests/packages/urllib3/util/connection.py | 679 | import socket
try:
from select import poll, POLLIN
except ImportError: # `poll` doesn't exist on OSX and other platforms
poll = False
try:
from select import select
except ImportError: # `select` doesn't exist on AppEngine.
select = False
def is_connection_dropped(conn): # Platform-specific
"""
Returns True if the connection is dropped and should be closed.
:param conn:
:class:`httplib.HTTPConnection` object.
Note: For platforms like AppEngine, this will always return ``False`` to
let the platform handle connection recycling transparently for us.
"""
sock = getattr(conn, 'sock', False)
if sock is False: # Platform-specific: AppEngine
return False
if sock is None: # Connection already closed (such as by httplib).
return True
if not poll:
if not select: # Platform-specific: AppEngine
return False
try:
return select([sock], [], [], 0.0)[0]
except socket.error:
return True
# This version is better on platforms that support it.
p = poll()
p.register(sock, POLLIN)
for (fno, ev) in p.poll(0.0):
if fno == sock.fileno():
# Either data is buffered (bad), or the connection is dropped.
return True
# This function is copied from socket.py in the Python 2.7 standard
# library test suite. Added to its signature is only `socket_options`.
def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None, socket_options=None):
"""Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
An host of '' or port 0 tells the OS to use the default.
"""
host, port = address
err = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socket.socket(af, socktype, proto)
# If provided, set socket level options before connecting.
# This is the only addition urllib3 makes to this function.
_set_socket_options(sock, socket_options)
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(sa)
return sock
except socket.error as _:
err = _
if sock is not None:
sock.close()
sock = None
if err is not None:
raise err
else:
raise socket.error("getaddrinfo returns an empty list")
def _set_socket_options(sock, options):
if options is None:
return
for opt in options:
sock.setsockopt(*opt)
|
geminy/aidear | refs/heads/master | oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/net/data/websocket/echo-request-headers_wsh.py | 57 | # Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# This handler serializes the received headers into a JSON string and sends it
# back to the client. In |headers_in|, the keys are converted to lower-case,
# while the original case is retained for the values.
import json
def web_socket_do_extra_handshake(request):
pass
def web_socket_transfer_data(request):
request.ws_stream.send_message(json.dumps(dict(request.headers_in.items())))
# Wait for closing handshake
request.ws_stream.receive_message()
|
marratj/ansible | refs/heads/devel | test/integration/targets/aws_lambda/files/mini_lambda.py | 139 | from __future__ import print_function
import json
import os
def handler(event, context):
"""
The handler function is the function which gets called each time
the lambda is run.
"""
# printing goes to the cloudwatch log allowing us to simply debug the lambda if we can find
# the log entry.
print("got event:\n" + json.dumps(event))
# if the name parameter isn't present this can throw an exception
# which will result in an amazon chosen failure from the lambda
# which can be completely fine.
name = event["name"]
# we can use environment variables as part of the configuration of the lambda
# which can change the behaviour of the lambda without needing a new upload
extra = os.environ.get("EXTRA_MESSAGE")
if extra is not None and len(extra) > 0:
greeting = "hello {0}. {1}".format(name, extra)
else:
greeting = "hello " + name
return {"message": greeting}
def main():
"""
This main function will normally never be called during normal
lambda use. It is here for testing the lambda program only.
"""
event = {"name": "james"}
context = None
print(handler(event, context))
if __name__ == '__main__':
main()
|
TetraAsh/baruwa2 | refs/heads/master | baruwa/forms/accounts.py | 1 | # -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4
# Baruwa - Web 2.0 MailScanner front-end.
# Copyright (C) 2010-2012 Andrew Colin Kissa <andrew@topdog.za.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""accounts forms"""
from wtforms import PasswordField, validators, DecimalField, RadioField
from wtforms import BooleanField, TextField, SelectField
from wtforms.ext.sqlalchemy.fields import QuerySelectMultipleField
from pylons.i18n.translation import lazy_ugettext as _
from sqlalchemy.orm.exc import NoResultFound
from baruwa.forms import Form
from baruwa.model.accounts import User
from baruwa.model.domains import Domain
from baruwa.model.meta import Session
from baruwa.forms.organizations import check_pw_strength
from baruwa.forms import TIMEZONE_TUPLES, REQ_MSG, EMAIL_MSG
from baruwa.forms.messages import MultiCheckboxField
ACCOUNT_TYPES = (
('3', _('User')),
('2', _('Domain admin')),
('1', _('Administrator')),
)
def check_password(form, field):
"check password strength"
check_pw_strength(field.data)
def check_domain(form, field):
"check domain"
domain = field.data.split('@')[1]
try:
Session.query(Domain).filter(Domain.name == domain).one()
except NoResultFound:
raise validators.ValidationError(
_(u'The domain: %(dom)s is not local')
% dict(dom=domain)
)
def check_account(form, field):
"check account"
if field.data == 3 and not form.domains.data:
raise validators.ValidationError(
_(u'Please select atleast one domain')
)
def can_reset(form, field):
"check account is legible to reset"
try:
user = Session.query(User)\
.filter(User.email == field.data)\
.one()
if user.account_type != 3:
raise validators.ValidationError(
_("Admin accounts cannot be reset via the web"))
except NoResultFound:
raise validators.ValidationError(_("Account not found"))
class AddUserForm(Form):
"""Add user"""
username = TextField(_('Username'),
[validators.Required(message=REQ_MSG),
validators.Length(min=4, max=254)])
firstname = TextField(_('First name'),
[validators.Length(max=254)])
lastname = TextField(_('Last name'),
[validators.Length(max=254)])
password1 = PasswordField(_('New Password'), [check_password,
validators.Required(message=REQ_MSG),
validators.EqualTo('password2',
message=_('Passwords must match'))])
password2 = PasswordField(_('Retype Password'),
[validators.Required(message=REQ_MSG)])
email = TextField(_('Email address'),
[validators.Required(message=REQ_MSG),
validators.Email(message=EMAIL_MSG)])
timezone = SelectField(_('Timezone'), choices=TIMEZONE_TUPLES)
account_type = SelectField(_('Account type'),
choices=list(ACCOUNT_TYPES))
domains = QuerySelectMultipleField(_('Domains'),
get_label='name',
allow_blank=True)
active = BooleanField(_('Enabled'))
send_report = BooleanField(_('Send reports'))
spam_checks = BooleanField(_('Enable spam checks'), default=True)
low_score = DecimalField(_('Probable spam score'), places=1, default=0)
high_score = DecimalField(_('Definite spam score'), places=1, default=0)
def validate_domains(form, field):
if int(form.account_type.data) == 3 and not field.data:
raise validators.ValidationError(
_(u'Please select atleast one domain'))
class EditUserForm(Form):
"""Edit user"""
username = TextField(_('Username'), [validators.Required(message=REQ_MSG),
validators.Length(min=4, max=254)])
firstname = TextField(_('First name'), [validators.Length(max=254)])
lastname = TextField(_('Last name'), [validators.Length(max=254)])
email = TextField(_('Email address'),
[validators.Required(message=REQ_MSG)])
timezone = SelectField(_('Timezone'), choices=TIMEZONE_TUPLES)
domains = QuerySelectMultipleField(_('Domains'), get_label='name',
allow_blank=False)
active = BooleanField(_('Enabled'))
send_report = BooleanField(_('Send reports'))
spam_checks = BooleanField(_('Enable spam checks'))
low_score = DecimalField(_('Spam low score'), places=1)
high_score = DecimalField(_('Spam high score'), places=1)
class BulkDelUsers(Form):
"""Bulk account delete form"""
accountid = MultiCheckboxField('')
whatdo = RadioField('', choices=[('delete', _('delete'),),
('disable', _('disable'),),
('enable', _('enable'),),])
class AddressForm(Form):
"""Add alias address"""
address = TextField(_('Email Address'),
[validators.Required(message=REQ_MSG),
validators.Email(message=EMAIL_MSG), check_domain])
enabled = BooleanField(_('Enabled'))
class ChangePasswordForm(Form):
"""Admin change user password"""
password1 = PasswordField(_('New Password'),
[check_password, validators.Required(message=REQ_MSG),
validators.EqualTo('password2',
message=_('Passwords must match'))])
password2 = PasswordField(_('Retype Password'),
[validators.Required(message=REQ_MSG)])
class UserPasswordForm(ChangePasswordForm):
"""User password change"""
password3 = PasswordField(_('Old Password'),
[validators.Required(message=REQ_MSG)])
class ResetPwForm(Form):
"""User reset password form"""
email = TextField(_('Email Address'),
[validators.Required(message=REQ_MSG),
validators.Email(message=EMAIL_MSG),
can_reset])
|
cxxgtxy/tensorflow | refs/heads/master | tensorflow/contrib/linalg/python/kernel_tests/linear_operator_addition_test.py | 70 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib import linalg as linalg_lib
from tensorflow.contrib.linalg.python.ops import linear_operator_addition
from tensorflow.python.framework import random_seed
from tensorflow.python.ops import linalg_ops
from tensorflow.python.platform import test
linalg = linalg_lib
random_seed.set_random_seed(23)
rng = np.random.RandomState(0)
add_operators = linear_operator_addition.add_operators
# pylint: disable=unused-argument
class _BadAdder(linear_operator_addition._Adder):
"""Adder that will fail if used."""
def can_add(self, op1, op2):
raise AssertionError("BadAdder.can_add called!")
def _add(self, op1, op2, operator_name, hints):
raise AssertionError("This line should not be reached")
# pylint: enable=unused-argument
class LinearOperatorAdditionCorrectnessTest(test.TestCase):
"""Tests correctness of addition with combinations of a few Adders.
Tests here are done with the _DEFAULT_ADDITION_TIERS, which means
add_operators should reduce all operators resulting in one single operator.
This shows that we are able to correctly combine adders using the tiered
system. All Adders should be tested separately, and there is no need to test
every Adder within this class.
"""
def test_one_operator_is_returned_unchanged(self):
op_a = linalg.LinearOperatorDiag([1., 1.])
op_sum = add_operators([op_a])
self.assertEqual(1, len(op_sum))
self.assertTrue(op_sum[0] is op_a)
def test_at_least_one_operators_required(self):
with self.assertRaisesRegexp(ValueError, "must contain at least one"):
add_operators([])
def test_attempting_to_add_numbers_raises(self):
with self.assertRaisesRegexp(TypeError, "contain only LinearOperator"):
add_operators([1, 2])
def test_two_diag_operators(self):
op_a = linalg.LinearOperatorDiag(
[1., 1.], is_positive_definite=True, name="A")
op_b = linalg.LinearOperatorDiag(
[2., 2.], is_positive_definite=True, name="B")
with self.test_session():
op_sum = add_operators([op_a, op_b])
self.assertEqual(1, len(op_sum))
op = op_sum[0]
self.assertTrue(isinstance(op, linalg_lib.LinearOperatorDiag))
self.assertAllClose([[3., 0.], [0., 3.]], op.to_dense().eval())
# Adding positive definite operators produces positive def.
self.assertTrue(op.is_positive_definite)
# Real diagonal ==> self-adjoint.
self.assertTrue(op.is_self_adjoint)
# Positive definite ==> non-singular
self.assertTrue(op.is_non_singular)
# Enforce particular name for this simple case
self.assertEqual("Add/B__A/", op.name)
def test_three_diag_operators(self):
op1 = linalg.LinearOperatorDiag(
[1., 1.], is_positive_definite=True, name="op1")
op2 = linalg.LinearOperatorDiag(
[2., 2.], is_positive_definite=True, name="op2")
op3 = linalg.LinearOperatorDiag(
[3., 3.], is_positive_definite=True, name="op3")
with self.test_session():
op_sum = add_operators([op1, op2, op3])
self.assertEqual(1, len(op_sum))
op = op_sum[0]
self.assertTrue(isinstance(op, linalg_lib.LinearOperatorDiag))
self.assertAllClose([[6., 0.], [0., 6.]], op.to_dense().eval())
# Adding positive definite operators produces positive def.
self.assertTrue(op.is_positive_definite)
# Real diagonal ==> self-adjoint.
self.assertTrue(op.is_self_adjoint)
# Positive definite ==> non-singular
self.assertTrue(op.is_non_singular)
def test_diag_tril_diag(self):
op1 = linalg.LinearOperatorDiag(
[1., 1.], is_non_singular=True, name="diag_a")
op2 = linalg.LinearOperatorTriL(
[[2., 0.], [0., 2.]],
is_self_adjoint=True,
is_non_singular=True,
name="tril")
op3 = linalg.LinearOperatorDiag(
[3., 3.], is_non_singular=True, name="diag_b")
with self.test_session():
op_sum = add_operators([op1, op2, op3])
self.assertEqual(1, len(op_sum))
op = op_sum[0]
self.assertTrue(isinstance(op, linalg_lib.LinearOperatorTriL))
self.assertAllClose([[6., 0.], [0., 6.]], op.to_dense().eval())
# The diag operators will be self-adjoint (because real and diagonal).
# The TriL operator has the self-adjoint hint set.
self.assertTrue(op.is_self_adjoint)
# Even though op1/2/3 are non-singular, this does not imply op is.
# Since no custom hint was provided, we default to None (unknown).
self.assertEqual(None, op.is_non_singular)
def test_matrix_diag_tril_diag_uses_custom_name(self):
op0 = linalg.LinearOperatorFullMatrix(
[[-1., -1.], [-1., -1.]], name="matrix")
op1 = linalg.LinearOperatorDiag([1., 1.], name="diag_a")
op2 = linalg.LinearOperatorTriL([[2., 0.], [1.5, 2.]], name="tril")
op3 = linalg.LinearOperatorDiag([3., 3.], name="diag_b")
with self.test_session():
op_sum = add_operators([op0, op1, op2, op3], operator_name="my_operator")
self.assertEqual(1, len(op_sum))
op = op_sum[0]
self.assertTrue(isinstance(op, linalg_lib.LinearOperatorFullMatrix))
self.assertAllClose([[5., -1.], [0.5, 5.]], op.to_dense().eval())
self.assertEqual("my_operator", op.name)
def test_incompatible_domain_dimensions_raises(self):
op1 = linalg.LinearOperatorFullMatrix(rng.rand(2, 3))
op2 = linalg.LinearOperatorDiag(rng.rand(2, 4))
with self.assertRaisesRegexp(ValueError, "must.*same domain dimension"):
add_operators([op1, op2])
def test_incompatible_range_dimensions_raises(self):
op1 = linalg.LinearOperatorFullMatrix(rng.rand(2, 3))
op2 = linalg.LinearOperatorDiag(rng.rand(3, 3))
with self.assertRaisesRegexp(ValueError, "must.*same range dimension"):
add_operators([op1, op2])
def test_non_broadcastable_batch_shape_raises(self):
op1 = linalg.LinearOperatorFullMatrix(rng.rand(2, 3, 3))
op2 = linalg.LinearOperatorDiag(rng.rand(4, 3, 3))
with self.assertRaisesRegexp(ValueError, "Incompatible shapes"):
add_operators([op1, op2])
class LinearOperatorOrderOfAdditionTest(test.TestCase):
"""Test that the order of addition is done as specified by tiers."""
def test_tier_0_additions_done_in_tier_0(self):
diag1 = linalg.LinearOperatorDiag([1.])
diag2 = linalg.LinearOperatorDiag([1.])
diag3 = linalg.LinearOperatorDiag([1.])
addition_tiers = [
[linear_operator_addition._AddAndReturnDiag()],
[_BadAdder()],
]
# Should not raise since all were added in tier 0, and tier 1 (with the
# _BadAdder) was never reached.
op_sum = add_operators([diag1, diag2, diag3], addition_tiers=addition_tiers)
self.assertEqual(1, len(op_sum))
self.assertTrue(isinstance(op_sum[0], linalg.LinearOperatorDiag))
def test_tier_1_additions_done_by_tier_1(self):
diag1 = linalg.LinearOperatorDiag([1.])
diag2 = linalg.LinearOperatorDiag([1.])
tril = linalg.LinearOperatorTriL([[1.]])
addition_tiers = [
[linear_operator_addition._AddAndReturnDiag()],
[linear_operator_addition._AddAndReturnTriL()],
[_BadAdder()],
]
# Should not raise since all were added by tier 1, and the
# _BadAdder) was never reached.
op_sum = add_operators([diag1, diag2, tril], addition_tiers=addition_tiers)
self.assertEqual(1, len(op_sum))
self.assertTrue(isinstance(op_sum[0], linalg.LinearOperatorTriL))
def test_tier_1_additions_done_by_tier_1_with_order_flipped(self):
diag1 = linalg.LinearOperatorDiag([1.])
diag2 = linalg.LinearOperatorDiag([1.])
tril = linalg.LinearOperatorTriL([[1.]])
addition_tiers = [
[linear_operator_addition._AddAndReturnTriL()],
[linear_operator_addition._AddAndReturnDiag()],
[_BadAdder()],
]
# Tier 0 could convert to TriL, and this converted everything to TriL,
# including the Diags.
# Tier 1 was never used.
# Tier 2 was never used (therefore, _BadAdder didn't raise).
op_sum = add_operators([diag1, diag2, tril], addition_tiers=addition_tiers)
self.assertEqual(1, len(op_sum))
self.assertTrue(isinstance(op_sum[0], linalg.LinearOperatorTriL))
def test_cannot_add_everything_so_return_more_than_one_operator(self):
diag1 = linalg.LinearOperatorDiag([1.])
diag2 = linalg.LinearOperatorDiag([2.])
tril5 = linalg.LinearOperatorTriL([[5.]])
addition_tiers = [
[linear_operator_addition._AddAndReturnDiag()],
]
# Tier 0 (the only tier) can only convert to Diag, so it combines the two
# diags, but the TriL is unchanged.
# Result should contain two operators, one Diag, one TriL.
op_sum = add_operators([diag1, diag2, tril5], addition_tiers=addition_tiers)
self.assertEqual(2, len(op_sum))
found_diag = False
found_tril = False
with self.test_session():
for op in op_sum:
if isinstance(op, linalg.LinearOperatorDiag):
found_diag = True
self.assertAllClose([[3.]], op.to_dense().eval())
if isinstance(op, linalg.LinearOperatorTriL):
found_tril = True
self.assertAllClose([[5.]], op.to_dense().eval())
self.assertTrue(found_diag and found_tril)
def test_intermediate_tier_is_not_skipped(self):
diag1 = linalg.LinearOperatorDiag([1.])
diag2 = linalg.LinearOperatorDiag([1.])
tril = linalg.LinearOperatorTriL([[1.]])
addition_tiers = [
[linear_operator_addition._AddAndReturnDiag()],
[_BadAdder()],
[linear_operator_addition._AddAndReturnTriL()],
]
# tril cannot be added in tier 0, and the intermediate tier 1 with the
# BadAdder will catch it and raise.
with self.assertRaisesRegexp(AssertionError, "BadAdder.can_add called"):
add_operators([diag1, diag2, tril], addition_tiers=addition_tiers)
class AddAndReturnScaledIdentityTest(test.TestCase):
def setUp(self):
self._adder = linear_operator_addition._AddAndReturnScaledIdentity()
def test_identity_plus_identity(self):
id1 = linalg.LinearOperatorIdentity(num_rows=2)
id2 = linalg.LinearOperatorIdentity(num_rows=2, batch_shape=[3])
hints = linear_operator_addition._Hints(
is_positive_definite=True, is_non_singular=True)
self.assertTrue(self._adder.can_add(id1, id2))
operator = self._adder.add(id1, id2, "my_operator", hints)
self.assertTrue(isinstance(operator, linalg.LinearOperatorScaledIdentity))
with self.test_session():
self.assertAllClose(2 *
linalg_ops.eye(num_rows=2, batch_shape=[3]).eval(),
operator.to_dense().eval())
self.assertTrue(operator.is_positive_definite)
self.assertTrue(operator.is_non_singular)
self.assertEqual("my_operator", operator.name)
def test_identity_plus_scaled_identity(self):
id1 = linalg.LinearOperatorIdentity(num_rows=2, batch_shape=[3])
id2 = linalg.LinearOperatorScaledIdentity(num_rows=2, multiplier=2.2)
hints = linear_operator_addition._Hints(
is_positive_definite=True, is_non_singular=True)
self.assertTrue(self._adder.can_add(id1, id2))
operator = self._adder.add(id1, id2, "my_operator", hints)
self.assertTrue(isinstance(operator, linalg.LinearOperatorScaledIdentity))
with self.test_session():
self.assertAllClose(3.2 *
linalg_ops.eye(num_rows=2, batch_shape=[3]).eval(),
operator.to_dense().eval())
self.assertTrue(operator.is_positive_definite)
self.assertTrue(operator.is_non_singular)
self.assertEqual("my_operator", operator.name)
def test_scaled_identity_plus_scaled_identity(self):
id1 = linalg.LinearOperatorScaledIdentity(
num_rows=2, multiplier=[2.2, 2.2, 2.2])
id2 = linalg.LinearOperatorScaledIdentity(num_rows=2, multiplier=-1.0)
hints = linear_operator_addition._Hints(
is_positive_definite=True, is_non_singular=True)
self.assertTrue(self._adder.can_add(id1, id2))
operator = self._adder.add(id1, id2, "my_operator", hints)
self.assertTrue(isinstance(operator, linalg.LinearOperatorScaledIdentity))
with self.test_session():
self.assertAllClose(1.2 *
linalg_ops.eye(num_rows=2, batch_shape=[3]).eval(),
operator.to_dense().eval())
self.assertTrue(operator.is_positive_definite)
self.assertTrue(operator.is_non_singular)
self.assertEqual("my_operator", operator.name)
class AddAndReturnDiagTest(test.TestCase):
def setUp(self):
self._adder = linear_operator_addition._AddAndReturnDiag()
def test_identity_plus_identity_returns_diag(self):
id1 = linalg.LinearOperatorIdentity(num_rows=2)
id2 = linalg.LinearOperatorIdentity(num_rows=2, batch_shape=[3])
hints = linear_operator_addition._Hints(
is_positive_definite=True, is_non_singular=True)
self.assertTrue(self._adder.can_add(id1, id2))
operator = self._adder.add(id1, id2, "my_operator", hints)
self.assertTrue(isinstance(operator, linalg.LinearOperatorDiag))
with self.test_session():
self.assertAllClose(2 *
linalg_ops.eye(num_rows=2, batch_shape=[3]).eval(),
operator.to_dense().eval())
self.assertTrue(operator.is_positive_definite)
self.assertTrue(operator.is_non_singular)
self.assertEqual("my_operator", operator.name)
def test_diag_plus_diag(self):
diag1 = rng.rand(2, 3, 4)
diag2 = rng.rand(4)
op1 = linalg.LinearOperatorDiag(diag1)
op2 = linalg.LinearOperatorDiag(diag2)
hints = linear_operator_addition._Hints(
is_positive_definite=True, is_non_singular=True)
self.assertTrue(self._adder.can_add(op1, op2))
operator = self._adder.add(op1, op2, "my_operator", hints)
self.assertTrue(isinstance(operator, linalg.LinearOperatorDiag))
with self.test_session():
self.assertAllClose(
linalg.LinearOperatorDiag(diag1 + diag2).to_dense().eval(),
operator.to_dense().eval())
self.assertTrue(operator.is_positive_definite)
self.assertTrue(operator.is_non_singular)
self.assertEqual("my_operator", operator.name)
class AddAndReturnTriLTest(test.TestCase):
def setUp(self):
self._adder = linear_operator_addition._AddAndReturnTriL()
def test_diag_plus_tril(self):
diag = linalg.LinearOperatorDiag([1., 2.])
tril = linalg.LinearOperatorTriL([[10., 0.], [30., 0.]])
hints = linear_operator_addition._Hints(
is_positive_definite=True, is_non_singular=True)
self.assertTrue(self._adder.can_add(diag, diag))
self.assertTrue(self._adder.can_add(diag, tril))
operator = self._adder.add(diag, tril, "my_operator", hints)
self.assertTrue(isinstance(operator, linalg.LinearOperatorTriL))
with self.test_session():
self.assertAllClose([[11., 0.], [30., 2.]], operator.to_dense().eval())
self.assertTrue(operator.is_positive_definite)
self.assertTrue(operator.is_non_singular)
self.assertEqual("my_operator", operator.name)
class AddAndReturnMatrixTest(test.TestCase):
def setUp(self):
self._adder = linear_operator_addition._AddAndReturnMatrix()
def test_diag_plus_diag(self):
diag1 = linalg.LinearOperatorDiag([1., 2.])
diag2 = linalg.LinearOperatorDiag([-1., 3.])
hints = linear_operator_addition._Hints(
is_positive_definite=False, is_non_singular=False)
self.assertTrue(self._adder.can_add(diag1, diag2))
operator = self._adder.add(diag1, diag2, "my_operator", hints)
self.assertTrue(isinstance(operator, linalg.LinearOperatorFullMatrix))
with self.test_session():
self.assertAllClose([[0., 0.], [0., 5.]], operator.to_dense().eval())
self.assertFalse(operator.is_positive_definite)
self.assertFalse(operator.is_non_singular)
self.assertEqual("my_operator", operator.name)
if __name__ == "__main__":
test.main()
|
srajag/contrail-controller | refs/heads/master | src/config/utils/provision_forwarding_mode.py | 7 | #!/usr/bin/python
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
import sys
import argparse
import ConfigParser
from vnc_api.vnc_api import *
class ForwardingModeSetup(object):
def __init__(self, args_str=None):
self._args = None
if not args_str:
args_str = ' '.join(sys.argv[1:])
self._parse_args(args_str)
self._vnc_lib = VncApi(
self._args.admin_user, self._args.admin_password,
self._args.admin_tenant_name,
self._args.api_server_ip,
self._args.api_server_port, '/')
#import pdb;pdb.set_trace()
vxlan_id = self._args.vxlan_id
vn_name = self._args.vn_name
forwarding_mode = self._args.forwarding_mode
project_fq_name_str = self._args.project_fq_name
project_fq_name = project_fq_name_str.split(':')
#Figure out VN
vni_list = self._vnc_lib.virtual_networks_list(
parent_fq_name = project_fq_name)['virtual-networks']
found = False
for vni_record in vni_list:
if (vni_record['fq_name'][0] == project_fq_name[0] and
vni_record['fq_name'][1] == project_fq_name[1] and
vni_record['fq_name'][2] == vn_name):
vni_obj = self._vnc_lib.virtual_network_read(
id = vni_record['uuid'])
vni_obj_properties = vni_obj.get_virtual_network_properties()
if (vxlan_id is not None):
vni_obj_properties.set_vxlan_network_identifier(int(vxlan_id))
if (forwarding_mode is not None):
vni_obj_properties.set_forwarding_mode(forwarding_mode)
vni_obj.set_virtual_network_properties(vni_obj_properties)
self._vnc_lib.virtual_network_update(vni_obj)
found = True
if not found:
print "No Virtual Network %s" %(vn_name)
sys.exit(1)
# end __init__
def _parse_args(self, args_str):
'''
Eg. python provision_forwarding_mode.py
--project_fq_name 'default-domain:admin'
--vn_name vn1
--vxlan_id 100
--forwarding_mode l2
'''
# Source any specified config/ini file
# Turn off help, so we print all options in response to -h
conf_parser = argparse.ArgumentParser(add_help=False)
conf_parser.add_argument("-c", "--conf_file",
help="Specify config file", metavar="FILE")
args, remaining_argv = conf_parser.parse_known_args(args_str.split())
defaults = {
'api_server_ip': '127.0.0.1',
'api_server_port': '8082',
'oper': 'add',
'control_names': [],
'route_table_name': 'CustomRouteTable',
'project_fq_name' : 'default-domain:admin',
}
ksopts = {
'admin_user': 'user1',
'admin_password': 'password1',
'admin_tenant_name': 'default-domain'
}
# Override with CLI options
# Don't surpress add_help here so it will handle -h
parser = argparse.ArgumentParser(
# Inherit options from config_parser
parents=[conf_parser],
# print script description with -h/--help
description=__doc__,
# Don't mess with format of description
formatter_class=argparse.RawDescriptionHelpFormatter,
)
defaults.update(ksopts)
parser.set_defaults(**defaults)
parser.add_argument(
"--vn_name", help="VN Name", required=True)
parser.add_argument(
"--project_fq_name", help="Fully qualified name of the Project", required=True)
parser.add_argument(
"--vxlan_id", help="VxLan ID", required=True)
parser.add_argument("--api_server_port", help="Port of api server", required=True)
parser.add_argument(
"--forwarding_mode", help="l2_l3 or l2 only", required=True)
parser.add_argument(
"--admin_tenant_name", help="Tenant to create the forwarding mode")
parser.add_argument(
"--admin_user", help="Name of keystone admin user")
parser.add_argument(
"--admin_password", help="Password of keystone admin user")
self._args = parser.parse_args(remaining_argv)
# end _parse_args
# end class ForwardingModeSetup
def main(args_str=None):
ForwardingModeSetup(args_str)
# end main
if __name__ == "__main__":
main()
|
caorong/ChinaDNS | refs/heads/master | tests/test.py | 165 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import signal
import time
import argparse
from subprocess import Popen
parser = argparse.ArgumentParser(description='test ChinaDNS')
parser.add_argument('-a', '--arguments', type=str, default=[])
parser.add_argument('-t', '--test-command', type=str, default=None)
config = parser.parse_args()
arguments = config.arguments
chinadns = ['src/chinadns', '-p', '15353', '-v'] + arguments.split()
print chinadns
p1 = Popen(chinadns, shell=False, bufsize=0, close_fds=True)
try:
with open(config.test_command) as f:
dig_cmd = f.read()
time.sleep(1)
p2 = Popen(dig_cmd.split() + ['-p', '15353'], shell=False,
bufsize=0, close_fds=True)
if p2 is not None:
r = p2.wait()
if r == 0:
print 'test passed'
sys.exit(r)
finally:
for p in [p1]:
try:
os.kill(p.pid, signal.SIGTERM)
os.waitpid(p.pid, 0)
except OSError:
pass
|
larsbergstrom/skia | refs/heads/master | tools/retrieve_from_googlesource.py | 160 | #!/usr/bin/python
# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Retrieve the given file from googlesource.com."""
from contextlib import closing
import base64
import sys
import urllib2
def get(repo_url, filepath):
"""Retrieve the contents of the given file from the given googlesource repo.
Args:
repo_url: string; URL of the repository from which to retrieve the file.
filepath: string; path of the file within the repository.
Return:
string; the contents of the given file.
"""
base64_url = '/'.join((repo_url, '+', 'master', filepath)) + '?format=TEXT'
with closing(urllib2.urlopen(base64_url)) as f:
return base64.b64decode(f.read())
if __name__ == '__main__':
if len(sys.argv) != 3:
print >> sys.stderr, 'Usage: %s <repo_url> <filepath>' % sys.argv[0]
sys.exit(1)
sys.stdout.write(get(sys.argv[1], sys.argv[2]))
|
AndrewGrossman/django | refs/heads/master | django/contrib/gis/db/models/query.py | 224 | import warnings
from django.contrib.gis.db.models import aggregates
from django.contrib.gis.db.models.fields import (
GeometryField, LineStringField, PointField, get_srid_info,
)
from django.contrib.gis.db.models.lookups import GISLookup
from django.contrib.gis.db.models.sql import (
AreaField, DistanceField, GeomField, GMLField,
)
from django.contrib.gis.geometry.backend import Geometry
from django.contrib.gis.measure import Area, Distance
from django.db import connections
from django.db.models.expressions import RawSQL
from django.db.models.fields import Field
from django.db.models.query import QuerySet
from django.utils import six
from django.utils.deprecation import (
RemovedInDjango20Warning, RemovedInDjango110Warning,
)
class GeoQuerySet(QuerySet):
"The Geographic QuerySet."
# ### GeoQuerySet Methods ###
def area(self, tolerance=0.05, **kwargs):
"""
Returns the area of the geographic field in an `area` attribute on
each element of this GeoQuerySet.
"""
# Performing setup here rather than in `_spatial_attribute` so that
# we can get the units for `AreaField`.
procedure_args, geo_field = self._spatial_setup(
'area', field_name=kwargs.get('field_name'))
s = {'procedure_args': procedure_args,
'geo_field': geo_field,
'setup': False,
}
connection = connections[self.db]
backend = connection.ops
if backend.oracle:
s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s'
s['procedure_args']['tolerance'] = tolerance
s['select_field'] = AreaField('sq_m') # Oracle returns area in units of meters.
elif backend.postgis or backend.spatialite:
if backend.geography:
# Geography fields support area calculation, returns square meters.
s['select_field'] = AreaField('sq_m')
elif not geo_field.geodetic(connection):
# Getting the area units of the geographic field.
s['select_field'] = AreaField(Area.unit_attname(geo_field.units_name(connection)))
else:
# TODO: Do we want to support raw number areas for geodetic fields?
raise Exception('Area on geodetic coordinate systems not supported.')
return self._spatial_attribute('area', s, **kwargs)
def centroid(self, **kwargs):
"""
Returns the centroid of the geographic field in a `centroid`
attribute on each element of this GeoQuerySet.
"""
return self._geom_attribute('centroid', **kwargs)
def collect(self, **kwargs):
"""
Performs an aggregate collect operation on the given geometry field.
This is analogous to a union operation, but much faster because
boundaries are not dissolved.
"""
warnings.warn(
"The collect GeoQuerySet method is deprecated. Use the Collect() "
"aggregate in an aggregate() or annotate() method.",
RemovedInDjango110Warning, stacklevel=2
)
return self._spatial_aggregate(aggregates.Collect, **kwargs)
def difference(self, geom, **kwargs):
"""
Returns the spatial difference of the geographic field in a `difference`
attribute on each element of this GeoQuerySet.
"""
return self._geomset_attribute('difference', geom, **kwargs)
def distance(self, geom, **kwargs):
"""
Returns the distance from the given geographic field name to the
given geometry in a `distance` attribute on each element of the
GeoQuerySet.
Keyword Arguments:
`spheroid` => If the geometry field is geodetic and PostGIS is
the spatial database, then the more accurate
spheroid calculation will be used instead of the
quicker sphere calculation.
`tolerance` => Used only for Oracle. The tolerance is
in meters -- a default of 5 centimeters (0.05)
is used.
"""
return self._distance_attribute('distance', geom, **kwargs)
def envelope(self, **kwargs):
"""
Returns a Geometry representing the bounding box of the
Geometry field in an `envelope` attribute on each element of
the GeoQuerySet.
"""
return self._geom_attribute('envelope', **kwargs)
def extent(self, **kwargs):
"""
Returns the extent (aggregate) of the features in the GeoQuerySet. The
extent will be returned as a 4-tuple, consisting of (xmin, ymin, xmax, ymax).
"""
warnings.warn(
"The extent GeoQuerySet method is deprecated. Use the Extent() "
"aggregate in an aggregate() or annotate() method.",
RemovedInDjango110Warning, stacklevel=2
)
return self._spatial_aggregate(aggregates.Extent, **kwargs)
def extent3d(self, **kwargs):
"""
Returns the aggregate extent, in 3D, of the features in the
GeoQuerySet. It is returned as a 6-tuple, comprising:
(xmin, ymin, zmin, xmax, ymax, zmax).
"""
warnings.warn(
"The extent3d GeoQuerySet method is deprecated. Use the Extent3D() "
"aggregate in an aggregate() or annotate() method.",
RemovedInDjango110Warning, stacklevel=2
)
return self._spatial_aggregate(aggregates.Extent3D, **kwargs)
def force_rhr(self, **kwargs):
"""
Returns a modified version of the Polygon/MultiPolygon in which
all of the vertices follow the Right-Hand-Rule. By default,
this is attached as the `force_rhr` attribute on each element
of the GeoQuerySet.
"""
return self._geom_attribute('force_rhr', **kwargs)
def geojson(self, precision=8, crs=False, bbox=False, **kwargs):
"""
Returns a GeoJSON representation of the geometry field in a `geojson`
attribute on each element of the GeoQuerySet.
The `crs` and `bbox` keywords may be set to True if the user wants
the coordinate reference system and the bounding box to be included
in the GeoJSON representation of the geometry.
"""
backend = connections[self.db].ops
if not backend.geojson:
raise NotImplementedError('Only PostGIS 1.3.4+ and SpatiaLite 3.0+ '
'support GeoJSON serialization.')
if not isinstance(precision, six.integer_types):
raise TypeError('Precision keyword must be set with an integer.')
options = 0
if crs and bbox:
options = 3
elif bbox:
options = 1
elif crs:
options = 2
s = {'desc': 'GeoJSON',
'procedure_args': {'precision': precision, 'options': options},
'procedure_fmt': '%(geo_col)s,%(precision)s,%(options)s',
}
return self._spatial_attribute('geojson', s, **kwargs)
def geohash(self, precision=20, **kwargs):
"""
Returns a GeoHash representation of the given field in a `geohash`
attribute on each element of the GeoQuerySet.
The `precision` keyword may be used to custom the number of
_characters_ used in the output GeoHash, the default is 20.
"""
s = {'desc': 'GeoHash',
'procedure_args': {'precision': precision},
'procedure_fmt': '%(geo_col)s,%(precision)s',
}
return self._spatial_attribute('geohash', s, **kwargs)
def gml(self, precision=8, version=2, **kwargs):
"""
Returns GML representation of the given field in a `gml` attribute
on each element of the GeoQuerySet.
"""
backend = connections[self.db].ops
s = {'desc': 'GML', 'procedure_args': {'precision': precision}}
if backend.postgis:
s['procedure_fmt'] = '%(version)s,%(geo_col)s,%(precision)s'
s['procedure_args'] = {'precision': precision, 'version': version}
if backend.oracle:
s['select_field'] = GMLField()
return self._spatial_attribute('gml', s, **kwargs)
def intersection(self, geom, **kwargs):
"""
Returns the spatial intersection of the Geometry field in
an `intersection` attribute on each element of this
GeoQuerySet.
"""
return self._geomset_attribute('intersection', geom, **kwargs)
def kml(self, **kwargs):
"""
Returns KML representation of the geometry field in a `kml`
attribute on each element of this GeoQuerySet.
"""
s = {'desc': 'KML',
'procedure_fmt': '%(geo_col)s,%(precision)s',
'procedure_args': {'precision': kwargs.pop('precision', 8)},
}
return self._spatial_attribute('kml', s, **kwargs)
def length(self, **kwargs):
"""
Returns the length of the geometry field as a `Distance` object
stored in a `length` attribute on each element of this GeoQuerySet.
"""
return self._distance_attribute('length', None, **kwargs)
def make_line(self, **kwargs):
"""
Creates a linestring from all of the PointField geometries in the
this GeoQuerySet and returns it. This is a spatial aggregate
method, and thus returns a geometry rather than a GeoQuerySet.
"""
warnings.warn(
"The make_line GeoQuerySet method is deprecated. Use the MakeLine() "
"aggregate in an aggregate() or annotate() method.",
RemovedInDjango110Warning, stacklevel=2
)
return self._spatial_aggregate(aggregates.MakeLine, geo_field_type=PointField, **kwargs)
def mem_size(self, **kwargs):
"""
Returns the memory size (number of bytes) that the geometry field takes
in a `mem_size` attribute on each element of this GeoQuerySet.
"""
return self._spatial_attribute('mem_size', {}, **kwargs)
def num_geom(self, **kwargs):
"""
Returns the number of geometries if the field is a
GeometryCollection or Multi* Field in a `num_geom`
attribute on each element of this GeoQuerySet; otherwise
the sets with None.
"""
return self._spatial_attribute('num_geom', {}, **kwargs)
def num_points(self, **kwargs):
"""
Returns the number of points in the first linestring in the
Geometry field in a `num_points` attribute on each element of
this GeoQuerySet; otherwise sets with None.
"""
return self._spatial_attribute('num_points', {}, **kwargs)
def perimeter(self, **kwargs):
"""
Returns the perimeter of the geometry field as a `Distance` object
stored in a `perimeter` attribute on each element of this GeoQuerySet.
"""
return self._distance_attribute('perimeter', None, **kwargs)
def point_on_surface(self, **kwargs):
"""
Returns a Point geometry guaranteed to lie on the surface of the
Geometry field in a `point_on_surface` attribute on each element
of this GeoQuerySet; otherwise sets with None.
"""
return self._geom_attribute('point_on_surface', **kwargs)
def reverse_geom(self, **kwargs):
"""
Reverses the coordinate order of the geometry, and attaches as a
`reverse` attribute on each element of this GeoQuerySet.
"""
s = {'select_field': GeomField()}
kwargs.setdefault('model_att', 'reverse_geom')
if connections[self.db].ops.oracle:
s['geo_field_type'] = LineStringField
return self._spatial_attribute('reverse', s, **kwargs)
def scale(self, x, y, z=0.0, **kwargs):
"""
Scales the geometry to a new size by multiplying the ordinates
with the given x,y,z scale factors.
"""
if connections[self.db].ops.spatialite:
if z != 0.0:
raise NotImplementedError('SpatiaLite does not support 3D scaling.')
s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s',
'procedure_args': {'x': x, 'y': y},
'select_field': GeomField(),
}
else:
s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s,%(z)s',
'procedure_args': {'x': x, 'y': y, 'z': z},
'select_field': GeomField(),
}
return self._spatial_attribute('scale', s, **kwargs)
def snap_to_grid(self, *args, **kwargs):
"""
Snap all points of the input geometry to the grid. How the
geometry is snapped to the grid depends on how many arguments
were given:
- 1 argument : A single size to snap both the X and Y grids to.
- 2 arguments: X and Y sizes to snap the grid to.
- 4 arguments: X, Y sizes and the X, Y origins.
"""
if False in [isinstance(arg, (float,) + six.integer_types) for arg in args]:
raise TypeError('Size argument(s) for the grid must be a float or integer values.')
nargs = len(args)
if nargs == 1:
size = args[0]
procedure_fmt = '%(geo_col)s,%(size)s'
procedure_args = {'size': size}
elif nargs == 2:
xsize, ysize = args
procedure_fmt = '%(geo_col)s,%(xsize)s,%(ysize)s'
procedure_args = {'xsize': xsize, 'ysize': ysize}
elif nargs == 4:
xsize, ysize, xorigin, yorigin = args
procedure_fmt = '%(geo_col)s,%(xorigin)s,%(yorigin)s,%(xsize)s,%(ysize)s'
procedure_args = {'xsize': xsize, 'ysize': ysize,
'xorigin': xorigin, 'yorigin': yorigin}
else:
raise ValueError('Must provide 1, 2, or 4 arguments to `snap_to_grid`.')
s = {'procedure_fmt': procedure_fmt,
'procedure_args': procedure_args,
'select_field': GeomField(),
}
return self._spatial_attribute('snap_to_grid', s, **kwargs)
def svg(self, relative=False, precision=8, **kwargs):
"""
Returns SVG representation of the geographic field in a `svg`
attribute on each element of this GeoQuerySet.
Keyword Arguments:
`relative` => If set to True, this will evaluate the path in
terms of relative moves (rather than absolute).
`precision` => May be used to set the maximum number of decimal
digits used in output (defaults to 8).
"""
relative = int(bool(relative))
if not isinstance(precision, six.integer_types):
raise TypeError('SVG precision keyword argument must be an integer.')
s = {
'desc': 'SVG',
'procedure_fmt': '%(geo_col)s,%(rel)s,%(precision)s',
'procedure_args': {
'rel': relative,
'precision': precision,
}
}
return self._spatial_attribute('svg', s, **kwargs)
def sym_difference(self, geom, **kwargs):
"""
Returns the symmetric difference of the geographic field in a
`sym_difference` attribute on each element of this GeoQuerySet.
"""
return self._geomset_attribute('sym_difference', geom, **kwargs)
def translate(self, x, y, z=0.0, **kwargs):
"""
Translates the geometry to a new location using the given numeric
parameters as offsets.
"""
if connections[self.db].ops.spatialite:
if z != 0.0:
raise NotImplementedError('SpatiaLite does not support 3D translation.')
s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s',
'procedure_args': {'x': x, 'y': y},
'select_field': GeomField(),
}
else:
s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s,%(z)s',
'procedure_args': {'x': x, 'y': y, 'z': z},
'select_field': GeomField(),
}
return self._spatial_attribute('translate', s, **kwargs)
def transform(self, srid=4326, **kwargs):
"""
Transforms the given geometry field to the given SRID. If no SRID is
provided, the transformation will default to using 4326 (WGS84).
"""
if not isinstance(srid, six.integer_types):
raise TypeError('An integer SRID must be provided.')
field_name = kwargs.get('field_name')
self._spatial_setup('transform', field_name=field_name)
self.query.add_context('transformed_srid', srid)
return self._clone()
def union(self, geom, **kwargs):
"""
Returns the union of the geographic field with the given
Geometry in a `union` attribute on each element of this GeoQuerySet.
"""
return self._geomset_attribute('union', geom, **kwargs)
def unionagg(self, **kwargs):
"""
Performs an aggregate union on the given geometry field. Returns
None if the GeoQuerySet is empty. The `tolerance` keyword is for
Oracle backends only.
"""
warnings.warn(
"The unionagg GeoQuerySet method is deprecated. Use the Union() "
"aggregate in an aggregate() or annotate() method.",
RemovedInDjango110Warning, stacklevel=2
)
return self._spatial_aggregate(aggregates.Union, **kwargs)
# ### Private API -- Abstracted DRY routines. ###
def _spatial_setup(self, att, desc=None, field_name=None, geo_field_type=None):
"""
Performs set up for executing the spatial function.
"""
# Does the spatial backend support this?
connection = connections[self.db]
func = getattr(connection.ops, att, False)
if desc is None:
desc = att
if not func:
raise NotImplementedError('%s stored procedure not available on '
'the %s backend.' %
(desc, connection.ops.name))
# Initializing the procedure arguments.
procedure_args = {'function': func}
# Is there a geographic field in the model to perform this
# operation on?
geo_field = self._geo_field(field_name)
if not geo_field:
raise TypeError('%s output only available on GeometryFields.' % func)
# If the `geo_field_type` keyword was used, then enforce that
# type limitation.
if geo_field_type is not None and not isinstance(geo_field, geo_field_type):
raise TypeError('"%s" stored procedures may only be called on %ss.' % (func, geo_field_type.__name__))
# Setting the procedure args.
procedure_args['geo_col'] = self._geocol_select(geo_field, field_name)
return procedure_args, geo_field
def _spatial_aggregate(self, aggregate, field_name=None,
geo_field_type=None, tolerance=0.05):
"""
DRY routine for calling aggregate spatial stored procedures and
returning their result to the caller of the function.
"""
# Getting the field the geographic aggregate will be called on.
geo_field = self._geo_field(field_name)
if not geo_field:
raise TypeError('%s aggregate only available on GeometryFields.' % aggregate.name)
# Checking if there are any geo field type limitations on this
# aggregate (e.g. ST_Makeline only operates on PointFields).
if geo_field_type is not None and not isinstance(geo_field, geo_field_type):
raise TypeError('%s aggregate may only be called on %ss.' % (aggregate.name, geo_field_type.__name__))
# Getting the string expression of the field name, as this is the
# argument taken by `Aggregate` objects.
agg_col = field_name or geo_field.name
# Adding any keyword parameters for the Aggregate object. Oracle backends
# in particular need an additional `tolerance` parameter.
agg_kwargs = {}
if connections[self.db].ops.oracle:
agg_kwargs['tolerance'] = tolerance
# Calling the QuerySet.aggregate, and returning only the value of the aggregate.
return self.aggregate(geoagg=aggregate(agg_col, **agg_kwargs))['geoagg']
def _spatial_attribute(self, att, settings, field_name=None, model_att=None):
"""
DRY routine for calling a spatial stored procedure on a geometry column
and attaching its output as an attribute of the model.
Arguments:
att:
The name of the spatial attribute that holds the spatial
SQL function to call.
settings:
Dictonary of internal settings to customize for the spatial procedure.
Public Keyword Arguments:
field_name:
The name of the geographic field to call the spatial
function on. May also be a lookup to a geometry field
as part of a foreign key relation.
model_att:
The name of the model attribute to attach the output of
the spatial function to.
"""
warnings.warn(
"The %s GeoQuerySet method is deprecated. See GeoDjango Functions "
"documentation to find the expression-based replacement." % att,
RemovedInDjango20Warning, stacklevel=2
)
# Default settings.
settings.setdefault('desc', None)
settings.setdefault('geom_args', ())
settings.setdefault('geom_field', None)
settings.setdefault('procedure_args', {})
settings.setdefault('procedure_fmt', '%(geo_col)s')
settings.setdefault('select_params', [])
connection = connections[self.db]
# Performing setup for the spatial column, unless told not to.
if settings.get('setup', True):
default_args, geo_field = self._spatial_setup(
att, desc=settings['desc'], field_name=field_name,
geo_field_type=settings.get('geo_field_type'))
for k, v in six.iteritems(default_args):
settings['procedure_args'].setdefault(k, v)
else:
geo_field = settings['geo_field']
# The attribute to attach to the model.
if not isinstance(model_att, six.string_types):
model_att = att
# Special handling for any argument that is a geometry.
for name in settings['geom_args']:
# Using the field's get_placeholder() routine to get any needed
# transformation SQL.
geom = geo_field.get_prep_value(settings['procedure_args'][name])
params = geo_field.get_db_prep_lookup('contains', geom, connection=connection)
geom_placeholder = geo_field.get_placeholder(geom, None, connection)
# Replacing the procedure format with that of any needed
# transformation SQL.
old_fmt = '%%(%s)s' % name
new_fmt = geom_placeholder % '%%s'
settings['procedure_fmt'] = settings['procedure_fmt'].replace(old_fmt, new_fmt)
settings['select_params'].extend(params)
# Getting the format for the stored procedure.
fmt = '%%(function)s(%s)' % settings['procedure_fmt']
# If the result of this function needs to be converted.
if settings.get('select_field'):
select_field = settings['select_field']
if connection.ops.oracle:
select_field.empty_strings_allowed = False
else:
select_field = Field()
# Finally, setting the extra selection attribute with
# the format string expanded with the stored procedure
# arguments.
self.query.add_annotation(
RawSQL(fmt % settings['procedure_args'], settings['select_params'], select_field),
model_att)
return self
def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs):
"""
DRY routine for GeoQuerySet distance attribute routines.
"""
# Setting up the distance procedure arguments.
procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name'))
# If geodetic defaulting distance attribute to meters (Oracle and
# PostGIS spherical distances return meters). Otherwise, use the
# units of the geometry field.
connection = connections[self.db]
geodetic = geo_field.geodetic(connection)
geography = geo_field.geography
if geodetic:
dist_att = 'm'
else:
dist_att = Distance.unit_attname(geo_field.units_name(connection))
# Shortcut booleans for what distance function we're using and
# whether the geometry field is 3D.
distance = func == 'distance'
length = func == 'length'
perimeter = func == 'perimeter'
if not (distance or length or perimeter):
raise ValueError('Unknown distance function: %s' % func)
geom_3d = geo_field.dim == 3
# The field's get_db_prep_lookup() is used to get any
# extra distance parameters. Here we set up the
# parameters that will be passed in to field's function.
lookup_params = [geom or 'POINT (0 0)', 0]
# Getting the spatial backend operations.
backend = connection.ops
# If the spheroid calculation is desired, either by the `spheroid`
# keyword or when calculating the length of geodetic field, make
# sure the 'spheroid' distance setting string is passed in so we
# get the correct spatial stored procedure.
if spheroid or (backend.postgis and geodetic and
(not geography) and length):
lookup_params.append('spheroid')
lookup_params = geo_field.get_prep_value(lookup_params)
params = geo_field.get_db_prep_lookup('distance_lte', lookup_params, connection=connection)
# The `geom_args` flag is set to true if a geometry parameter was
# passed in.
geom_args = bool(geom)
if backend.oracle:
if distance:
procedure_fmt = '%(geo_col)s,%(geom)s,%(tolerance)s'
elif length or perimeter:
procedure_fmt = '%(geo_col)s,%(tolerance)s'
procedure_args['tolerance'] = tolerance
else:
# Getting whether this field is in units of degrees since the field may have
# been transformed via the `transform` GeoQuerySet method.
srid = self.query.get_context('transformed_srid')
if srid:
u, unit_name, s = get_srid_info(srid, connection)
geodetic = unit_name.lower() in geo_field.geodetic_units
if geodetic and not connection.features.supports_distance_geodetic:
raise ValueError(
'This database does not support linear distance '
'calculations on geodetic coordinate systems.'
)
if distance:
if srid:
# Setting the `geom_args` flag to false because we want to handle
# transformation SQL here, rather than the way done by default
# (which will transform to the original SRID of the field rather
# than to what was transformed to).
geom_args = False
procedure_fmt = '%s(%%(geo_col)s, %s)' % (backend.transform, srid)
if geom.srid is None or geom.srid == srid:
# If the geom parameter srid is None, it is assumed the coordinates
# are in the transformed units. A placeholder is used for the
# geometry parameter. `GeomFromText` constructor is also needed
# to wrap geom placeholder for SpatiaLite.
if backend.spatialite:
procedure_fmt += ', %s(%%%%s, %s)' % (backend.from_text, srid)
else:
procedure_fmt += ', %%s'
else:
# We need to transform the geom to the srid specified in `transform()`,
# so wrapping the geometry placeholder in transformation SQL.
# SpatiaLite also needs geometry placeholder wrapped in `GeomFromText`
# constructor.
if backend.spatialite:
procedure_fmt += (', %s(%s(%%%%s, %s), %s)' % (
backend.transform, backend.from_text,
geom.srid, srid))
else:
procedure_fmt += ', %s(%%%%s, %s)' % (backend.transform, srid)
else:
# `transform()` was not used on this GeoQuerySet.
procedure_fmt = '%(geo_col)s,%(geom)s'
if not geography and geodetic:
# Spherical distance calculation is needed (because the geographic
# field is geodetic). However, the PostGIS ST_distance_sphere/spheroid()
# procedures may only do queries from point columns to point geometries
# some error checking is required.
if not backend.geography:
if not isinstance(geo_field, PointField):
raise ValueError('Spherical distance calculation only supported on PointFields.')
if not str(Geometry(six.memoryview(params[0].ewkb)).geom_type) == 'Point':
raise ValueError(
'Spherical distance calculation only supported with '
'Point Geometry parameters'
)
# The `function` procedure argument needs to be set differently for
# geodetic distance calculations.
if spheroid:
# Call to distance_spheroid() requires spheroid param as well.
procedure_fmt += ",'%(spheroid)s'"
procedure_args.update({'function': backend.distance_spheroid, 'spheroid': params[1]})
else:
procedure_args.update({'function': backend.distance_sphere})
elif length or perimeter:
procedure_fmt = '%(geo_col)s'
if not geography and geodetic and length:
# There's no `length_sphere`, and `length_spheroid` also
# works on 3D geometries.
procedure_fmt += ",'%(spheroid)s'"
procedure_args.update({'function': backend.length_spheroid, 'spheroid': params[1]})
elif geom_3d and connection.features.supports_3d_functions:
# Use 3D variants of perimeter and length routines on supported backends.
if perimeter:
procedure_args.update({'function': backend.perimeter3d})
elif length:
procedure_args.update({'function': backend.length3d})
# Setting up the settings for `_spatial_attribute`.
s = {'select_field': DistanceField(dist_att),
'setup': False,
'geo_field': geo_field,
'procedure_args': procedure_args,
'procedure_fmt': procedure_fmt,
}
if geom_args:
s['geom_args'] = ('geom',)
s['procedure_args']['geom'] = geom
elif geom:
# The geometry is passed in as a parameter because we handled
# transformation conditions in this routine.
s['select_params'] = [backend.Adapter(geom)]
return self._spatial_attribute(func, s, **kwargs)
def _geom_attribute(self, func, tolerance=0.05, **kwargs):
"""
DRY routine for setting up a GeoQuerySet method that attaches a
Geometry attribute (e.g., `centroid`, `point_on_surface`).
"""
s = {'select_field': GeomField()}
if connections[self.db].ops.oracle:
s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s'
s['procedure_args'] = {'tolerance': tolerance}
return self._spatial_attribute(func, s, **kwargs)
def _geomset_attribute(self, func, geom, tolerance=0.05, **kwargs):
"""
DRY routine for setting up a GeoQuerySet method that attaches a
Geometry attribute and takes a Geoemtry parameter. This is used
for geometry set-like operations (e.g., intersection, difference,
union, sym_difference).
"""
s = {
'geom_args': ('geom',),
'select_field': GeomField(),
'procedure_fmt': '%(geo_col)s,%(geom)s',
'procedure_args': {'geom': geom},
}
if connections[self.db].ops.oracle:
s['procedure_fmt'] += ',%(tolerance)s'
s['procedure_args']['tolerance'] = tolerance
return self._spatial_attribute(func, s, **kwargs)
def _geocol_select(self, geo_field, field_name):
"""
Helper routine for constructing the SQL to select the geographic
column. Takes into account if the geographic field is in a
ForeignKey relation to the current model.
"""
compiler = self.query.get_compiler(self.db)
opts = self.model._meta
if geo_field not in opts.fields:
# Is this operation going to be on a related geographic field?
# If so, it'll have to be added to the select related information
# (e.g., if 'location__point' was given as the field name).
# Note: the operation really is defined as "must add select related!"
self.query.add_select_related([field_name])
# Call pre_sql_setup() so that compiler.select gets populated.
compiler.pre_sql_setup()
for col, _, _ in compiler.select:
if col.output_field == geo_field:
return col.as_sql(compiler, compiler.connection)[0]
raise ValueError("%r not in compiler's related_select_cols" % geo_field)
elif geo_field not in opts.local_fields:
# This geographic field is inherited from another model, so we have to
# use the db table for the _parent_ model instead.
parent_model = geo_field.model._meta.concrete_model
return self._field_column(compiler, geo_field, parent_model._meta.db_table)
else:
return self._field_column(compiler, geo_field)
# Private API utilities, subject to change.
def _geo_field(self, field_name=None):
"""
Returns the first Geometry field encountered or the one specified via
the `field_name` keyword. The `field_name` may be a string specifying
the geometry field on this GeoQuerySet's model, or a lookup string
to a geometry field via a ForeignKey relation.
"""
if field_name is None:
# Incrementing until the first geographic field is found.
for field in self.model._meta.fields:
if isinstance(field, GeometryField):
return field
return False
else:
# Otherwise, check by the given field name -- which may be
# a lookup to a _related_ geographic field.
return GISLookup._check_geo_field(self.model._meta, field_name)
def _field_column(self, compiler, field, table_alias=None, column=None):
"""
Helper function that returns the database column for the given field.
The table and column are returned (quoted) in the proper format, e.g.,
`"geoapp_city"."point"`. If `table_alias` is not specified, the
database table associated with the model of this `GeoQuerySet` will be
used. If `column` is specified, it will be used instead of the value
in `field.column`.
"""
if table_alias is None:
table_alias = compiler.query.get_meta().db_table
return "%s.%s" % (compiler.quote_name_unless_alias(table_alias),
compiler.connection.ops.quote_name(column or field.column))
|
webmasterraj/FogOrNot | refs/heads/master | flask/lib/python2.7/site-packages/numpy/distutils/fcompiler/lahey.py | 229 | from __future__ import division, absolute_import, print_function
import os
from numpy.distutils.fcompiler import FCompiler
compilers = ['LaheyFCompiler']
class LaheyFCompiler(FCompiler):
compiler_type = 'lahey'
description = 'Lahey/Fujitsu Fortran 95 Compiler'
version_pattern = r'Lahey/Fujitsu Fortran 95 Compiler Release (?P<version>[^\s*]*)'
executables = {
'version_cmd' : ["<F90>", "--version"],
'compiler_f77' : ["lf95", "--fix"],
'compiler_fix' : ["lf95", "--fix"],
'compiler_f90' : ["lf95"],
'linker_so' : ["lf95", "-shared"],
'archiver' : ["ar", "-cr"],
'ranlib' : ["ranlib"]
}
module_dir_switch = None #XXX Fix me
module_include_switch = None #XXX Fix me
def get_flags_opt(self):
return ['-O']
def get_flags_debug(self):
return ['-g', '--chk', '--chkglobal']
def get_library_dirs(self):
opt = []
d = os.environ.get('LAHEY')
if d:
opt.append(os.path.join(d, 'lib'))
return opt
def get_libraries(self):
opt = []
opt.extend(['fj9f6', 'fj9i6', 'fj9ipp', 'fj9e6'])
return opt
if __name__ == '__main__':
from distutils import log
log.set_verbosity(2)
from numpy.distutils.fcompiler import new_fcompiler
compiler = new_fcompiler(compiler='lahey')
compiler.customize()
print(compiler.get_version())
|
UltrosBot/Ultros | refs/heads/master | system/plugins/manager.py | 1 | # coding=utf-8
import glob
import yaml
from copy import copy
from distutils.version import StrictVersion
from twisted.internet.defer import inlineCallbacks, returnValue, Deferred
from system.enums import PluginState
from system.events.manager import EventManager
from system.events.general import PluginUnloadedEvent, PluginLoadedEvent
from system.logging.logger import getLogger
from system.plugins.info import Info
from system.plugins.loaders.python import PythonPluginLoader
from system.singleton import Singleton
__author__ = 'Gareth Coles'
"""
The plugin manager. It manages plugins.
The manager is in charge of discovering, loading, unloading, reloading and
generally looking after all things plugin.
"""
OPERATORS = {
">": lambda x, y: x > y,
">=": lambda x, y: x >= y,
"<": lambda x, y: x < y,
"<=": lambda x, y: x <= y,
"==": lambda x, y: x == y,
"!=": lambda x, y: x != y,
}
def MISSING_OPERATOR(x, y):
return True
class PluginManager(object):
"""
The plugin manager itself. This is a Singleton.
"""
__metaclass__ = Singleton
factory_manager = None
log = None
module = ""
path = ""
info_objects = {}
plugin_objects = {}
events = EventManager()
def __init__(self, factory_manager=None,
path="./plugins", module="plugins"):
if factory_manager is None:
raise ValueError("Factory manager cannot be None!")
self.log = getLogger("Plugins")
self.loaders = {}
python_loader = PythonPluginLoader(factory_manager, self)
self.loaders["python"] = python_loader
self.factory_manager = factory_manager
self.module = module
self.path = path
try:
import hy # noqa
except ImportError:
hy = None # noqa
self.log.warn("Unable to find Hy - Hy plugins will not load")
self.log.warn("Install Hy with pip if you need this support")
def find_loader(self, info):
for loader in self.loaders.itervalues():
if loader.can_load_plugin(info):
return loader
return None
def add_loader(self, loader):
"""
Add a plugin loader, for loading specific types of plugin
This will fail with a result of False if there's already a loader
with the same name.
:param loader: Instance of your plugin loader
:type loader: BasePluginLoader
:returns: Whether the loader was added
:rtype: bool
"""
if loader.name in self.loaders:
return False
self.loaders[loader.name] = loader
return True
@inlineCallbacks
def remove_loader(self, name):
"""
Remove a plugin loader by name
This will fail with a result of False if there isn't a loader
registered with the specified name.
:param name: Name of the loader to remove
:type name: str
:returns: A Deferred, resulting in whether the loader was removed
:rtype: Deferred(bool)
"""
if name not in self.loaders:
returnValue(False)
to_unload = []
loader = self.loaders[name]
for plugin in self.plugin_objects.itervalues():
if plugin._loader == loader.name:
to_unload.append(plugin.info.name)
del loader
for plugin in to_unload:
_ = yield self.unload_plugin(plugin)
del self.loaders[name]
returnValue(True)
def scan(self, output=True):
"""
Scan for all the .plug files available.
:param output: Whether to output info messages
"""
self.info_objects = {}
files = glob.glob("%s/*.plug" % self.path)
if not files:
if output:
self.log.info("No plugins found.")
return
self.log.debug("Loading info files..")
for fn in files:
try:
obj = yaml.load(open(fn, "r"))
c_name = obj["core"]["name"] # "Cased" name
name = c_name.lower()
if name in self.info_objects:
self.log.error(
"Duplicate plugin name detected: %s" % c_name
)
self.log.error("Only the first one will be able to load!")
continue
self.info_objects[name] = Info(obj)
if output:
self.log.debug("Found plugin info: %s" % c_name)
except Exception:
self.log.exception("Error loading info file: %s" % fn)
if output:
self.log.info("%s plugins found." % len(self.info_objects))
extra = 0
for k, v in self.plugin_objects.iteritems():
if k in self.info_objects:
continue
extra += 1
self.info_objects[k] = v.info
if output:
if extra > 1:
self.log.warning("%s plugins have disappeared." % extra)
@inlineCallbacks
def load_plugins(self, plugins, output=True):
"""
Attempt to load up all plugins specified in a list
This is intended to do the primary plugin load operation on startup,
using the plugin names specified in the configuration.
Plugin names are not case-sensitive.
:param plugins: List of plugin names to look for
:param output: Whether to output errors and other messages to the log
:type plugins: list
:type output: bool
:returns: A Deferred, resulting in no value
:rtype: Deferred
"""
self.loaders["python"].setup()
# Plugins still needing loaded
to_load = []
# Final, ordered, list of plugins to load
load_order = []
# Get plugin info objects, etc.
for name in plugins:
name = name.lower()
if name not in self.info_objects:
if output:
self.log.warning("Unknown plugin: %s" % name)
continue
info = self.info_objects[name]
# Store the list of deps separately so we can keep track of the
# unmet ones, for logging later on
to_load.append((info, [i.lower() for i in info.dependencies]))
# Determine order
has_loaded = True
while len(to_load) > 0 and has_loaded:
has_loaded = False
# Iterate backwards so we can remove items
for x in xrange(len(to_load) - 1, -1, -1):
info = to_load[x][0]
deps = to_load[x][1]
self.log.trace(
"Checking dependencies for plugins: %s" % info.name
)
for i, dep in enumerate(copy(deps)):
if " " in dep:
dep_name, dep_operator, dep_version = dep.split(" ")
else:
dep_name = dep
dep_operator = None
dep_version = None
operator_func = OPERATORS.get(
dep_operator, MISSING_OPERATOR
)
if dep_version:
parsed_dep_version = StrictVersion(dep_version)
else:
parsed_dep_version = dep_version
for loaded in load_order:
# I know this isn't super efficient, but it doesn't
# matter, it's a tiny list. This comment exists
# purely for myself.
if loaded.name.lower() == dep_name:
self.log.trace("Found a dependency")
loaded_version = StrictVersion(loaded.version)
if not operator_func(
loaded_version, parsed_dep_version
):
break
deps[i] = None
if deps.count(None) == len(deps):
self.log.trace("No more deps")
break
self.log.trace(deps)
while None in deps:
deps.remove(None)
if len(deps) == 0:
# No outstanding dependencies - safe to load
self.log.trace(
"All dependencies met, adding to load queue."
)
load_order.append(info)
del to_load[x]
has_loaded = True
# Deal with unloadable plugins
if len(to_load) > 0:
for plugin in to_load:
self.log.warning(
'Unable to load plugin "%s" due to failed dependencies: '
'%s' %
(
plugin[0].name,
", ".join(plugin[1])
)
)
did_load = []
# Deal with loadable plugins
for info in load_order:
self.log.debug("Loading plugin: %s" % info.name)
result = yield self.load_plugin(info.name)
if result is PluginState.LoadError:
self.log.debug("LoadError")
pass # Already output by load_plugin
elif result is PluginState.UnknownType:
self.log.debug("UnknownType")
pass # Already output by load_plugin
elif result is PluginState.NotExists:
self.log.warning(
"Plugin state: NotExists (This should never happen)"
)
elif result is PluginState.Loaded:
if output:
self.log.info(
"Loaded plugin: %s v%s by %s" % (
info.name,
info.version,
info.author
)
)
did_load.append(info.name)
elif result is PluginState.AlreadyLoaded:
if output:
self.log.warning("Plugin already loaded: %s" % info.name)
elif result is PluginState.Unloaded: # Can actually happen now
self.log.warn("Plugin unloaded: %s" % info.name)
self.log.warn("This means the plugin disabled itself - did "
"it output anything on its own?")
elif result is PluginState.DependencyMissing:
self.log.debug("DependencyMissing")
self.log.info("Loaded {} plugins: {}".format(
len(did_load), ", ".join(sorted(did_load))
))
@inlineCallbacks
def load_plugin(self, name):
"""
Load a single plugin by its case-insensitive name
:param name: The name of the plugin to load
:type name: str
:return: A Deferred, resulting in a PluginState enum value representing
the result
:rtype: Deferred(PluginState)
"""
name = name.lower()
if name not in self.info_objects:
returnValue(PluginState.NotExists)
if name in self.plugin_objects:
returnValue(PluginState.AlreadyLoaded)
info = self.info_objects[name]
for dep in info.dependencies:
dep = dep.lower()
if " " in dep:
dep_name, dep_operator, dep_version = dep.split(" ")
else:
dep_name = dep
dep_operator = None
dep_version = None
operator_func = OPERATORS.get(
dep_operator, MISSING_OPERATOR
)
if dep_version:
parsed_dep_version = StrictVersion(dep_version)
else:
parsed_dep_version = dep_version
if dep_name not in self.plugin_objects:
returnValue(PluginState.DependencyMissing)
loaded = self.plugin_objects[dep_name]
loaded_version = StrictVersion(loaded.info.version)
if not operator_func(loaded_version, parsed_dep_version):
returnValue(PluginState.DependencyMissing)
loader = self.find_loader(info)
if loader is None:
self.log.error(
"Unknown plugin type: {} (Plugin: {})".format(
info.type, name
)
)
returnValue(PluginState.UnknownType)
result, obj = yield loader.load_plugin(info)
if result is PluginState.Loaded:
self.plugin_objects[name] = obj
event = PluginLoadedEvent(self, obj)
self.events.run_callback("PluginLoaded", event)
returnValue(result)
@inlineCallbacks
def unload_plugins(self, output=True):
"""
Unload all loaded plugins
:param output: A Deferred, resulting in whether to output errors and
other messages to the log
:type output: Deferred(bool)
"""
if output:
self.log.info(
"Unloading {} plugins..".format(len(self.plugin_objects))
)
for key in self.plugin_objects.keys():
result = yield self.unload_plugin(key)
if result is PluginState.LoadError:
self.log.warning(
"Plugin state: LoadError (This should never happen)"
)
elif result is PluginState.NotExists:
self.log.warning("No such plugin: {}".format(key))
elif result is PluginState.Loaded:
self.log.warning(
"Plugin state: Loaded (This should never happen)"
)
elif result is PluginState.AlreadyLoaded:
self.log.warning(
"Plugin state: Already Loaded (This should never happen)"
)
elif result is PluginState.Unloaded:
pass # Output by the unload_plugin function already
elif result is PluginState.DependencyMissing:
self.log.warning(
"Plugin state: DependencyMissing (This should never "
"happen)"
)
else:
self.log.warning(
"Unknown plugin state: {0} "
"(This should never happen)".format(
result
)
)
self.log.warning("Bug the developer of '{0}'!".format(key))
@inlineCallbacks
def unload_plugin(self, name):
"""
Unload a single loaded plugin by its case-insensitive name
:param name: The name of the plugin to unload
:type name: str
:return: A Deferred, resulting in a PluginState enum value representing
the result
:rtype: Deferred(PluginState)
"""
name = name.lower()
if name not in self.plugin_objects:
returnValue(PluginState.NotExists)
obj = self.plugin_objects[name]
if obj.sub_plugins is not None:
for o in obj.sub_plugins:
self.factory_manager.commands.unregister_commands_for_owner(o)
self.factory_manager.event_manager.remove_callbacks_for_plugin(
o
)
self.factory_manager.storage.release_files(o)
self.factory_manager.commands.unregister_commands_for_owner(obj)
self.factory_manager.event_manager.remove_callbacks_for_plugin(obj)
self.factory_manager.storage.release_files(obj)
try:
d = obj.deactivate()
if isinstance(d, Deferred):
_ = yield d
except Exception:
self.log.exception("Error deactivating plugin: %s" % obj.info.name)
event = PluginUnloadedEvent(self, obj)
self.events.run_callback("PluginUnloaded", event)
del self.plugin_objects[name]
self.log.info("Unloaded plugin: {}".format(name))
returnValue(PluginState.Unloaded)
def reload_plugins(self, output=True):
"""
Reload all loaded plugins
:param output: Whether to output errors and other messages to the log
:type output: bool
"""
plugins = self.plugin_objects.keys()
self.scan(output)
for name in plugins:
c_name = self.get_plugin_info(name).name
result = self.reload_plugin(name)
if result is PluginState.LoadError:
pass # Already output
elif result is PluginState.NotExists:
self.log.warning("Plugin has disappeared: %s" % c_name)
elif result is PluginState.Loaded:
if output:
self.log.info("Reloaded plugin: %s" % c_name)
elif result is PluginState.AlreadyLoaded:
if output:
self.log.warning("Plugin already loaded: %s" % c_name)
elif result is PluginState.Unloaded:
self.log.warning(
"Plugin state: Unloaded (This should never happen)"
)
elif result is PluginState.DependencyMissing:
pass # Already output
@inlineCallbacks
def reload_plugin(self, name):
"""
Reload a single loaded plugin by its case-insensitive name
:param name: The name of the plugin to reload
:type name: str
:return: A Deferred, resulting in a PluginState enum value representing
the result
:rtype: Deferred(PluginState)
"""
name = name.lower()
result = yield self.unload_plugin(name)
if result is not PluginState.Unloaded:
returnValue(result)
r = yield self.load_plugin(name)
returnValue(r)
def get_plugin(self, name):
"""
Get a plugin instance by its case-insensitive name
returns None if the plugin isn't loaded or doesn't exist
:param name: The name of the plugin to get
:type name: str
:return: PluginObject instance, or None
"""
name = name.lower()
if name in self.plugin_objects:
return self.plugin_objects[name]
return None
def get_plugin_info(self, name):
"""
Get a plugin's info object by its case-insensitive name
returns None if the plugin doesn't exist
:param name: The name of the plugin to get the info for
:type name: str
:return: Info instance, or None
"""
name = name.lower()
if name in self.info_objects:
return self.info_objects[name]
return None
def plugin_loaded(self, name):
"""
Check whether a plugin is loaded by its case-insensitive name
:param name: The name of the plugin to check
:type name: str
:return: Whether the plugin is loaded
:rtype: bool
"""
name = name.lower()
return name in self.plugin_objects
|
olasitarska/django | refs/heads/master | tests/middleware_exceptions/urls.py | 107 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^middleware_exceptions/view/$', views.normal_view),
url(r'^middleware_exceptions/not_found/$', views.not_found),
url(r'^middleware_exceptions/error/$', views.server_error),
url(r'^middleware_exceptions/null_view/$', views.null_view),
url(r'^middleware_exceptions/permission_denied/$', views.permission_denied),
url(r'^middleware_exceptions/template_response/$', views.template_response),
url(r'^middleware_exceptions/template_response_error/$', views.template_response_error),
]
|
mropert/conan | refs/heads/develop | conans/server/rest/server.py | 4 | import bottle
from conans.server.rest.api_v1 import ApiV1
from conans.model.version import Version
class ConanServer(object):
"""
Server class. Instances api_v1 application and run it.
Receives the store.
"""
store = None
root_app = None
def __init__(self, run_port, credentials_manager,
updown_auth_manager, authorizer, authenticator,
file_manager, search_manager, server_version, min_client_compatible_version,
server_capabilities):
assert(isinstance(server_version, Version))
assert(isinstance(min_client_compatible_version, Version))
server_capabilities = server_capabilities or []
self.api_v1 = ApiV1(credentials_manager, updown_auth_manager,
server_version, min_client_compatible_version,
server_capabilities)
self.root_app = bottle.Bottle()
self.root_app.mount("/v1/", self.api_v1)
self.run_port = run_port
self.api_v1.search_manager = search_manager
self.api_v1.authorizer = authorizer
self.api_v1.authenticator = authenticator
self.api_v1.file_manager = file_manager
self.api_v1.setup()
def run(self, **kwargs):
port = kwargs.pop("port", self.run_port)
debug_set = kwargs.pop("debug", False)
host = kwargs.pop("host", "localhost")
bottle.Bottle.run(self.root_app, host=host,
port=port, debug=debug_set, reloader=False)
|
spadae22/odoo | refs/heads/chris_master_8 | addons/website_gengo/controllers/main.py | 350 | # -*- coding: utf-8 -*-
import openerp
from openerp import http, SUPERUSER_ID
from openerp.http import request
import time
GENGO_DEFAULT_LIMIT = 20
class website_gengo(http.Controller):
@http.route('/website/get_translated_length', type='json', auth='user', website=True)
def get_translated_length(self, translated_ids, lang):
ir_translation_obj = request.registry['ir.translation']
result={"done":0}
gengo_translation_ids = ir_translation_obj.search(request.cr, request.uid, [('id','in',translated_ids),('gengo_translation','!=', False)])
for trans in ir_translation_obj.browse(request.cr, request.uid, gengo_translation_ids):
result['done'] += len(trans.source.split())
return result
@http.route('/website/check_gengo_set', type='json', auth='user', website=True)
def check_gengo_set(self):
user = request.registry['res.users'].browse(request.cr, SUPERUSER_ID, request.uid)
company_flag = 0
if not user.company_id.gengo_public_key or not user.company_id.gengo_private_key:
company_flag = user.company_id.id
return company_flag
@http.route('/website/set_gengo_config', type='json', auth='user', website=True)
def set_gengo_config(self,config):
user = request.registry['res.users'].browse(request.cr, request.uid, request.uid)
if user.company_id:
request.registry['res.company'].write(request.cr, request.uid, user.company_id.id, config)
return True
@http.route('/website/post_gengo_jobs', type='json', auth='user', website=True)
def post_gengo_jobs(self):
request.registry['base.gengo.translations']._sync_request(request.cr, request.uid, limit=GENGO_DEFAULT_LIMIT, context=request.context)
return True
|
hcs/mailman | refs/heads/master | bootstrap.py | 9 | ##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Bootstrap a buildout-based project
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
"""
import os, shutil, sys, tempfile, textwrap, urllib, urllib2, subprocess
from optparse import OptionParser
if sys.platform == 'win32':
def quote(c):
if ' ' in c:
return '"%s"' % c # work around spawn lamosity on windows
else:
return c
else:
quote = str
# See zc.buildout.easy_install._has_broken_dash_S for motivation and comments.
stdout, stderr = subprocess.Popen(
[sys.executable, '-Sc',
'try:\n'
' import ConfigParser\n'
'except ImportError:\n'
' print 1\n'
'else:\n'
' print 0\n'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
has_broken_dash_S = bool(int(stdout.strip()))
# In order to be more robust in the face of system Pythons, we want to
# run without site-packages loaded. This is somewhat tricky, in
# particular because Python 2.6's distutils imports site, so starting
# with the -S flag is not sufficient. However, we'll start with that:
if not has_broken_dash_S and 'site' in sys.modules:
# We will restart with python -S.
args = sys.argv[:]
args[0:0] = [sys.executable, '-S']
args = map(quote, args)
os.execv(sys.executable, args)
# Now we are running with -S. We'll get the clean sys.path, import site
# because distutils will do it later, and then reset the path and clean
# out any namespace packages from site-packages that might have been
# loaded by .pth files.
clean_path = sys.path[:]
import site
sys.path[:] = clean_path
for k, v in sys.modules.items():
if (hasattr(v, '__path__') and
len(v.__path__)==1 and
not os.path.exists(os.path.join(v.__path__[0],'__init__.py'))):
# This is a namespace package. Remove it.
sys.modules.pop(k)
is_jython = sys.platform.startswith('java')
setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py'
distribute_source = 'http://python-distribute.org/distribute_setup.py'
# parsing arguments
def normalize_to_url(option, opt_str, value, parser):
if value:
if '://' not in value: # It doesn't smell like a URL.
value = 'file://%s' % (
urllib.pathname2url(
os.path.abspath(os.path.expanduser(value))),)
if opt_str == '--download-base' and not value.endswith('/'):
# Download base needs a trailing slash to make the world happy.
value += '/'
else:
value = None
name = opt_str[2:].replace('-', '_')
setattr(parser.values, name, value)
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --setup-source and --download-base to point to
local resources, you can keep this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", dest="version",
help="use a specific zc.buildout version")
parser.add_option("-d", "--distribute",
action="store_true", dest="use_distribute", default=False,
help="Use Distribute rather than Setuptools.")
parser.add_option("--setup-source", action="callback", dest="setup_source",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or file location for the setup file. "
"If you use Setuptools, this will default to " +
setuptools_source + "; if you use Distribute, this "
"will default to " + distribute_source +"."))
parser.add_option("--download-base", action="callback", dest="download_base",
callback=normalize_to_url, nargs=1, type="string",
help=("Specify a URL or directory for downloading "
"zc.buildout and either Setuptools or Distribute. "
"Defaults to PyPI."))
parser.add_option("--eggs",
help=("Specify a directory for storing eggs. Defaults to "
"a temporary directory that is deleted when the "
"bootstrap script completes."))
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", None, action="store", dest="config_file",
help=("Specify the path to the buildout configuration "
"file to be used."))
options, args = parser.parse_args()
# if -c was provided, we push it back into args for buildout's main function
if options.config_file is not None:
args += ['-c', options.config_file]
if options.eggs:
eggs_dir = os.path.abspath(os.path.expanduser(options.eggs))
else:
eggs_dir = tempfile.mkdtemp()
if options.setup_source is None:
if options.use_distribute:
options.setup_source = distribute_source
else:
options.setup_source = setuptools_source
if options.accept_buildout_test_releases:
args.append('buildout:accept-buildout-test-releases=true')
args.append('bootstrap')
try:
import pkg_resources
import setuptools # A flag. Sometimes pkg_resources is installed alone.
if not hasattr(pkg_resources, '_distribute'):
raise ImportError
except ImportError:
ez_code = urllib2.urlopen(
options.setup_source).read().replace('\r\n', '\n')
ez = {}
exec ez_code in ez
setup_args = dict(to_dir=eggs_dir, download_delay=0)
if options.download_base:
setup_args['download_base'] = options.download_base
if options.use_distribute:
setup_args['no_fake'] = True
ez['use_setuptools'](**setup_args)
reload(sys.modules['pkg_resources'])
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
cmd = [quote(sys.executable),
'-c',
quote('from setuptools.command.easy_install import main; main()'),
'-mqNxd',
quote(eggs_dir)]
if not has_broken_dash_S:
cmd.insert(1, '-S')
find_links = options.download_base
if not find_links:
find_links = os.environ.get('bootstrap-testing-find-links')
if find_links:
cmd.extend(['-f', quote(find_links)])
if options.use_distribute:
setup_requirement = 'distribute'
else:
setup_requirement = 'setuptools'
ws = pkg_resources.working_set
setup_requirement_path = ws.find(
pkg_resources.Requirement.parse(setup_requirement)).location
env = dict(
os.environ,
PYTHONPATH=setup_requirement_path)
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setup_requirement_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
if is_jython:
import subprocess
exitcode = subprocess.Popen(cmd, env=env).wait()
else: # Windows prefers this, apparently; otherwise we would prefer subprocess
exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env]))
if exitcode != 0:
sys.stdout.flush()
sys.stderr.flush()
print ("An error occurred when trying to install zc.buildout. "
"Look above this message for any errors that "
"were output by easy_install.")
sys.exit(exitcode)
ws.add_entry(eggs_dir)
ws.require(requirement)
import zc.buildout.buildout
zc.buildout.buildout.main(args)
if not options.eggs: # clean up temporary egg directory
shutil.rmtree(eggs_dir)
|
HossainKhademian/YowsUP | refs/heads/master | yowsup/layers/auth/keystream.py | 67 | import hashlib, hmac, sys
from struct import pack
from operator import xor
from itertools import starmap
class RC4:
def __init__(self, key, drop):
self.s = []
self.i = 0;
self.j = 0;
self.s = [0] * 256
for i in range(0, len(self.s)):
self.s[i] = i
for i in range(0, len(self.s)):
self.j = (self.j + self.s[i] + key[i % len(key)]) % 256
RC4.swap(self.s, i, self.j)
self.j = 0;
self.cipher(bytearray(drop), 0, drop)
def cipher(self, data, offset, length):
while True:
num = length
length = num - 1
if num == 0: break
self.i = (self.i+1) % 256
self.j = (self.j + self.s[self.i]) % 256
RC4.swap(self.s, self.i, self.j)
num2 = offset
offset = num2 + 1
data[num2] = (data[num2] ^ self.s[(self.s[self.i] + self.s[self.j]) % 256])
@staticmethod
def swap(arr, i, j):
tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
class KeyStream:
def __init__(self, key, macKey):
self.key = key if sys.version_info < (3, 0) else bytes(key)
self.rc4 = RC4(self.key, 0x300)
self.macKey = str(macKey) if sys.version_info < (3, 0) else bytes(macKey)
self.seq = 0
def computeMac(self, bytes_buffer, int_offset, int_length):
mac = hmac.new(self.macKey, None, hashlib.sha1)
updateData = bytes_buffer[int_offset:] + bytearray([self.seq >> 24, (self.seq >> 16) % 256, (self.seq >> 8) % 256, self.seq % 256])
try:
mac.update(updateData)
except TypeError: #python3 support
mac.update(bytes(updateData))
self.seq += 1
return bytearray(mac.digest())
def decodeMessage(self, bufdata, macOffset, offset, length):
buf = bufdata[:-4]
hashed = bufdata[-4:]
numArray = self.computeMac(buf, 0, len(buf))
num = 0
while num < 4:
if numArray[macOffset + num] == hashed[num]:
num += 1
else:
raise Exception("INVALID MAC")
self.rc4.cipher(buf, 0, len(buf))
return buf
def encodeMessage(self, buf, macOffset, offset, length):
self.rc4.cipher(buf, offset, length)
mac = self.computeMac(buf, offset, length)
output = buf[0:macOffset] + mac[0:4] + buf[macOffset+4:]
return output
@staticmethod
def generateKeys(password, nonce):
resultBytes = []
for i in range(1, 5):
currNonce = nonce + bytearray([i])
resultBytes.append(KeyStream.pbkdf2(password, currNonce, 2, 20))
return resultBytes
#@staticmethod ##use if drop python-2.6 support
#def pbkdf2( password, salt, itercount, keylen):
# return bytearray(hashlib.pbkdf2_hmac('sha1', password, salt, itercount, keylen))
@staticmethod
def pbkdf2( password, salt, itercount, keylen, hashfn = hashlib.sha1 ):
def pbkdf2_F( h, salt, itercount, blocknum ):
def prf( h, data ):
hm = h.copy()
try:
hm.update(bytearray(data))
except TypeError: #python 3 support
hm.update(bytes(data))
d = hm.digest()
return bytearray(d)
U = prf( h, salt + pack('>i',blocknum ) )
T = U
for i in range(2, itercount + 1):
U = prf( h, U )
T = starmap(xor, zip(T, U))
return T
digest_size = hashfn().digest_size
l = int(keylen / digest_size)
if keylen % digest_size != 0:
l += 1
h = hmac.new(bytes(password), None, hashfn )
T = bytearray()
for i in range(1, l+1):
tmp = pbkdf2_F( h, salt, itercount, i )
T.extend(tmp)
return T[0: keylen] |
Ginray/my-flask-blog | refs/heads/master | manage.py | 2 | #!/usr/bin/env python
import os
from app import create_app, db
from app.models import User, Role, Permission, Post
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
return dict(app=app, db=db, User=User, Role=Role, Permission=Permission,
Post=Post)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
if __name__ == '__main__':
manager.run()
|
sbidoul/buildbot | refs/heads/master | master/buildbot/db/pool.py | 9 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import time
import traceback
import sqlalchemy as sa
from twisted.internet import threads
from twisted.python import log
from twisted.python import threadpool
from buildbot.db.buildrequests import AlreadyClaimedError
from buildbot.db.changesources import ChangeSourceAlreadyClaimedError
from buildbot.db.schedulers import SchedulerAlreadyClaimedError
from buildbot.process import metrics
# set this to True for *very* verbose query debugging output; this can
# be monkey-patched from master.cfg, too:
# from buildbot.db import pool
# pool.debug = True
debug = False
_debug_id = 1
def timed_do_fn(f):
"""Decorate a do function to log before, after, and elapsed time,
with the name of the calling function. This is not speedy!"""
def wrap(callable, *args, **kwargs):
global _debug_id
# get a description of the function that called us
st = traceback.extract_stack(limit=2)
file, line, name, _ = st[0]
# and its locals
frame = inspect.currentframe()
locals = frame.f_locals
# invent a unique ID for the description
id, _debug_id = _debug_id, _debug_id + 1
descr = "%s-%08x" % (name, id)
start_time = time.time()
log.msg("%s - before ('%s' line %d)" % (descr, file, line))
for name in locals:
if name in ('self', 'thd'):
continue
log.msg("%s - %s = %r" % (descr, name, locals[name]))
# wrap the callable to log the begin and end of the actual thread
# function
def callable_wrap(*args, **kargs):
log.msg("%s - thd start" % (descr,))
try:
return callable(*args, **kwargs)
finally:
log.msg("%s - thd end" % (descr,))
d = f(callable_wrap, *args, **kwargs)
@d.addBoth
def after(x):
end_time = time.time()
elapsed = (end_time - start_time) * 1000
log.msg("%s - after (%0.2f ms elapsed)" % (descr, elapsed))
return x
return d
wrap.__name__ = f.__name__
wrap.__doc__ = f.__doc__
return wrap
class DBThreadPool(object):
running = False
def __init__(self, engine, reactor, verbose=False):
# verbose is used by upgrade scripts, and if it is set we should print
# messages about versions and other warnings
log_msg = log.msg
if verbose:
def _log_msg(m):
print(m)
log_msg = _log_msg
self.reactor = reactor
pool_size = 5
# If the engine has an C{optimal_thread_pool_size} attribute, then the
# maxthreads of the thread pool will be set to that value. This is
# most useful for SQLite in-memory connections, where exactly one
# connection (and thus thread) should be used.
if hasattr(engine, 'optimal_thread_pool_size'):
pool_size = engine.optimal_thread_pool_size
self._pool = threadpool.ThreadPool(minthreads=1,
maxthreads=pool_size,
name='DBThreadPool')
self.engine = engine
if engine.dialect.name == 'sqlite':
vers = self.get_sqlite_version()
if vers < (3, 7):
log_msg("Using SQLite Version %s" % (vers,))
log_msg("NOTE: this old version of SQLite does not support "
"WAL journal mode; a busy master may encounter "
"'Database is locked' errors. Consider upgrading.")
if vers < (3, 6, 19):
log_msg("NOTE: this old version of SQLite is not "
"supported.")
raise RuntimeError("unsupported SQLite version")
self._start_evt = self.reactor.callWhenRunning(self._start)
# patch the do methods to do verbose logging if necessary
if debug:
self.do = timed_do_fn(self.do)
self.do_with_engine = timed_do_fn(self.do_with_engine)
def _start(self):
self._start_evt = None
if not self.running:
self._pool.start()
self._stop_evt = self.reactor.addSystemEventTrigger(
'during', 'shutdown', self._stop)
self.running = True
def _stop(self):
self._stop_evt = None
threads.deferToThreadPool(
self.reactor, self._pool, self.engine.dispose)
self._pool.stop()
self.running = False
def shutdown(self):
"""Manually stop the pool. This is only necessary from tests, as the
pool will stop itself when the reactor stops under normal
circumstances."""
if not self._stop_evt:
return # pool is already stopped
self.reactor.removeSystemEventTrigger(self._stop_evt)
self._stop()
# Try about 170 times over the space of a day, with the last few tries
# being about an hour apart. This is designed to span a reasonable amount
# of time for repairing a broken database server, while still failing
# actual problematic queries eventually
BACKOFF_START = 1.0
BACKOFF_MULT = 1.05
MAX_OPERATIONALERROR_TIME = 3600 * 24 # one day
def __thd(self, with_engine, callable, args, kwargs):
# try to call callable(arg, *args, **kwargs) repeatedly until no
# OperationalErrors occur, where arg is either the engine (with_engine)
# or a connection (not with_engine)
backoff = self.BACKOFF_START
start = time.time()
while True:
if with_engine:
arg = self.engine
else:
arg = self.engine.contextual_connect()
try:
try:
rv = callable(arg, *args, **kwargs)
assert not isinstance(rv, sa.engine.ResultProxy), \
"do not return ResultProxy objects!"
except sa.exc.OperationalError as e:
if not self.engine.should_retry(e):
log.err(e, 'Got fatal OperationalError on DB')
raise
elapsed = time.time() - start
if elapsed > self.MAX_OPERATIONALERROR_TIME:
log.err(e, ('Raising due to {0} seconds delay on DB '
'query retries'.format(self.MAX_OPERATIONALERROR_TIME)))
raise
metrics.MetricCountEvent.log(
"DBThreadPool.retry-on-OperationalError")
# sleep (remember, we're in a thread..)
time.sleep(backoff)
backoff *= self.BACKOFF_MULT
# and re-try
log.err(e, 'retrying {} after sql error {}'.format(callable, e))
continue
# AlreadyClaimedError are normal especially in a multimaster
# configuration
except (AlreadyClaimedError, ChangeSourceAlreadyClaimedError, SchedulerAlreadyClaimedError):
raise
except Exception as e:
log.err(e, 'Got fatal Exception on DB')
raise
finally:
if not with_engine:
arg.close()
break
return rv
def do(self, callable, *args, **kwargs):
return threads.deferToThreadPool(self.reactor, self._pool,
self.__thd, False, callable, args, kwargs)
def do_with_engine(self, callable, *args, **kwargs):
return threads.deferToThreadPool(self.reactor, self._pool,
self.__thd, True, callable, args, kwargs)
def get_sqlite_version(self):
import sqlite3
return sqlite3.sqlite_version_info
|
woerwin/handy | refs/heads/master | tools/gjslint/build/lib/closure_linter/__init__.py | 267 | #!/usr/bin/env python
# Copyright 2008 The Closure Linter Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Package indicator for gjslint."""
|
zhushun0008/sms-tools | refs/heads/master | software/models_interface/models_GUI.py | 24 | from Tkinter import *
from notebook import * # window with tabs
from dftModel_GUI_frame import *
from stft_GUI_frame import *
from sineModel_GUI_frame import *
from harmonicModel_GUI_frame import *
from stochasticModel_GUI_frame import *
from sprModel_GUI_frame import *
from spsModel_GUI_frame import *
from hprModel_GUI_frame import *
from hpsModel_GUI_frame import *
root = Tk( )
root.title('sms-tools models GUI')
nb = notebook(root, TOP) # make a few diverse frames (panels), each using the NB as 'master':
# uses the notebook's frame
f1 = Frame(nb( ))
dft = DftModel_frame(f1)
f2 = Frame(nb( ))
stft = Stft_frame(f2)
f3 = Frame(nb( ))
sine = SineModel_frame(f3)
f4 = Frame(nb( ))
harmonic = HarmonicModel_frame(f4)
f5 = Frame(nb( ))
stochastic = StochasticModel_frame(f5)
f6 = Frame(nb( ))
spr = SprModel_frame(f6)
f7 = Frame(nb( ))
sps = SpsModel_frame(f7)
f8 = Frame(nb( ))
hpr = HprModel_frame(f8)
f9 = Frame(nb( ))
hps = HpsModel_frame(f9)
nb.add_screen(f1, "DFT")
nb.add_screen(f2, "STFT")
nb.add_screen(f3, "Sine")
nb.add_screen(f4, "Harmonic")
nb.add_screen(f5, "Stochastic")
nb.add_screen(f6, "SPR")
nb.add_screen(f7, "SPS")
nb.add_screen(f8, "HPR")
nb.add_screen(f9, "HPS")
nb.display(f1)
root.geometry('+0+0')
root.mainloop( )
|
nicoboss/Floatmotion | refs/heads/master | OpenGL/raw/GLES2/APPLE/framebuffer_multisample.py | 8 | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GLES2 import _types as _cs
# End users want this...
from OpenGL.raw.GLES2._types import *
from OpenGL.raw.GLES2 import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'GLES2_APPLE_framebuffer_multisample'
def _f( function ):
return _p.createFunction( function,_p.PLATFORM.GLES2,'GLES2_APPLE_framebuffer_multisample',error_checker=_errors._error_checker)
GL_DRAW_FRAMEBUFFER_APPLE=_C('GL_DRAW_FRAMEBUFFER_APPLE',0x8CA9)
GL_DRAW_FRAMEBUFFER_BINDING_APPLE=_C('GL_DRAW_FRAMEBUFFER_BINDING_APPLE',0x8CA6)
GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_APPLE=_C('GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_APPLE',0x8D56)
GL_MAX_SAMPLES_APPLE=_C('GL_MAX_SAMPLES_APPLE',0x8D57)
GL_READ_FRAMEBUFFER_APPLE=_C('GL_READ_FRAMEBUFFER_APPLE',0x8CA8)
GL_READ_FRAMEBUFFER_BINDING_APPLE=_C('GL_READ_FRAMEBUFFER_BINDING_APPLE',0x8CAA)
GL_RENDERBUFFER_SAMPLES_APPLE=_C('GL_RENDERBUFFER_SAMPLES_APPLE',0x8CAB)
@_f
@_p.types(None,_cs.GLenum,_cs.GLsizei,_cs.GLenum,_cs.GLsizei,_cs.GLsizei)
def glRenderbufferStorageMultisampleAPPLE(target,samples,internalformat,width,height):pass
@_f
@_p.types(None,)
def glResolveMultisampleFramebufferAPPLE():pass
|
mufaddalq/cloudstack-datera-driver | refs/heads/4.2 | tools/marvin/marvin/sshClient.py | 1 | # 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 paramiko
import time
import cloudstackException
import contextlib
import logging
from marvin.codes import (
SUCCESS, FAIL, INVALID_INPUT, EXCEPTION_OCCURRED
)
from contextlib import closing
class SshClient(object):
'''
Added timeout flag for ssh connect calls.Default to 3.0 seconds
'''
def __init__(self, host, port, user, passwd, retries=20, delay=30,
log_lvl=logging.INFO, keyPairFiles=None, timeout=10.0):
self.host = None
self.port = 22
self.user = user
self.passwd = passwd
self.keyPairFiles = keyPairFiles
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.logger = logging.getLogger('sshClient')
self.retryCnt = 0
self.delay = 0
self.timeout = 3.0
ch = logging.StreamHandler()
ch.setLevel(log_lvl)
self.logger.addHandler(ch)
#Check invalid host value and raise exception
#Atleast host is required for connection
if host is not None and host != '':
self.host = host
if retries is not None and retries > 0:
self.retryCnt = retries
if delay is not None and delay > 0:
self.delay = delay
if timeout is not None and timeout > 0:
self.timeout = timeout
if port is not None or port >= 0:
self.port = port
if self.createConnection() == FAIL:
raise cloudstackException.\
internalError("Connection Failed")
def execute(self, command):
stdin, stdout, stderr = self.ssh.exec_command(command)
output = stdout.readlines()
errors = stderr.readlines()
results = []
if output is not None and len(output) == 0:
if errors is not None and len(errors) > 0:
for error in errors:
results.append(error.rstrip())
else:
for strOut in output:
results.append(strOut.rstrip())
self.logger.debug("{Cmd: %s via Host: %s} {returns: %s}" %
(command, str(self.host), results))
return results
def createConnection(self):
'''
@Name: createConnection
@Desc: Creates an ssh connection for
retries mentioned,along with sleep mentioned
@Output: SUCCESS on successful connection
FAIL If connection through ssh failed
'''
ret = FAIL
while self.retryCnt >= 0:
try:
self.logger.debug("SSH Connection: Host:%s User:%s\
Port:%s" %
(self.host, self.user, str(self.port)
))
if self.keyPairFiles is None:
self.ssh.connect(hostname=self.host,
port=self.port,
username=self.user,
password=self.passwd,
timeout=self.timeout)
else:
self.ssh.connect(hostname=self.host,
port=self.port,
username=self.user,
password=self.passwd,
key_filename=self.keyPairFiles,
timeout=self.timeout,
look_for_keys=False
)
ret = SUCCESS
break
except Exception as se:
self.retryCnt = self.retryCnt - 1
if self.retryCnt == 0:
break
time.sleep(self.delay)
return ret
def runCommand(self, command):
'''
@Name: runCommand
@Desc: Runs a command over ssh and
returns the result along with status code
@Input: command to execute
@Output: 1: status of command executed.
Default to None
SUCCESS : If command execution is successful
FAIL : If command execution has failed
EXCEPTION_OCCURRED: Exception occurred while executing
command
INVALID_INPUT : If invalid value for command is passed
2: stdin,stdout,stderr values of command output
'''
excep_msg = ''
ret = {"status": None, "stdin": None, "stdout": None, "stderr": None}
if command is None or command == '':
ret["status"] = INVALID_INPUT
return ret
try:
status_check = 1
stdin, stdout, stderr = self.ssh.exec_command(command)
output = stdout.readlines()
errors = stderr.readlines()
inp = stdin.readlines()
ret["stdin"] = inp
ret["stdout"] = output
ret["stderr"] = errors
if stdout is not None:
status_check = stdout.channel.recv_exit_status()
if status_check == 0:
ret["status"] = SUCCESS
else:
ret["status"] = FAIL
except Exception as e:
excep_msg = str(e)
ret["status"] = EXCEPTION_OCCURRED
finally:
self.logger.debug(" Host: %s Cmd: %s Output:%s Exception: %s" %
(self.host, command, str(ret), excep_msg))
return ret
def scp(self, srcFile, destPath):
transport = paramiko.Transport((self.host, int(self.port)))
transport.connect(username=self.user, password=self.passwd)
sftp = paramiko.SFTPClient.from_transport(transport)
try:
sftp.put(srcFile, destPath)
except IOError, e:
raise e
def close(self):
if self.ssh is not None:
self.ssh.close()
if __name__ == "__main__":
with contextlib.closing(SshClient("10.223.75.10", 22, "root",
"password")) as ssh:
print ssh.execute("ls -l")
|
e-q/scipy | refs/heads/master | scipy/ndimage/tests/test_c_api.py | 19 | import numpy as np
from numpy.testing import assert_allclose
from scipy import ndimage
from scipy.ndimage import _ctest
from scipy.ndimage import _cytest
from scipy._lib._ccallback import LowLevelCallable
FILTER1D_FUNCTIONS = [
lambda filter_size: _ctest.filter1d(filter_size),
lambda filter_size: _cytest.filter1d(filter_size, with_signature=False),
lambda filter_size: LowLevelCallable(_cytest.filter1d(filter_size, with_signature=True)),
lambda filter_size: LowLevelCallable.from_cython(_cytest, "_filter1d",
_cytest.filter1d_capsule(filter_size)),
]
FILTER2D_FUNCTIONS = [
lambda weights: _ctest.filter2d(weights),
lambda weights: _cytest.filter2d(weights, with_signature=False),
lambda weights: LowLevelCallable(_cytest.filter2d(weights, with_signature=True)),
lambda weights: LowLevelCallable.from_cython(_cytest, "_filter2d", _cytest.filter2d_capsule(weights)),
]
TRANSFORM_FUNCTIONS = [
lambda shift: _ctest.transform(shift),
lambda shift: _cytest.transform(shift, with_signature=False),
lambda shift: LowLevelCallable(_cytest.transform(shift, with_signature=True)),
lambda shift: LowLevelCallable.from_cython(_cytest, "_transform", _cytest.transform_capsule(shift)),
]
def test_generic_filter():
def filter2d(footprint_elements, weights):
return (weights*footprint_elements).sum()
def check(j):
func = FILTER2D_FUNCTIONS[j]
im = np.ones((20, 20))
im[:10,:10] = 0
footprint = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
footprint_size = np.count_nonzero(footprint)
weights = np.ones(footprint_size)/footprint_size
res = ndimage.generic_filter(im, func(weights),
footprint=footprint)
std = ndimage.generic_filter(im, filter2d, footprint=footprint,
extra_arguments=(weights,))
assert_allclose(res, std, err_msg="#{} failed".format(j))
for j, func in enumerate(FILTER2D_FUNCTIONS):
check(j)
def test_generic_filter1d():
def filter1d(input_line, output_line, filter_size):
for i in range(output_line.size):
output_line[i] = 0
for j in range(filter_size):
output_line[i] += input_line[i+j]
output_line /= filter_size
def check(j):
func = FILTER1D_FUNCTIONS[j]
im = np.tile(np.hstack((np.zeros(10), np.ones(10))), (10, 1))
filter_size = 3
res = ndimage.generic_filter1d(im, func(filter_size),
filter_size)
std = ndimage.generic_filter1d(im, filter1d, filter_size,
extra_arguments=(filter_size,))
assert_allclose(res, std, err_msg="#{} failed".format(j))
for j, func in enumerate(FILTER1D_FUNCTIONS):
check(j)
def test_geometric_transform():
def transform(output_coordinates, shift):
return output_coordinates[0] - shift, output_coordinates[1] - shift
def check(j):
func = TRANSFORM_FUNCTIONS[j]
im = np.arange(12).reshape(4, 3).astype(np.float64)
shift = 0.5
res = ndimage.geometric_transform(im, func(shift))
std = ndimage.geometric_transform(im, transform, extra_arguments=(shift,))
assert_allclose(res, std, err_msg="#{} failed".format(j))
for j, func in enumerate(TRANSFORM_FUNCTIONS):
check(j)
|
fulmicoton/pylearn2 | refs/heads/master | pylearn2/scripts/icml_2013_wrepl/multimodal/make_submission.py | 44 | from __future__ import print_function
import numpy as np
import sys
from theano.compat.six.moves import xrange
from theano import function
from theano import tensor as T
from pylearn2.utils import serial
from pylearn2.utils.string_utils import preprocess
def usage():
"""
Run
python make_submission.py <model> <test set>
where <test set> is public_test or private_test
(private_test will be released 72 hours before the end of the contest)
"""
if len(sys.argv) != 3:
usage()
print("(You used the wrong number of arguments)")
quit(-1)
_, model_path, test_set = sys.argv
model = serial.load(model_path)
# Load BOVW features
features_dir = preprocess('${PYLEARN2_DATA_PATH}/icml_2013_multimodal/'+test_set+'_layer_2_features')
vectors = []
for i in xrange(500):
vectors.append(serial.load(features_dir + '/' + str(i) + '.npy'))
features = np.concatenate(vectors, axis=0)
del vectors
# Load BOW targets
f = open('wordlist.txt')
wordlist = f.readlines()
f.close()
options_dir = preprocess('${PYLEARN2_DATA_PATH}/icml_2013_multimodal/'+test_set+'_options')
def load_options(option):
rval = np.zeros((500, 4000), dtype='float32')
for i in xrange(500):
f = open(options_dir + '/' + str(i) + '.option_' + str(option) + '.desc')
l = f.readlines()
f.close()
for w in l:
if w in wordlist:
rval[i, wordlist.index(w)] = 1
return rval
option_0, option_1 = [load_options(0), load_options(1)]
X = T.matrix()
Y0 = T.matrix()
Y1 = T.matrix()
Y_hat = model.fprop(X)
cost_0 = model.layers[-1].kl(Y=Y0, Y_hat=Y_hat)
cost_1 = model.layers[-1].kl(Y=Y1, Y_hat=Y_hat)
f = function([X, Y0, Y1], cost_1 < cost_0)
prediction = f(features, option_0, option_1)
f = open('submission.csv', 'w')
for i in xrange(500):
f.write(str(prediction[i])+'\n')
f.close()
|
Keenwawa/libopencm3 | refs/heads/master | scripts/data/lpc43xx/yaml_odict.py | 54 | import yaml
from collections import OrderedDict
def construct_odict(load, node):
"""This is the same as SafeConstructor.construct_yaml_omap(),
except the data type is changed to OrderedDict() and setitem is
used instead of append in the loop.
>>> yaml.load('''
... !!omap
... - foo: bar
... - mumble: quux
... - baz: gorp
... ''')
OrderedDict([('foo', 'bar'), ('mumble', 'quux'), ('baz', 'gorp')])
>>> yaml.load('''!!omap [ foo: bar, mumble: quux, baz : gorp ]''')
OrderedDict([('foo', 'bar'), ('mumble', 'quux'), ('baz', 'gorp')])
"""
omap = OrderedDict()
yield omap
if not isinstance(node, yaml.SequenceNode):
raise yaml.constructor.ConstructorError(
"while constructing an ordered map",
node.start_mark,
"expected a sequence, but found %s" % node.id, node.start_mark
)
for subnode in node.value:
if not isinstance(subnode, yaml.MappingNode):
raise yaml.constructor.ConstructorError(
"while constructing an ordered map", node.start_mark,
"expected a mapping of length 1, but found %s" % subnode.id,
subnode.start_mark
)
if len(subnode.value) != 1:
raise yaml.constructor.ConstructorError(
"while constructing an ordered map", node.start_mark,
"expected a single mapping item, but found %d items" % len(subnode.value),
subnode.start_mark
)
key_node, value_node = subnode.value[0]
key = load.construct_object(key_node)
value = load.construct_object(value_node)
omap[key] = value
yaml.add_constructor(u'tag:yaml.org,2002:omap', construct_odict)
def repr_pairs(dump, tag, sequence, flow_style=None):
"""This is the same code as BaseRepresenter.represent_sequence(),
but the value passed to dump.represent_data() in the loop is a
dictionary instead of a tuple."""
value = []
node = yaml.SequenceNode(tag, value, flow_style=flow_style)
if dump.alias_key is not None:
dump.represented_objects[dump.alias_key] = node
best_style = True
for (key, val) in sequence:
item = dump.represent_data({key: val})
if not (isinstance(item, yaml.ScalarNode) and not item.style):
best_style = False
value.append(item)
if flow_style is None:
if dump.default_flow_style is not None:
node.flow_style = dump.default_flow_style
else:
node.flow_style = best_style
return node
def repr_odict(dumper, data):
"""
>>> data = OrderedDict([('foo', 'bar'), ('mumble', 'quux'), ('baz', 'gorp')])
>>> yaml.dump(data, default_flow_style=False)
'!!omap\\n- foo: bar\\n- mumble: quux\\n- baz: gorp\\n'
>>> yaml.dump(data, default_flow_style=True)
'!!omap [foo: bar, mumble: quux, baz: gorp]\\n'
"""
return repr_pairs(dumper, u'tag:yaml.org,2002:omap', data.iteritems())
yaml.add_representer(OrderedDict, repr_odict)
|
google-code/android-scripting | refs/heads/master | python/src/Tools/bgen/bgen/bgenStackBuffer.py | 44 | """Buffers allocated on the stack."""
from bgenBuffer import FixedInputBufferType, FixedOutputBufferType
class StackOutputBufferType(FixedOutputBufferType):
"""Fixed output buffer allocated on the stack -- passed as (buffer, size).
Instantiate with the buffer size as parameter.
"""
def passOutput(self, name):
return "%s__out__, %s" % (name, self.size)
class VarStackOutputBufferType(StackOutputBufferType):
"""Output buffer allocated on the stack -- passed as (buffer, &size).
Instantiate with the buffer size as parameter.
"""
def getSizeDeclarations(self, name):
return []
def getAuxDeclarations(self, name):
return ["int %s__len__ = %s" % (name, self.size)]
def passOutput(self, name):
return "%s__out__, &%s__len__" % (name, name)
def mkvalueArgs(self, name):
return "%s__out__, (int)%s__len__" % (name, name)
class VarVarStackOutputBufferType(VarStackOutputBufferType):
"""Output buffer allocated on the stack -- passed as (buffer, size, &size).
Instantiate with the buffer size as parameter.
"""
def passOutput(self, name):
return "%s__out__, %s__len__, &%s__len__" % (name, name, name)
class ReturnVarStackOutputBufferType(VarStackOutputBufferType):
"""Output buffer allocated on the stack -- passed as (buffer, size) -> size.
Instantiate with the buffer size as parameter.
The function's return value is the size.
(XXX Should have a way to suppress returning it separately, too.)
"""
def passOutput(self, name):
return "%s__out__, %s__len__" % (name, name)
def mkvalueArgs(self, name):
return "%s__out__, (int)_rv" % name
|
shaded-enmity/dnf | refs/heads/master | dnf/yum/config.py | 1 | # Copyright 2002 Duke University
# Copyright (C) 2012-2013 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
Configuration parser and default values for yum.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from . import misc
from .misc import read_in_items_from_dot_dir
from dnf.pycomp import basestring
from iniparse.compat import ParsingError, RawConfigParser as ConfigParser
import copy
import dnf.conf.parser
import dnf.conf.substitutions
import dnf.const
import dnf.exceptions
import dnf.pycomp
import dnf.util
import os
import shlex
import types
class Option(object):
"""
This class handles a single Yum configuration file option. Create
subclasses for each type of supported configuration option.
Python descriptor foo (__get__ and __set__) is used to make option
definition easy and concise.
"""
def __init__(self, default=None, parse_default=False):
self._setattrname()
self.inherit = False
if parse_default:
default = self.parse(default)
self.default = default
def _setattrname(self):
"""Calculate the internal attribute name used to store option state in
configuration instances.
"""
self._attrname = '__opt%d' % id(self)
self._attrname_deleted = '__opt%d_deleted' % id(self)
def __get__(self, obj, objtype):
"""Called when the option is read (via the descriptor protocol).
:param obj: The configuration instance to modify.
:param objtype: The type of the config instance (not used).
:return: The parsed option value or the default value if the value
wasn't set in the configuration file.
"""
if getattr(obj, self._attrname_deleted, None) is True:
raise RuntimeError("Option is no longer a part of the conf.")
if obj is None:
return self
return getattr(obj, self._attrname, None)
def __set__(self, obj, value):
"""Called when the option is set (via the descriptor protocol).
:param obj: The configuration instance to modify.
:param value: The value to set the option to.
"""
# Only try to parse if it's a string
if isinstance(value, basestring):
try:
value = self.parse(value)
except ValueError as e:
raise ValueError('Error parsing "%s = %r": %s' % (self._optname,
value, str(e)))
elif isinstance(value, int):
try:
value = self.parse_int(value)
except ValueError as e:
raise ValueError('Error parsing "%s = %r": %s' % (self._optname,
value, str(e)))
setattr(obj, self._attrname, value)
def __delete__(self, obj):
setattr(obj, self._attrname_deleted, True)
def setup(self, obj, name):
"""Initialise the option for a config instance.
This must be called before the option can be set or retrieved.
:param obj: :class:`BaseConfig` (or subclass) instance.
:param name: Name of the option.
"""
self._optname = name
setattr(obj, self._attrname, copy.copy(self.default))
def clone(self):
"""Return a safe copy of this :class:`Option` instance.
:return: a safe copy of this :class:`Option` instance
"""
new = copy.copy(self)
new._setattrname()
return new
def parse(self, val):
"""Parse the string value to the :class:`Option`'s native value.
:param s: raw string value to parse
:return: validated native value
:raise: ValueError if there was a problem parsing the string.
Subclasses should override this
"""
return val
def parse_int(self, val):
"""Parse `n`, ensuring it is a suitable integer value.
Return parsed value or raise ValueError if it is not suitable.
"""
return val
def tostring(self, value):
"""Convert the :class:`Option`'s native value to a string value. This
does the opposite of the :func:`parse` method above.
Subclasses should override this.
:param value: native option value
:return: string representation of input
"""
return str(value)
def Inherit(option_obj):
"""Clone an Option` instance for the purposes of inheritance.
The returned instance has all the same properties as the input Option and
shares items such as the default value. Use this to avoid redefinition of
reused options.
"""
new_option = option_obj.clone()
new_option.inherit = True
return new_option
class ListOption(Option):
"""An option containing a list of strings."""
def __init__(self, default=None, parse_default=False):
if default is None:
default = []
super(ListOption, self).__init__(default, parse_default)
def parse(self, s):
"""Convert a string from the config file to a workable list, parses
globdir: paths as foo.d-style dirs.
:param s: The string to be converted to a list. Commas and
whitespace are used as separators for the list
:return: *s* converted to a list
"""
# we need to allow for the '\n[whitespace]' continuation - easier
# to sub the \n with a space and then read the lines
s = s.replace('\n', ' ')
s = s.replace(',', ' ')
results = []
for item in s.split():
if item.startswith('glob:'):
thisglob = item.replace('glob:', '')
results.extend(read_in_items_from_dot_dir(thisglob))
continue
results.append(item)
return results
def tostring(self, value):
"""Convert a list of to a string value. This does the
opposite of the :func:`parse` method above.
:param value: a list of values
:return: string representation of input
"""
return '\n '.join(value)
class UrlOption(Option):
"""This option handles lists of URLs with validation of the URL
scheme.
"""
def __init__(self, default=None, schemes=('http', 'ftp', 'file', 'https'),
allow_none=False):
super(UrlOption, self).__init__(default)
self.schemes = schemes
self.allow_none = allow_none
def parse(self, url):
"""Parse a url to make sure that it is valid, and in a scheme
that can be used.
:param url: a string containing the url to parse
:return: *url* if it is valid
:raises: :class:`ValueError` if there is an error parsing the url
"""
url = url.strip()
# Handle the "_none_" special case
if url.lower() == '_none_':
if self.allow_none:
return None
else:
raise ValueError('"_none_" is not a valid value')
# Check that scheme is valid
s = dnf.pycomp.urlparse.urlparse(url)[0]
if s not in self.schemes:
raise ValueError('URL must be %s not "%s"' % (self._schemelist(), s))
return url
def _schemelist(self):
'''Return a user friendly list of the allowed schemes
'''
if len(self.schemes) < 1:
return 'empty'
elif len(self.schemes) == 1:
return self.schemes[0]
else:
return '%s or %s' % (', '.join(self.schemes[:-1]), self.schemes[-1])
class UrlListOption(ListOption):
"""Option for handling lists of URLs with validation of the URL
scheme.
"""
def __init__(self, default=None, schemes=('http', 'ftp', 'file', 'https'),
parse_default=False):
super(UrlListOption, self).__init__(default, parse_default)
# Hold a UrlOption instance to assist with parsing
self._urloption = UrlOption(schemes=schemes)
def parse(self, s):
"""Parse a string containing multiple urls into a list, and
ensure that they are in a scheme that can be used.
:param s: the string to parse
:return: a list of strings containing the urls in *s*
:raises: :class:`ValueError` if there is an error parsing the urls
"""
out = []
s = s.replace('\n', ' ')
s = s.replace(',', ' ')
items = [item.replace(' ', '%20') for item in shlex.split(s)]
tmp = []
for item in items:
if item.startswith('glob:'):
thisglob = item.replace('glob:', '')
tmp.extend(read_in_items_from_dot_dir(thisglob))
continue
tmp.append(item)
for url in super(UrlListOption, self).parse(' '.join(tmp)):
out.append(self._urloption.parse(url))
return out
class IntOption(Option):
"""An option representing an integer value."""
def __init__(self, default=None, range_min=None, range_max=None):
super(IntOption, self).__init__(default)
self._range_min = range_min
self._range_max = range_max
def parse(self, s):
"""Parse a string containing an integer.
:param s: the string to parse
:return: the integer in *s*
:raises: :class:`ValueError` if there is an error parsing the
integer
"""
try:
val = int(s)
except (ValueError, TypeError):
raise ValueError('invalid integer value')
return self.parse_int(val)
def parse_int(self, n):
if self._range_max is not None and n > self._range_max:
raise ValueError('Out of range integer value.')
if self._range_min is not None and n < self._range_min:
raise ValueError('Out of range integer value.')
return n
class PositiveIntOption(IntOption):
"""An option representing a positive integer value, where 0 can
have a special representation.
"""
def __init__(self, default=None, range_min=0, range_max=None,
names_of_0=None):
super(PositiveIntOption, self).__init__(default, range_min, range_max)
self._names0 = names_of_0
def parse(self, s):
"""Parse a string containing a positive integer, where 0 can
have a special representation.
:param s: the string to parse
:return: the integer in *s*
:raises: :class:`ValueError` if there is an error parsing the
integer
"""
if s in self._names0:
return 0
return super(PositiveIntOption, self).parse(s)
class SecondsOption(Option):
"""An option representing an integer value of seconds, or a human
readable variation specifying days, hours, minutes or seconds
until something happens. Works like :class:`BytesOption`. Note
that due to historical president -1 means "never", so this accepts
that and allows the word never, too.
Valid inputs: 100, 1.5m, 90s, 1.2d, 1d, 0xF, 0.1, -1, never.
Invalid inputs: -10, -0.1, 45.6Z, 1d6h, 1day, 1y.
Return value will always be an integer
"""
MULTS = {'d': 60 * 60 * 24, 'h' : 60 * 60, 'm' : 60, 's': 1}
def parse(self, s):
"""Parse a string containing an integer value of seconds, or a human
readable variation specifying days, hours, minutes or seconds
until something happens. Works like :class:`BytesOption`. Note
that due to historical president -1 means "never", so this accepts
that and allows the word never, too.
Valid inputs: 100, 1.5m, 90s, 1.2d, 1d, 0xF, 0.1, -1, never.
Invalid inputs: -10, -0.1, 45.6Z, 1d6h, 1day, 1y.
:param s: the string to parse
:return: an integer representing the number of seconds
specified by *s*
:raises: :class:`ValueError` if there is an error parsing the string
"""
if len(s) < 1:
raise ValueError("no value specified")
if s == "-1" or s == "never": # Special cache timeout, meaning never
return -1
if s[-1].isalpha():
n = s[:-1]
unit = s[-1].lower()
mult = self.MULTS.get(unit, None)
if not mult:
raise ValueError("unknown unit '%s'" % unit)
else:
n = s
mult = 1
try:
n = float(n)
except (ValueError, TypeError):
raise ValueError('invalid value')
if n < 0:
raise ValueError("seconds value may not be negative")
return int(n * mult)
class BoolOption(Option):
"""An option representing a boolean value. The value can be one
of 0, 1, yes, no, true, or false.
"""
def parse(self, s):
"""Parse a string containing a boolean value. 1, yes, and
true will evaluate to True; and 0, no, and false will evaluate
to False. Case is ignored.
:param s: the string containing the boolean value
:return: the boolean value contained in *s*
:raises: :class:`ValueError` if there is an error in parsing
the boolean value
"""
s = s.lower()
if s in ('0', 'no', 'false'):
return False
elif s in ('1', 'yes', 'true'):
return True
else:
raise ValueError('invalid boolean value')
def tostring(self, value):
"""Convert a boolean value to a string value. This does the
opposite of the :func:`parse` method above.
:param value: the boolean value to convert
:return: a string representation of *value*
"""
if value:
return "1"
else:
return "0"
class FloatOption(Option):
"""An option representing a numeric float value."""
def parse(self, s):
"""Parse a string containing a numeric float value.
:param s: a string containing a numeric float value to parse
:return: the numeric float value contained in *s*
:raises: :class:`ValueError` if there is an error parsing
float value
"""
try:
return float(s.strip())
except (ValueError, TypeError):
raise ValueError('invalid float value')
class SelectionOption(Option):
"""Handles string values where only specific values are
allowed.
"""
def __init__(self, default=None, allowed=(), mapper={}):
super(SelectionOption, self).__init__(default)
self._allowed = allowed
self._mapper = mapper
def parse(self, s):
"""Parse a string for specific values.
:param s: the string to parse
:return: *s* if it contains a valid value
:raises: :class:`ValueError` if there is an error parsing the values
"""
if s in self._mapper:
s = self._mapper[s]
if s not in self._allowed:
raise ValueError('"%s" is not an allowed value' % s)
return s
class CaselessSelectionOption(SelectionOption):
"""Mainly for compatibility with :class:`BoolOption`, works like
:class:`SelectionOption` but lowers input case.
"""
def parse(self, s):
"""Parse a string for specific values.
:param s: the string to parse
:return: *s* if it contains a valid value
:raises: :class:`ValueError` if there is an error parsing the values
"""
return super(CaselessSelectionOption, self).parse(s.lower())
class BytesOption(Option):
"""An option representing a value in bytes. The value may be given
in bytes, kilobytes, megabytes, or gigabytes.
"""
# Multipliers for unit symbols
MULTS = {
'k': 1024,
'm': 1024*1024,
'g': 1024*1024*1024,
}
def parse(self, s):
"""Parse a friendly bandwidth option to bytes. The input
should be a string containing a (possibly floating point)
number followed by an optional single character unit. Valid
units are 'k', 'M', 'G'. Case is ignored. The convention that
1k = 1024 bytes is used.
Valid inputs: 100, 123M, 45.6k, 12.4G, 100K, 786.3, 0.
Invalid inputs: -10, -0.1, 45.6L, 123Mb.
:param s: the string to parse
:return: the number of bytes represented by *s*
:raises: :class:`ValueError` if the option can't be parsed
"""
if len(s) < 1:
raise ValueError("no value specified")
if s[-1].isalpha():
n = s[:-1]
unit = s[-1].lower()
mult = self.MULTS.get(unit, None)
if not mult:
raise ValueError("unknown unit '%s'" % unit)
else:
n = s
mult = 1
try:
n = float(n)
except ValueError:
raise ValueError("couldn't convert '%s' to number" % n)
if n < 0:
raise ValueError("bytes value may not be negative")
return int(n * mult)
class ThrottleOption(BytesOption):
"""An option representing a bandwidth throttle value. See
:func:`parse` for acceptable input values.
"""
def parse(self, s):
"""Get a throttle option. Input may either be a percentage or
a "friendly bandwidth value" as accepted by the
:class:`BytesOption`.
Valid inputs: 100, 50%, 80.5%, 123M, 45.6k, 12.4G, 100K, 786.0, 0.
Invalid inputs: 100.1%, -4%, -500.
:param s: the string to parse
:return: the bandwidth represented by *s*. The return value
will be an int if a bandwidth value was specified, and a
float if a percentage was given
:raises: :class:`ValueError` if input can't be parsed
"""
if len(s) < 1:
raise ValueError("no value specified")
if s[-1] == '%':
n = s[:-1]
try:
n = float(n)
except ValueError:
raise ValueError("couldn't convert '%s' to number" % n)
if n < 0 or n > 100:
raise ValueError("percentage is out of range")
return n / 100.0
else:
return BytesOption.parse(self, s)
class BaseConfig(object):
"""Base class for storing configuration definitions.
Subclass when creating your own definitions.
"""
def __init__(self):
self._section = None
self.cfg = None
for name in self.iterkeys():
option = self.optionobj(name)
option.setup(self, name)
def __str__(self):
out = []
out.append('[%s]' % self._section)
for name, value in self.iteritems():
out.append('%s: %r' % (name, value))
return '\n'.join(out)
def override(self, ovr_dict):
"""Override config values with those from ovr_dict.
Do nothing about the keys that are not options.
"""
for (ovr_opt, ovr_val) in ovr_dict.items():
opt = self.optionobj(ovr_opt, exceptions=False)
if opt is not None:
setattr(self, ovr_opt, ovr_val)
def populate(self, parser, section, parent=None):
"""Set option values from an INI file section.
:param parser: :class:`ConfigParser` instance (or subclass)
:param section: INI file section to read use
:param parent: Optional parent :class:`BaseConfig` (or
subclass) instance to use when doing option value
inheritance
"""
self.cfg = parser
self._section = section
if parser.has_section(section):
opts = set(parser.options(section))
else:
opts = set()
for name in self.iterkeys():
option = self.optionobj(name)
value = None
if name in opts:
value = parser.get(section, name)
else:
# No matching option in this section, try inheriting
if parent and option.inherit:
value = getattr(parent, name)
if value is not None:
setattr(self, name, value)
@classmethod
def optionobj(cls, name, exceptions=True):
"""Return the :class:`Option` instance for the given name.
:param cls: the class to return the :class:`Option` instance from
:param name: the name of the :class:`Option` instance to return
:param exceptions: defines what action to take if the
specified :class:`Option` instance does not exist. If *exceptions* is
True, a :class:`KeyError` will be raised. If *exceptions*
is False, None will be returned
:return: the :class:`Option` instance specified by *name*, or None if
it does not exist and *exceptions* is False
:raises: :class:`KeyError` if the specified :class:`Option` does not
exist, and *exceptions* is True
"""
obj = getattr(cls, name, None)
if isinstance(obj, Option):
return obj
elif exceptions:
raise KeyError
else:
return None
@classmethod
def isoption(cls, name):
"""Return True if the given name refers to a defined option.
:param cls: the class to find the option in
:param name: the name of the option to search for
:return: whether *name* specifies a defined option
"""
return cls.optionobj(name, exceptions=False) is not None
def iterkeys(self):
"""Yield the names of all defined options in the instance."""
for name in dir(self):
if self.isoption(name):
yield name
def iteritems(self):
"""Yield (name, value) pairs for every option in the
instance. The value returned is the parsed, validated option
value.
"""
# Use dir() so that we see inherited options too
for name in self.iterkeys():
yield (name, getattr(self, name))
def write(self, fileobj, section=None, always=()):
"""Write out the configuration to a file-like object.
:param fileobj: File-like object to write to
:param section: Section name to use. If not specified, the section name
used during parsing will be used
:param always: A sequence of option names to always write out.
Options not listed here will only be written out if they are at
non-default values. Set to None to dump out all options
"""
# Write section heading
if section is None:
if self._section is None:
raise ValueError("not populated, don't know section")
section = self._section
# Updated the ConfigParser with the changed values
cfg_options = self.cfg.options(section)
for name, value in self.iteritems():
option = self.optionobj(name)
if always is None or name in always or option.default != value \
or name in cfg_options:
self.cfg.set(section, name, option.tostring(value))
# write the updated ConfigParser to the fileobj.
self.cfg.write(fileobj)
class YumConf(BaseConfig):
"""Configuration option definitions for yum.conf's [main] section."""
debuglevel = IntOption(2, 0, 10) # :api
errorlevel = IntOption(2, 0, 10)
installroot = Option('/') # :api
config_file_path = Option(dnf.const.CONF_FILENAME) # :api
plugins = BoolOption(True)
pluginpath = ListOption([dnf.const.PLUGINPATH]) # :api
pluginconfpath = ListOption([dnf.const.PLUGINCONFPATH]) # :api
persistdir = Option(dnf.const.PERSISTDIR) # :api
def __init__(self):
super(YumConf, self).__init__()
self.substitutions = dnf.conf.substitutions.Substitutions()
def _var_replace(self, option):
path = getattr(self, option)
new_path = dnf.conf.parser.substitute(path, self.substitutions)
setattr(self, option, new_path)
def prepend_installroot(self, option):
# :api
path = getattr(self, option)
path = path.lstrip('/')
setattr(self, option, os.path.join(self.installroot, path))
@property
def releasever(self):
# :api
return self.substitutions.get('releasever')
@releasever.setter
def releasever(self, val):
# :api
if val is None:
self.substitutions.pop('releasever', None)
return
self.substitutions['releasever'] = val
recent = IntOption(7, range_min=0)
reset_nice = BoolOption(True)
cachedir = Option(dnf.const.SYSTEM_CACHEDIR) # :api
keepcache = BoolOption(False)
logdir = Option('/var/log') # :api
reposdir = ListOption(['/etc/yum/repos.d', '/etc/yum.repos.d']) # :api
debug_solver = BoolOption(False)
exclude = ListOption()
include = ListOption()
fastestmirror = BoolOption(False)
proxy = UrlOption(schemes=('http', 'ftp', 'https'), allow_none=True) #:api
proxy_username = Option() #:api
proxy_password = Option() #:api
username = Option() #:api
password = Option() #:api
installonlypkgs = ListOption(dnf.const.INSTALLONLYPKGS)
# NOTE: If you set this to 2, then because it keeps the current kernel it
# means if you ever install an "old" kernel it'll get rid of the newest one
# so you probably want to use 3 as a minimum ... if you turn it on.
installonly_limit = PositiveIntOption(0, range_min=2, # :api
names_of_0=["0", "<off>"])
tsflags = ListOption() # :api
assumeyes = BoolOption(False) # :api
assumeno = BoolOption(False)
defaultyes = BoolOption(False)
alwaysprompt = BoolOption(True)
diskspacecheck = BoolOption(True)
gpgcheck = BoolOption(False)
repo_gpgcheck = BoolOption(False)
localpkg_gpgcheck = BoolOption(False)
obsoletes = BoolOption(True)
showdupesfromrepos = BoolOption(False)
enabled = BoolOption(True)
enablegroups = BoolOption(True)
bandwidth = BytesOption(0)
minrate = BytesOption(1000)
ip_resolve = CaselessSelectionOption(
allowed=('ipv4', 'ipv6', 'whatever'),
mapper={'4': 'ipv4', '6': 'ipv6'})
throttle = ThrottleOption(0)
timeout = SecondsOption(120)
max_parallel_downloads = IntOption(None, range_min=1)
metadata_expire = SecondsOption(60 * 60 * 48) # 48 hours
metadata_timer_sync = SecondsOption(60 * 60 * 3) # 3 hours
disable_excludes = ListOption()
multilib_policy = SelectionOption('best', ('best', 'all')) # :api
best = BoolOption(False) # :api
install_weak_deps = BoolOption(True)
bugtracker_url = Option(dnf.const.BUGTRACKER)
color = SelectionOption('auto', ('auto', 'never', 'always'),
mapper={'on' : 'always', 'yes' : 'always',
'1' : 'always', 'true' : 'always',
'off' : 'never', 'no' : 'never',
'0' : 'never', 'false' : 'never',
'tty' : 'auto', 'if-tty' : 'auto'})
color_list_installed_older = Option('bold')
color_list_installed_newer = Option('bold,yellow')
color_list_installed_reinstall = Option('normal')
color_list_installed_extra = Option('bold,red')
color_list_available_upgrade = Option('bold,blue')
color_list_available_downgrade = Option('dim,cyan')
color_list_available_reinstall = Option('bold,underline,green')
color_list_available_install = Option('normal')
color_update_installed = Option('normal')
color_update_local = Option('bold')
color_update_remote = Option('normal')
color_search_match = Option('bold')
sslcacert = Option() # :api
sslverify = BoolOption(True) # :api
sslclientcert = Option() # :api
sslclientkey = Option() # :api
deltarpm = BoolOption(True)
history_record = BoolOption(True)
history_record_packages = ListOption(['dnf', 'rpm'])
rpmverbosity = Option('info')
strict = BoolOption(True) # :api
clean_requirements_on_remove = BoolOption(False)
history_list_view = SelectionOption('commands',
('single-user-commands', 'users',
'commands'),
mapper={'cmds': 'commands',
'default': 'commands'})
def dump(self):
"""Return a string representing the values of all the
configuration options.
:return: a string representing the values of all the
configuration options
"""
output = '[main]\n'
# we exclude all vars which start with _ or are in this list:
excluded_vars = ('cfg',
'config_file_path',
'disable_excludes',
'substitutions')
for attr in dir(self):
if attr.startswith('_'):
continue
if attr in excluded_vars:
continue
try:
res = getattr(self, attr)
except RuntimeError:
output += "(%s deleted)\n" % attr
continue
if isinstance(res, types.MethodType):
continue
if not res and type(res) not in (type(False), type(0)):
res = ''
if isinstance(res, list):
res = ',\n '.join(res)
output = output + '%s = %s\n' % (attr, res)
return output
def read(self, filename=None):
# :api
if filename is None:
filename = self.config_file_path
parser = ConfigParser()
config_pp = dnf.conf.parser.ConfigPreProcessor(filename)
try:
parser.readfp(config_pp)
except ParsingError as e:
raise dnf.exceptions.ConfigError("Parsing file failed: %s" % e)
self.populate(parser, 'main')
# update to where we read the file from
self.config_file_path = filename
@property
def verbose(self):
return self.debuglevel >= dnf.const.VERBOSE_LEVEL
class RepoConf(BaseConfig):
"""Option definitions for repository INI file sections."""
__cached_keys = set()
def iterkeys(self):
"""Yield the names of all defined options in the instance."""
ck = self.__cached_keys
if not isinstance(self, RepoConf):
ck = set()
if not ck:
ck.update(list(BaseConfig.iterkeys(self)))
for name in self.__cached_keys:
yield name
name = Option() # :api
enabled = Inherit(YumConf.enabled)
baseurl = UrlListOption() # :api
mirrorlist = UrlOption() # :api
metalink = UrlOption() # :api
mediaid = Option()
gpgkey = UrlListOption()
exclude = ListOption()
include = ListOption()
fastestmirror = Inherit(YumConf.fastestmirror)
proxy = Inherit(YumConf.proxy) #:api
proxy_username = Inherit(YumConf.proxy_username) #:api
proxy_password = Inherit(YumConf.proxy_password) #:api
username = Inherit(YumConf.username) #:api
password = Inherit(YumConf.password) #:api
gpgcheck = Inherit(YumConf.gpgcheck)
repo_gpgcheck = Inherit(YumConf.repo_gpgcheck)
enablegroups = Inherit(YumConf.enablegroups)
bandwidth = Inherit(YumConf.bandwidth)
minrate = Inherit(YumConf.minrate)
ip_resolve = Inherit(YumConf.ip_resolve)
throttle = Inherit(YumConf.throttle)
timeout = Inherit(YumConf.timeout)
max_parallel_downloads = Inherit(YumConf.max_parallel_downloads)
metadata_expire = Inherit(YumConf.metadata_expire)
cost = IntOption(1000)
priority = IntOption(99)
sslcacert = Inherit(YumConf.sslcacert) # :api
sslverify = Inherit(YumConf.sslverify) # :api
sslclientcert = Inherit(YumConf.sslclientcert) # :api
sslclientkey = Inherit(YumConf.sslclientkey) # :api
deltarpm = Inherit(YumConf.deltarpm)
skip_if_unavailable = BoolOption(True) # :api
def logdir_fit(current_logdir):
return current_logdir if dnf.util.am_i_root() else misc.getCacheDir()
|
ewanbarr/anansi | refs/heads/master | anansi/tcc/legacy_code/tcc_shutdown.py | 1 | from lxml import etree
from anansi.comms import TCPClient
from ConfigParser import ConfigParser
from anansi.config import config
import sys
import os
config_path = os.environ["ANANSI_CONFIG"]
config = ConfigParser()
config.read(os.path.join(config_path,"anansi.cfg"))
ANANSI_SERVER_IP = config.get("IPAddresses","anansi_ip")
ANANSI_SERVER_PORT = config.getint("IPAddresses","anansi_port")
class TCCMessage(object):
def __init__(self,user,comment=""):
self.root = self._gen_element("tcc_request")
self.user_info(user,comment)
def __str__(self):
return etree.tostring(self.root,encoding='ISO-8859-1')
def __repr__(self):
return etree.tostring(self.root,encoding='ISO-8859-1',pretty_print=True)
def _gen_element(self,name,text=None,attributes=None):
root = etree.Element(name)
if attributes is not None:
for key,val in attributes.items():
root.attrib[key] = val
if text is not None:
root.text = text
return root
def server_command(self,command):
elem = self._gen_element("server_command")
elem.append(self._gen_element("command",text=command))
self.root.append(elem)
def user_info(self,username,comment):
elem = self._gen_element("user_info")
elem.append(self._gen_element("name",text=username))
elem.append(self._gen_element("comment",text=comment))
self.root.append(elem)
def tcc_command(self,command):
elem = self._gen_element("tcc_command")
elem.append(self._gen_element("command",text=command))
self.root.append(elem)
def tcc_pointing(self,x,y,east_arm="enabled",west_arm="enabled",**attributes):
elem = self._gen_element("tcc_command")
elem.append(self._gen_element("command",text="point"))
pointing = self._gen_element("pointing",attributes=attributes)
pointing.append(self._gen_element("xcoord",text=str(x)))
pointing.append(self._gen_element("ycoord",text=str(y)))
arms = self._gen_element("arms")
arms.append(self._gen_element("east",text=east_arm))
arms.append(self._gen_element("west",text=west_arm))
elem.append(pointing)
elem.append(arms)
self.root.append(elem)
class TCCUser(object):
def send(self,msg,ip=ANANSI_SERVER_IP,port=ANANSI_SERVER_PORT,recv=True):
client = TCPClient(ip,port)
client.send(msg)
if recv:
response = client.receive()
else:
response = None
del client
return response
def shutdown():
msg = TCCMessage("ebarr")
msg.server_command("shutdown")
print repr(msg)
client = TCCUser()
client.send(str(msg),recv=False)
def point(x,y,system="equatorial",tracking="on",east_arm="enabled",west_arm="enabled"):
msg = TCCMessage("ebarr")
msg.tcc_pointing(x,y,system=system,tracking=tracking,east_arm=east_arm,west_arm=west_arm,units="hhmmss")
print repr(msg)
client = TCCUser()
print client.send(str(msg))
if __name__ == "__main__":
shutdown()
|
tdautc19841202/wechatpy | refs/heads/master | wechatpy/pay/__init__.py | 1 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import copy
import requests
import xmltodict
from optionaldict import optionaldict
from wechatpy.utils import random_string
from wechatpy.exceptions import WeChatPayException
from wechatpy.pay.utils import calculate_signature
from wechatpy.pay.utils import dict_to_xml
from wechatpy.pay.base import BaseWeChatPayAPI
from wechatpy.pay import api
class WeChatPay(object):
redpack = api.WeChatRedpack()
"""红包接口"""
transfer = api.WeChatTransfer()
"""企业付款接口"""
coupon = api.WeChatCoupon()
"""代金券接口"""
order = api.WeChatOrder()
"""订单接口"""
refund = api.WeChatRefund()
"""退款接口"""
tools = api.WeChatTools()
"""工具类接口"""
jsapi = api.WeChatJSAPI()
API_BASE_URL = 'https://api.mch.weixin.qq.com/'
def __new__(cls, *args, **kwargs):
self = super(WeChatPay, cls).__new__(cls)
for name, _api in self.__class__.__dict__.items():
if isinstance(_api, BaseWeChatPayAPI):
_api = copy.deepcopy(_api)
_api._client = self
setattr(self, name, _api)
return self
def __init__(self, appid, api_key, mch_id, sub_mch_id=None,
mch_cert=None, mch_key=None):
"""
:param appid: 微信公众号 appid
:param api_key: 商户 key
:param mch_id: 商户号
:param sub_mch_id: 可选,子商户号,受理模式下必填
:param mch_cert: 商户证书路径
:param mch_key: 商户证书私钥路径
"""
self.appid = appid
self.api_key = api_key
self.mch_id = mch_id
self.sub_mch_id = sub_mch_id
self.mch_cert = mch_cert
self.mch_key = mch_key
def _request(self, method, url_or_endpoint, **kwargs):
if not url_or_endpoint.startswith(('http://', 'https://')):
api_base_url = kwargs.pop('api_base_url', self.API_BASE_URL)
url = '{base}{endpoint}'.format(
base=api_base_url,
endpoint=url_or_endpoint
)
else:
url = url_or_endpoint
if isinstance(kwargs.get('data', ''), dict):
data = optionaldict(kwargs['data'])
if 'mchid' not in data:
# Fuck Tencent
data.setdefault('mch_id', self.mch_id)
data.setdefault('sub_mch_id', self.sub_mch_id)
data.setdefault('nonce_str', random_string(32))
sign = calculate_signature(data, self.api_key)
body = dict_to_xml(data, sign)
body = body.encode('utf-8')
kwargs['data'] = body
# 商户证书
if self.mch_cert and self.mch_key:
kwargs['cert'] = (self.mch_cert, self.mch_key)
res = requests.request(
method=method,
url=url,
**kwargs
)
try:
res.raise_for_status()
except requests.RequestException as reqe:
raise WeChatPayException(
return_code=None,
client=self,
request=reqe.request,
response=reqe.response
)
return self._handle_result(res)
def _handle_result(self, res):
xml = res.text
try:
data = xmltodict.parse(xml)['xml']
except xmltodict.ParsingInterrupted:
# 解析 XML 失败
return xml
return_code = data['return_code']
return_msg = data.get('return_msg')
result_code = data.get('result_code')
errcode = data.get('err_code')
errmsg = data.get('err_code_des')
if return_code != 'SUCCESS' or result_code != 'SUCCESS':
# 返回状态码不为成功
raise WeChatPayException(
return_code,
result_code,
return_msg,
errcode,
errmsg,
client=self,
request=res.request,
response=res
)
return data
def get(self, url, **kwargs):
return self._request(
method='get',
url_or_endpoint=url,
**kwargs
)
def post(self, url, **kwargs):
return self._request(
method='post',
url_or_endpoint=url,
**kwargs
)
|
netsec-ethz/scion | refs/heads/scionlab | python/topology/go.py | 1 | # Copyright 2014 ETH Zurich
# Copyright 2018 ETH Zurich, Anapaya Systems
#
# 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.
"""
:mod:`go` --- SCION topology go generator
=============================================
"""
# Stdlib
import os
import toml
import yaml
from typing import Mapping
# SCION
from python.lib.util import write_file
from python.topology.common import (
ArgsTopoDicts,
DISP_CONFIG_NAME,
docker_host,
prom_addr,
prom_addr_dispatcher,
sciond_ip,
sciond_name,
translate_features,
SD_API_PORT,
SD_CONFIG_NAME,
CO_CONFIG_NAME,
)
from python.topology.net import socket_address_str, NetworkDescription, IPNetwork
from python.topology.prometheus import (
CS_PROM_PORT,
DEFAULT_BR_PROM_PORT,
SCIOND_PROM_PORT,
DISP_PROM_PORT,
CO_PROM_PORT,
)
from python.topology.topo import DEFAULT_LINK_BW
CS_QUIC_PORT = 30352
CO_QUIC_PORT = 30357
class GoGenArgs(ArgsTopoDicts):
def __init__(self, args, topo_dicts, networks: Mapping[IPNetwork, NetworkDescription]):
super().__init__(args, topo_dicts)
self.networks = networks
class GoGenerator(object):
def __init__(self, args):
"""
:param GoGenArgs args: Contains the passed command line arguments and topo dicts.
"""
self.args = args
self.log_dir = '/share/logs' if args.docker else 'logs'
self.db_dir = '/share/cache' if args.docker else 'gen-cache'
self.certs_dir = '/share/crypto' if args.docker else 'gen-certs'
self.log_level = 'debug'
def generate_br(self):
for topo_id, topo in self.args.topo_dicts.items():
for k, v in topo.get("border_routers", {}).items():
base = topo_id.base_dir(self.args.output_dir)
br_conf = self._build_br_conf(topo_id, topo["isd_as"], base, k, v)
write_file(os.path.join(base, "%s.toml" % k), toml.dumps(br_conf))
def _build_br_conf(self, topo_id, ia, base, name, v):
config_dir = '/share/conf' if self.args.docker else base
raw_entry = {
'general': {
'id': name,
'config_dir': config_dir,
},
'log': self._log_entry(name),
'metrics': {
'prometheus': prom_addr(v['internal_addr'], DEFAULT_BR_PROM_PORT),
},
'features': translate_features(self.args.features),
}
return raw_entry
def generate_control_service(self):
for topo_id, topo in self.args.topo_dicts.items():
ca = 'issuing' in topo.get("attributes", [])
for elem_id, elem in topo.get("control_service", {}).items():
# only a single Go-BS per AS is currently supported
if elem_id.endswith("-1"):
base = topo_id.base_dir(self.args.output_dir)
bs_conf = self._build_control_service_conf(
topo_id, topo["isd_as"], base, elem_id, elem, ca)
write_file(os.path.join(base, "%s.toml" % elem_id),
toml.dumps(bs_conf))
def _build_control_service_conf(self, topo_id, ia, base, name, infra_elem, ca):
config_dir = '/share/conf' if self.args.docker else base
raw_entry = {
'general': {
'id': name,
'config_dir': config_dir,
'reconnect_to_dispatcher': True,
},
'log': self._log_entry(name),
'trust_db': {
'connection': os.path.join(self.db_dir, '%s.trust.db' % name),
},
'beacon_db': {
'connection': os.path.join(self.db_dir, '%s.beacon.db' % name),
},
'path_db': {
'connection': os.path.join(self.db_dir, '%s.path.db' % name),
},
'tracing': self._tracing_entry(),
'metrics': self._metrics_entry(infra_elem, CS_PROM_PORT),
'features': translate_features(self.args.features),
}
if ca:
raw_entry['renewal_db'] = {
'connection': os.path.join(self.db_dir, '%s.renewal.db' % name),
}
return raw_entry
def generate_co(self):
if not self.args.colibri:
return
for topo_id, topo in self.args.topo_dicts.items():
for elem_id, elem in topo.get("colibri_service", {}).items():
# only a single Go-CO per AS is currently supported
if elem_id.endswith("-1"):
base = topo_id.base_dir(self.args.output_dir)
co_conf = self._build_co_conf(topo_id, topo["isd_as"], base, elem_id, elem)
write_file(os.path.join(base, elem_id, CO_CONFIG_NAME), toml.dumps(co_conf))
traffic_matrix = self._build_co_traffic_matrix(topo_id)
write_file(os.path.join(base, elem_id, 'matrix.yml'),
yaml.dump(traffic_matrix, default_flow_style=False))
rsvps = self._build_co_reservations(topo_id)
write_file(os.path.join(base, elem_id, 'reservations.yml'),
yaml.dump(rsvps, default_flow_style=False))
def _build_co_conf(self, topo_id, ia, base, name, infra_elem):
config_dir = '/share/conf' if self.args.docker else base
raw_entry = {
'general': {
'ID': name,
'ConfigDir': config_dir,
'ReconnectToDispatcher': True,
},
'log': self._log_entry(name),
'trust_db': {
'connection': os.path.join(self.db_dir, '%s.trust.db' % name),
},
'tracing': self._tracing_entry(),
'metrics': self._metrics_entry(infra_elem, CO_PROM_PORT),
'features': translate_features(self.args.features),
}
return raw_entry
def _build_co_traffic_matrix(self, ia):
"""
Creates a NxN traffic matrix for colibri with N = len(interfaces)
"""
topo = self.args.topo_dicts[ia]
if_ids = {iface for br in topo['border_routers'].values() for iface in br['interfaces']}
if_ids.add(0)
bw = int(DEFAULT_LINK_BW / (len(if_ids) - 1))
traffic_matrix = {}
for inIfid in if_ids:
traffic_matrix[inIfid] = {}
for egIfid in if_ids.difference({inIfid}):
traffic_matrix[inIfid][egIfid] = bw
return traffic_matrix
def _build_co_reservations(self, ia):
"""
Generates a dictionary of reservations with one entry per core AS (if "ia" is core)
excluding itself, or a pair (up and down) per core AS in the ISD if "ia" is not core.
"""
rsvps = {}
this_as = self.args.topo_dicts[ia]
if this_as['Core']:
for dst_ia, topo in self.args.topo_dicts.items():
if dst_ia != ia and topo['Core']:
rsvps['Core-%s' % dst_ia] = self._build_co_reservation(dst_ia, 'Core')
else:
for dst_ia, topo in self.args.topo_dicts.items():
if dst_ia != ia and dst_ia._isd == ia._isd and topo['Core']:
# reach this core AS in the same ISD
rsvps['Up-%s' % dst_ia] = self._build_co_reservation(dst_ia, 'Up')
rsvps['Down-%s' % dst_ia] = self._build_co_reservation(dst_ia, 'Down')
return rsvps
def _build_co_reservation(self, dst_ia, path_type):
start_props = {'L', 'T'}
end_props = {'L', 'T'}
if path_type == 'Up':
start_props.remove('T')
elif path_type == 'Down':
end_props.remove('T')
return {
'desired_size': 27,
'ia': str(dst_ia),
'max_size': 30,
'min_size': 1,
'path_predicate': '%s#0' % dst_ia,
'path_type': path_type,
'split_cls': 8,
'end_props': {
'start': list(start_props),
'end': list(end_props)
}
}
def generate_sciond(self):
for topo_id, topo in self.args.topo_dicts.items():
base = topo_id.base_dir(self.args.output_dir)
sciond_conf = self._build_sciond_conf(topo_id, topo["isd_as"], base)
write_file(os.path.join(base, SD_CONFIG_NAME), toml.dumps(sciond_conf))
def _build_sciond_conf(self, topo_id, ia, base):
name = sciond_name(topo_id)
config_dir = '/share/conf' if self.args.docker else base
ip = sciond_ip(self.args.docker, topo_id, self.args.networks)
raw_entry = {
'general': {
'id': name,
'config_dir': config_dir,
'reconnect_to_dispatcher': True,
},
'log': self._log_entry(name),
'trust_db': {
'connection': os.path.join(self.db_dir, '%s.trust.db' % name),
},
'path_db': {
'connection': os.path.join(self.db_dir, '%s.path.db' % name),
},
'sd': {
'address': socket_address_str(ip, SD_API_PORT),
},
'tracing': self._tracing_entry(),
'metrics': {
'prometheus': socket_address_str(ip, SCIOND_PROM_PORT)
},
'features': translate_features(self.args.features),
}
return raw_entry
def generate_disp(self):
if self.args.docker:
self._gen_disp_docker()
else:
elem_dir = os.path.join(self.args.output_dir, "dispatcher")
config_file_path = os.path.join(elem_dir, DISP_CONFIG_NAME)
write_file(config_file_path, toml.dumps(self._build_disp_conf("dispatcher")))
def _gen_disp_docker(self):
for topo_id, topo in self.args.topo_dicts.items():
base = topo_id.base_dir(self.args.output_dir)
elem_ids = ['sig_%s' % topo_id.file_fmt()] + \
list(topo.get("border_routers", {})) + \
list(topo.get("control_service", {})) + \
['tester_%s' % topo_id.file_fmt()]
for k in elem_ids:
disp_id = 'disp_%s' % k
disp_conf = self._build_disp_conf(disp_id, topo_id)
write_file(os.path.join(base, '%s.toml' % disp_id), toml.dumps(disp_conf))
def _build_disp_conf(self, name, topo_id=None):
prometheus_addr = prom_addr_dispatcher(self.args.docker, topo_id,
self.args.networks, DISP_PROM_PORT, name)
return {
'dispatcher': {
'id': name,
},
'log': self._log_entry(name),
'metrics': {
'prometheus': prometheus_addr,
},
'features': translate_features(self.args.features),
}
def _tracing_entry(self):
docker_ip = docker_host(self.args.docker)
entry = {
'enabled': True,
'debug': True,
'agent': '%s:6831' % docker_ip
}
return entry
def _log_entry(self, name):
return {
'console': {
'level': self.log_level,
},
}
def _metrics_entry(self, infra_elem, base_port):
a = prom_addr(infra_elem['addr'], base_port)
return {
'prometheus': a,
}
|
googleapis/googleapis-gen | refs/heads/master | google/cloud/tpu/v1/tpu-v1-py/tests/unit/gapic/__init__.py | 951 |
# -*- coding: utf-8 -*-
# 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.
#
|
lonetwin/opencore | refs/heads/master | opencore/models/tests/test_adapters.py | 4 | # Copyright (C) 2008-2009 Open Society Institute
# Thomas Moroz: tmoroz.org
# 2010-2011 Large Blue
# Fergus Doyle: fergus.doyle@largeblue.com
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License Version 2 as published
# by the Free Software Foundation. You may not use, modify or distribute
# this program under any other version of the GNU General Public License.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
import unittest
from repoze.bfg import testing
from zope.interface import Interface
from opencore import testing as ocoretesting
class TestDeprecatedCatalogSearch(unittest.TestCase):
def setUp(self):
testing.cleanUp()
def tearDown(self):
testing.cleanUp()
def _getTargetClass(self):
from opencore.models.adapters import CatalogSearch
return CatalogSearch
def _makeOne(self, context, request):
global __warningregistry__
import warnings
old_filters = warnings.filters[:]
warnings.filterwarnings('ignore', category=DeprecationWarning)
try:
adapter = self._getTargetClass()(context, request)
finally:
warnings.filters[:] = old_filters
assert __warningregistry__
del __warningregistry__
return adapter
def test_it(self):
context = testing.DummyModel()
context.catalog = ocoretesting.DummyCatalog({})
request = testing.DummyRequest()
adapter = self._makeOne(context, request)
num, docids, resolver = adapter()
self.assertEqual(num, 0)
self.assertEqual(list(docids), [])
def test_unfound_model(self):
from repoze.bfg.interfaces import ILogger
class DummyLogger:
def warn(self, msg):
self.msg = msg
logger = DummyLogger()
testing.registerUtility(logger, ILogger, 'repoze.bfg.debug')
a = testing.DummyModel()
b = testing.DummyModel()
testing.registerModels({'/a':a})
context = testing.DummyModel()
context.catalog = ocoretesting.DummyCatalog({1:'/a', 2:'/b'})
request = testing.DummyRequest()
adapter = self._makeOne(context, request)
num, docids, resolver = adapter()
self.assertEqual(num, 2)
self.assertEqual(list(docids), [1, 2])
results = filter(None, map(resolver, docids))
self.assertEqual(results, [a])
self.assertEqual(logger.msg, 'Model missing: /b')
def test_unfound_docid(self):
context = testing.DummyModel()
context.catalog = ocoretesting.DummyCatalog({})
request = testing.DummyRequest()
adapter = self._makeOne(context, request)
num, docids, resolver = adapter()
self.assertEqual(resolver(123), None)
class TestCatalogSearch(unittest.TestCase):
def setUp(self):
testing.cleanUp()
def tearDown(self):
testing.cleanUp()
def _getTargetClass(self):
from opencore.models.adapters import CatalogSearch
return CatalogSearch
def _makeOne(self, context):
adapter = self._getTargetClass()(context)
return adapter
def test_it(self):
context = testing.DummyModel()
context.catalog = ocoretesting.DummyCatalog({})
adapter = self._makeOne(context)
num, docids, resolver = adapter()
self.assertEqual(num, 0)
self.assertEqual(list(docids), [])
def test_unfound_model(self):
from repoze.bfg.interfaces import ILogger
class DummyLogger:
def warn(self, msg):
self.msg = msg
logger = DummyLogger()
testing.registerUtility(logger, ILogger, 'repoze.bfg.debug')
a = testing.DummyModel()
b = testing.DummyModel()
testing.registerModels({'/a':a})
context = testing.DummyModel()
context.catalog = ocoretesting.DummyCatalog({1:'/a', 2:'/b'})
adapter = self._makeOne(context)
num, docids, resolver = adapter()
self.assertEqual(num, 2)
self.assertEqual(list(docids), [1, 2])
results = filter(None, map(resolver, docids))
self.assertEqual(results, [a])
self.assertEqual(logger.msg, 'Model missing: /b')
def test_unfound_docid(self):
context = testing.DummyModel()
context.catalog = ocoretesting.DummyCatalog({})
adapter = self._makeOne(context)
num, docids, resolver = adapter()
self.assertEqual(resolver(123), None)
class TestGridEntryInfo(unittest.TestCase):
def _getTargetClass(self):
from opencore.models.adapters import GridEntryInfo
return GridEntryInfo
def _makeOne(self, context, request):
return self._getTargetClass()(context, request)
def test_class_conforms_to_IGridEntryInfo(self):
from zope.interface.verify import verifyClass
from opencore.models.interfaces import IGridEntryInfo
verifyClass(IGridEntryInfo, self._getTargetClass())
# instance wont conform due to properties
def test_title(self):
request = testing.DummyRequest()
context = testing.DummyModel()
context.title = 'title'
adapter = self._makeOne(context, request)
self.assertEqual(adapter.title, 'title')
def test_url(self):
request = testing.DummyRequest()
context = testing.DummyModel()
adapter = self._makeOne(context, request)
self.assertEqual(adapter.url, 'http://example.com/')
def test_comment_url(self):
request = testing.DummyRequest()
context = testing.DummyModel()
commentfolder = testing.DummyModel()
grandparent = testing.DummyModel()
grandparent['commentfolder'] = commentfolder
commentfolder['0123'] = context
from zope.interface import directlyProvides
from opencore.models.interfaces import IComment
directlyProvides(context, IComment)
adapter = self._makeOne(context, request)
self.assertEqual(adapter.url, 'http://example.com/#comment-0123')
def test_type(self):
from zope.interface import Interface
from zope.interface import taggedValue
from zope.interface import directlyProvides
from repoze.lemonade.testing import registerContentFactory
request = testing.DummyRequest()
context = testing.DummyModel()
class Dummy:
pass
class IDummy(Interface):
taggedValue('name', 'yo')
registerContentFactory(Dummy, IDummy)
directlyProvides(context, IDummy)
adapter = self._makeOne(context, request)
self.assertEqual(adapter.type, 'yo')
def test_modified(self):
import datetime
request = testing.DummyRequest()
context = testing.DummyModel()
now = datetime.datetime.now()
context.modified = now
adapter = self._makeOne(context, request)
self.assertEqual(adapter.modified,now.strftime("%m/%d/%Y"))
def test_created(self):
import datetime
request = testing.DummyRequest()
context = testing.DummyModel()
now = datetime.datetime.now()
context.created = now
adapter = self._makeOne(context, request)
self.assertEqual(adapter.created,now.strftime("%m/%d/%Y"))
def test_creator_title(self):
request = testing.DummyRequest()
context = testing.DummyModel()
from opencore.models.interfaces import ISite
from zope.interface import directlyProvides
directlyProvides(context, ISite)
creator = testing.DummyModel(title='Dummy creator')
context['profiles'] = profiles = testing.DummyModel()
profiles['creator'] = creator
context.creator = 'creator'
adapter = self._makeOne(context, request)
self.assertEqual(adapter.creator_title,
'Dummy creator')
def test_creator_without_title(self):
request = testing.DummyRequest()
context = testing.DummyModel()
from opencore.models.interfaces import ISite
from zope.interface import directlyProvides
directlyProvides(context, ISite)
creator = testing.DummyModel()
context['profiles'] = profiles = testing.DummyModel()
profiles['creator'] = creator
context.creator = 'creator'
adapter = self._makeOne(context, request)
self.assertEqual(adapter.creator_title,
'no profile title')
def test_creator_url(self):
request = testing.DummyRequest()
context = testing.DummyModel()
from opencore.models.interfaces import ISite
from zope.interface import directlyProvides
directlyProvides(context, ISite)
creator = testing.DummyModel(title='Dummy creator')
context['profiles'] = profiles = testing.DummyModel()
profiles['creator'] = creator
context.creator = 'creator'
adapter = self._makeOne(context, request)
self.assertEqual(adapter.creator_url,
'http://example.com/profiles/creator/')
def test_modified_by_title_falls_back_to_creator(self):
request = testing.DummyRequest()
context = testing.DummyModel()
from opencore.models.interfaces import ISite
from zope.interface import directlyProvides
directlyProvides(context, ISite)
profile = testing.DummyModel(title='Test User')
context['profiles'] = profiles = testing.DummyModel()
profiles['testuser'] = profile
context.creator = 'testuser'
adapter = self._makeOne(context, request)
self.assertEqual(adapter.modified_by_title, 'Test User')
def test_modified_by_title(self):
request = testing.DummyRequest()
context = testing.DummyModel()
from opencore.models.interfaces import ISite
from zope.interface import directlyProvides
directlyProvides(context, ISite)
profile = testing.DummyModel(title='Test User')
context['profiles'] = profiles = testing.DummyModel()
profiles['testuser'] = profile
context.modified_by = 'testuser'
adapter = self._makeOne(context, request)
self.assertEqual(adapter.modified_by_title, 'Test User')
def test_modified_by_without_title(self):
request = testing.DummyRequest()
context = testing.DummyModel()
from opencore.models.interfaces import ISite
from zope.interface import directlyProvides
directlyProvides(context, ISite)
profile = testing.DummyModel()
context['profiles'] = profiles = testing.DummyModel()
profiles['testuser'] = profile
context.modified_by = 'testuser'
adapter = self._makeOne(context, request)
self.assertEqual(adapter.modified_by_title, 'no profile title')
def test_modified_by_without_profile(self):
request = testing.DummyRequest()
context = testing.DummyModel()
from opencore.models.interfaces import ISite
from zope.interface import directlyProvides
directlyProvides(context, ISite)
profile = testing.DummyModel()
context['profiles'] = profiles = testing.DummyModel()
context.modified_by = 'testuser'
adapter = self._makeOne(context, request)
self.assertEqual(adapter.modified_by_title, 'no profile title')
def test_modified_by_url(self):
request = testing.DummyRequest()
context = testing.DummyModel()
from opencore.models.interfaces import ISite
from zope.interface import directlyProvides
directlyProvides(context, ISite)
profile = testing.DummyModel(title='Test User')
context['profiles'] = profiles = testing.DummyModel()
profiles['testuser'] = profile
context.modified_by = 'testuser'
adapter = self._makeOne(context, request)
self.assertEqual(adapter.modified_by_url,
'http://example.com/profiles/testuser/')
class TestTagQuery(unittest.TestCase):
def setUp(self):
testing.cleanUp()
def tearDown(self):
testing.cleanUp()
def _getTargetClass(self):
from opencore.models.adapters import TagQuery
return TagQuery
def _makeOne(self, context, request):
manager = self._getTargetClass()(context, request)
manager.iface = DummyInterface
return manager
def test_tags_with_counts(self):
from zope.interface import directlyProvides
from opencore import testing as ocoretesting
context = testing.DummyModel()
request = testing.DummyRequest()
context.catalog = ocoretesting.DummyCatalog()
def dummy_getTagObjects(*args, **kw):
self.assertEqual(kw['items'], (123,))
return [testing.DummyModel(name='tag1', user='nyc1'),
testing.DummyModel(name='tag1', user='admin'),
testing.DummyModel(name='tag2', user='nyc1'),
]
dummy_tags = testing.DummyModel()
dummy_tags.getTagObjects = dummy_getTagObjects
context.tags = dummy_tags
directlyProvides(context, DummyInterface)
adapter = self._makeOne(context, request)
adapter._docid = 123
adapter.username = u'admin'
alltaginfo = adapter.tagswithcounts
self.assertEqual(len(alltaginfo), 2, alltaginfo)
self.assertEqual(alltaginfo[0]['count'], 2)
self.assertEqual(alltaginfo[0]['tag'], u'tag1')
self.assertEqual(alltaginfo[0]['snippet'], '')
self.assertEqual(alltaginfo[1]['count'], 1)
self.assertEqual(alltaginfo[1]['tag'], u'tag2')
self.assertEqual(alltaginfo[1]['snippet'], 'nondeleteable')
def test_tagusers(self):
context = testing.DummyModel()
tags = context.tags = testing.DummyModel()
def _getTags(*args, **kw):
self.assertEqual(kw['users'], ('dummy',))
self.assertEqual(kw['items'], (1,))
return ['1', '2']
tags.getTags = _getTags
request = testing.DummyRequest()
adapter = self._makeOne(context, request)
adapter._docid = 1
adapter.username = u'dummy'
self.assertEqual(adapter.tagusers, '1 2')
def test_docid(self):
from opencore import testing as ocoretesting
request = testing.DummyRequest()
context = testing.DummyModel()
context.catalog = ocoretesting.DummyCatalog()
adapter = self._makeOne(context, request)
self.assertEqual(adapter.docid, None)
def test_tags_with_prefix(self):
request = testing.DummyRequest()
context = testing.DummyModel()
tags = testing.DummyModel()
tags.getTagsWithPrefix = lambda x: x
context.tags = tags
adapter = self._makeOne(context, request)
generator = adapter.tags_with_prefix('1')
self.assertEqual(list(generator), ['1'])
class TestCommunityInfo(unittest.TestCase):
def _getTargetClass(self):
from opencore.models.adapters import CommunityInfo
return CommunityInfo
def _makeOne(self, context, request):
return self._getTargetClass()(context, request)
def _makeCommunity(self, **kw):
community = testing.DummyModel(title='title', description='description')
return community
def test_class_conforms_to_ICommunityInfo(self):
from zope.interface.verify import verifyClass
from opencore.models.interfaces import ICommunityInfo
verifyClass(ICommunityInfo, self._getTargetClass())
# instance wont conform due to properties
def test_number_of_members(self):
context = self._makeCommunity()
request = testing.DummyRequest()
context.number_of_members = 3
adapter = self._makeOne(context, request)
self.assertEqual(adapter.number_of_members, 3)
def test_tabs_requestcontext_iscommunity(self):
from opencore.models.interfaces import ICommunity
from opencore.models.interfaces import IToolFactory
from repoze.lemonade.testing import registerListItem
from zope.interface import directlyProvides
tool_factory = DummyToolFactory()
registerListItem(IToolFactory, tool_factory, 'one', title='One')
context = self._makeCommunity()
directlyProvides(context, ICommunity)
request = testing.DummyRequest()
request.context = context
adapter = self._makeOne(context, request)
tabs = adapter.tabs
self.assertEqual(len(tabs), 2)
self.assertEqual(tabs[0],
{'url': 'http://example.com/view.html',
'css_class': 'curr', 'name': 'OVERVIEW'}
)
self.assertEqual(tabs[1],
{'url': 'http://example.com/tab',
'css_class': '', 'name': 'ONE'}
)
def test_tabs_requestcontext_is_not_community(self):
from opencore.models.interfaces import IToolFactory
from repoze.lemonade.testing import registerListItem
tool_factory = DummyToolFactory()
registerListItem(IToolFactory, tool_factory, 'one', title='One')
context = self._makeCommunity()
request = testing.DummyRequest()
request.context = context
adapter = self._makeOne(context, request)
tabs = adapter.tabs
self.assertEqual(len(tabs), 2)
self.assertEqual(tabs[0],
{'url': 'http://example.com/view.html',
'css_class': '', 'name': 'OVERVIEW'}
)
self.assertEqual(tabs[1],
{'url': 'http://example.com/tab',
'css_class': 'curr', 'name': 'ONE'}
)
def test_description(self):
context = self._makeCommunity()
context.description = 'description'
request = testing.DummyRequest()
adapter = self._makeOne(context, request)
self.assertEqual(adapter.description, 'description')
def test_title(self):
context = self._makeCommunity()
context.title = 'title'
request = testing.DummyRequest()
adapter = self._makeOne(context, request)
self.assertEqual(adapter.title, 'title')
def test_name(self):
context = self._makeCommunity()
context.__name__ = 'name'
request = testing.DummyRequest()
adapter = self._makeOne(context, request)
self.assertEqual(adapter.name, 'name')
def test_last_activity_date(self):
context = self._makeCommunity()
import datetime
now = datetime.datetime.now()
context.content_modified = now
request = testing.DummyRequest()
adapter = self._makeOne(context, request)
self.assertEqual(adapter.last_activity_date, now.strftime("%m/%d/%Y"))
def test_url(self):
context = self._makeCommunity()
request = testing.DummyRequest()
adapter = self._makeOne(context, request)
self.assertEqual(adapter.url, 'http://example.com/')
def test_community_tags_no_tags_tool(self):
context = self._makeCommunity()
request = testing.DummyRequest()
adapter = self._makeOne(context, request)
self.assertEqual(len(adapter.community_tags), 0)
def test_community_tags_wo_tags_tool_less_than_five(self):
context = self._makeCommunity()
context.__name__ = 'dummy'
tool = context.tags = DummyTags([('foo', 3), ('bar', 6)])
request = testing.DummyRequest()
adapter = self._makeOne(context, request)
tags = adapter.community_tags
self.assertEqual(len(tags), 2)
self.assertEqual(tags[0], {'tag': 'bar', 'count': 6})
self.assertEqual(tags[1], {'tag': 'foo', 'count': 3})
self.assertEqual(tool._called_with, 'dummy')
def test_community_tags_wo_tags_tool_more_than_five(self):
context = self._makeCommunity()
context.tags = DummyTags([('foo', 3),
('bar', 6),
('baz', 14),
('qux', 1),
('quxxy', 4),
('spam', 2),
])
request = testing.DummyRequest()
adapter = self._makeOne(context, request)
tags = adapter.community_tags
self.assertEqual(len(tags), 5)
self.assertEqual(tags[0], {'tag': 'baz', 'count': 14})
self.assertEqual(tags[1], {'tag': 'bar', 'count': 6})
self.assertEqual(tags[2], {'tag': 'quxxy', 'count': 4})
self.assertEqual(tags[3], {'tag': 'foo', 'count': 3})
self.assertEqual(tags[4], {'tag': 'spam', 'count': 2})
def test_is_member_direct(self):
context = self._makeCommunity()
context.member_names = ['dummy', 'foo']
request = testing.DummyRequest()
testing.registerDummySecurityPolicy('dummy')
adapter = self._makeOne(context, request)
self.assertEqual(adapter.member, True)
def test_is_member_via_group(self):
context = self._makeCommunity()
context.member_names = ['a_group', 'foo']
request = testing.DummyRequest()
testing.registerDummySecurityPolicy('dummy', ['a_group'])
adapter = self._makeOne(context, request)
self.assertEqual(adapter.member, True)
def test_is_not_member(self):
context = self._makeCommunity()
context.member_names = ['foo', 'bar']
request = testing.DummyRequest()
testing.registerDummySecurityPolicy('dummy')
adapter = self._makeOne(context, request)
self.assertEqual(adapter.member, False)
def test_is_moderator(self):
context = self._makeCommunity()
context.moderator_names = ['dummy', 'foo']
request = testing.DummyRequest()
testing.registerDummySecurityPolicy('dummy')
adapter = self._makeOne(context, request)
self.assertEqual(adapter.moderator, True)
def test_is_not_moderator(self):
context = self._makeCommunity()
context.moderator_names = ['foo', 'bar']
request = testing.DummyRequest()
testing.registerDummySecurityPolicy('dummy')
adapter = self._makeOne(context, request)
self.assertEqual(adapter.moderator, False)
class FlexibleTextIndexDataTests(unittest.TestCase):
def _getTargetClass(self):
from opencore.models.adapters import FlexibleTextIndexData
return FlexibleTextIndexData
def _makeOne(self, context):
return self._getTargetClass()(context)
def test_class_conforms_to_ITextIndexData(self):
from zope.interface.verify import verifyClass
from opencore.models.interfaces import ITextIndexData
verifyClass(ITextIndexData, self._getTargetClass())
def test_instance_conforms_to_ITextIndexData(self):
from zope.interface.verify import verifyObject
from opencore.models.interfaces import ITextIndexData
context = testing.DummyModel()
verifyObject(ITextIndexData, self._makeOne(context))
def test___call___defaults_no_matching_attrs(self):
context = testing.DummyModel()
adapter = self._makeOne(context)
self.assertEqual(adapter(), '')
def test___call___defaults_skips_empty_attrs(self):
context = testing.DummyModel(title = '',
text = 'b',
)
adapter = self._makeOne(context)
self.assertEqual(adapter(), 'b')
def test___call___defaults_some_matching_attrs(self):
context = testing.DummyModel(title = 'a',
text = 'b',
)
adapter = self._makeOne(context)
self.assertEqual(adapter(), 'a ' * 10 + 'b')
def test___call___defaults_all_matching_attrs(self):
context = testing.DummyModel(title = 'a',
description = 'b',
text = 'c',
)
adapter = self._makeOne(context)
self.assertEqual(adapter(), 'a ' * 10 + 'b c')
def test___call___derived(self):
context = testing.DummyModel(title = 'a',
description = 'b',
text = 'c',
)
class Derived(self._getTargetClass()):
ATTR_WEIGHT_CLEANER = [('description', 2, None)]
context = testing.DummyModel(description='b')
adapter = Derived(context)
self.assertEqual(adapter(), 'b b')
def test___call___derived_w_extractor(self):
context = testing.DummyModel(title = 'a',
description = 'b',
text = 'c',
)
class Derived(self._getTargetClass()):
ATTR_WEIGHT_CLEANER = [(lambda x: 'z', 3, None),
('description', 2, None),
]
context = testing.DummyModel(description='b')
adapter = Derived(context)
self.assertEqual(adapter(), 'z z z b b')
def test___call___derived_w_cleaner(self):
context = testing.DummyModel(title = 'a',
description = 'b',
text = 'c',
)
class Derived(self._getTargetClass()):
ATTR_WEIGHT_CLEANER = [('title', 2, lambda x: 'y'),
]
context = testing.DummyModel(title='a')
adapter = Derived(context)
self.assertEqual(adapter(), 'y y')
class Test_makeFlexibleTextIndexData(unittest.TestCase):
def _callFUT(self, attr_weights):
from opencore.models.adapters import makeFlexibleTextIndexData
return makeFlexibleTextIndexData(attr_weights)
def test_no_attr_weights_raises(self):
self.assertRaises(ValueError, self._callFUT, ())
def test_w_attr_weights(self):
from zope.interface.verify import verifyObject
from opencore.models.interfaces import ITextIndexData
factory = self._callFUT([('title', 2, None),
('description', 1, None),
])
context = testing.DummyModel()
adapter = factory(context)
verifyObject(ITextIndexData, adapter)
self.assertEqual(adapter(), '')
context.title = 'a'
self.assertEqual(adapter(), 'a a')
context.description = 'b'
self.assertEqual(adapter(), 'a a b')
class TestTitleAndDescriptionIndexData(unittest.TestCase):
def setUp(self):
testing.cleanUp()
def tearDown(self):
testing.cleanUp()
def _getTargetClass(self):
from opencore.models.adapters import TitleAndDescriptionIndexData
return TitleAndDescriptionIndexData
def _makeOne(self, context):
return self._getTargetClass()(context)
def test_class_conforms_to_ITextIndexData(self):
from zope.interface.verify import verifyClass
from opencore.models.interfaces import ITextIndexData
verifyClass(ITextIndexData, self._getTargetClass())
def test_instance_conforms_to_ITextIndexData(self):
from zope.interface.verify import verifyObject
from opencore.models.interfaces import ITextIndexData
context = testing.DummyModel()
verifyObject(ITextIndexData, self._makeOne(context))
def test_no_description(self):
context = testing.DummyModel()
context.title = 'thetitle'
context.description = ''
adapter = self._makeOne(context)
data = adapter()
self.assertEqual(data, 'thetitle ' * 9 + 'thetitle')
def test_w_description(self):
context = testing.DummyModel()
context.title = 'thetitle'
context.description = 'Hi!'
adapter = self._makeOne(context)
data = adapter()
self.assertEqual(data, 'thetitle ' * 10 + 'Hi!')
class TestTitleAndTextIndexData(unittest.TestCase):
def setUp(self):
testing.cleanUp()
def tearDown(self):
testing.cleanUp()
def _getTargetClass(self):
from opencore.models.adapters import TitleAndTextIndexData
return TitleAndTextIndexData
def _makeOne(self, context):
return self._getTargetClass()(context)
def test_class_conforms_to_ITextIndexData(self):
from zope.interface.verify import verifyClass
from opencore.models.interfaces import ITextIndexData
verifyClass(ITextIndexData, self._getTargetClass())
def test_instance_conforms_to_ITextIndexData(self):
from zope.interface.verify import verifyObject
from opencore.models.interfaces import ITextIndexData
context = testing.DummyModel()
verifyObject(ITextIndexData, self._makeOne(context))
def test_no_text(self):
context = testing.DummyModel(title = 'thetitle',
text = '',
)
adapter = self._makeOne(context)
data = adapter()
self.assertEqual(data, 'thetitle ' * 9 + 'thetitle')
def test_w_text(self):
context = testing.DummyModel(title = 'thetitle',
text = '<html><body>Hi!</body></html>',
)
adapter = self._makeOne(context)
data = adapter()
self.assertEqual(data, 'thetitle ' * 10 + '\n\nHi!\n\n')
class TestFileTextIndexData(unittest.TestCase):
def setUp(self):
testing.cleanUp()
def tearDown(self):
testing.cleanUp()
def _getTargetClass(self):
from opencore.models.adapters import FileTextIndexData
return FileTextIndexData
def _makeOne(self, context):
return self._getTargetClass()(context)
def test_class_conforms_to_ITextIndexData(self):
from zope.interface.verify import verifyClass
from opencore.models.interfaces import ITextIndexData
verifyClass(ITextIndexData, self._getTargetClass())
def test_instance_conforms_to_ITextIndexData(self):
from zope.interface.verify import verifyObject
from opencore.models.interfaces import ITextIndexData
context = testing.DummyModel()
verifyObject(ITextIndexData, self._makeOne(context))
def test_no_converter(self):
context = testing.DummyModel()
context.title = 'Some Title'
context.mimetype = 'nonexistent'
adapter = self._makeOne(context)
self.assertEqual(adapter(), 'Some Title ' * 9 + 'Some Title')
def test_with_converter(self):
from opencore.utilities.converters.interfaces import IConverter
converter = DummyConverter('stuff')
testing.registerUtility(converter, IConverter, 'mimetype')
context = testing.DummyModel()
context.title = 'Some Title'
context.mimetype = 'mimetype'
context.blobfile = DummyBlobFile()
adapter = self._makeOne(context)
self.assertEqual(adapter(), 'Some Title ' * 10 + 'stuff')
def test_cache_with_converter(self):
from opencore.utilities.converters.interfaces import IConverter
converter = DummyConverter('stuff')
testing.registerUtility(converter, IConverter, 'mimetype')
context = testing.DummyModel()
context.title = 'Some Title'
context.mimetype = 'mimetype'
context.blobfile = DummyBlobFile()
adapter = self._makeOne(context)
self.assertEqual(converter.called, 0)
self.assertEqual(adapter(), 'Some Title ' * 10 + 'stuff')
self.assertEqual(converter.called, 1)
self.assertEqual(adapter(), 'Some Title ' * 10 + 'stuff')
self.assertEqual(converter.called, 1) # Didn't call converter again
class DummyConverter:
def __init__(self, data):
self.data = data
self.called = 0
def convert(self, filename, encoding=None, mimetype=None):
self.called += 1
import StringIO
return StringIO.StringIO(self.data), 'ascii'
class DummyBlobFile:
def _current_filename(self):
return None
class DummyTags:
_called_with = None
def __init__(self, tags=()):
self._tags = tags
def getFrequency(self, tags=None, community=None):
assert tags is None
self._called_with = community
return self._tags
class DummyToolFactory:
def is_present(self, context, request):
return True
def tab_url(self, context, request):
return 'http://example.com/tab'
def is_current(self, context, request):
return True
class DummyInterface(Interface):
pass
class DummyFieldIndex:
def __init__(self, data={}):
self._fwd_index = data
|
johnbryan/jbryanOrg | refs/heads/master | lib/flask/__init__.py | 345 | # -*- coding: utf-8 -*-
"""
flask
~~~~~
A microframework based on Werkzeug. It's extensively documented
and follows best practice patterns.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
__version__ = '0.10'
# utilities we import from Werkzeug and Jinja2 that are unused
# in the module but are exported as public interface.
from werkzeug.exceptions import abort
from werkzeug.utils import redirect
from jinja2 import Markup, escape
from .app import Flask, Request, Response
from .config import Config
from .helpers import url_for, flash, send_file, send_from_directory, \
get_flashed_messages, get_template_attribute, make_response, safe_join, \
stream_with_context
from .globals import current_app, g, request, session, _request_ctx_stack, \
_app_ctx_stack
from .ctx import has_request_context, has_app_context, \
after_this_request, copy_current_request_context
from .module import Module
from .blueprints import Blueprint
from .templating import render_template, render_template_string
# the signals
from .signals import signals_available, template_rendered, request_started, \
request_finished, got_request_exception, request_tearing_down, \
appcontext_tearing_down, appcontext_pushed, \
appcontext_popped, message_flashed
# We're not exposing the actual json module but a convenient wrapper around
# it.
from . import json
# This was the only thing that flask used to export at one point and it had
# a more generic name.
jsonify = json.jsonify
# backwards compat, goes away in 1.0
from .sessions import SecureCookieSession as Session
json_available = True
|
aprefontaine/TMScheduler | refs/heads/master | django/contrib/gis/gdal/srs.py | 30 | """
The Spatial Reference class, represensents OGR Spatial Reference objects.
Example:
>>> from django.contrib.gis.gdal import SpatialReference
>>> srs = SpatialReference('WGS84')
>>> print srs
GEOGCS["WGS 84",
DATUM["WGS_1984",
SPHEROID["WGS 84",6378137,298.257223563,
AUTHORITY["EPSG","7030"]],
TOWGS84[0,0,0,0,0,0,0],
AUTHORITY["EPSG","6326"]],
PRIMEM["Greenwich",0,
AUTHORITY["EPSG","8901"]],
UNIT["degree",0.01745329251994328,
AUTHORITY["EPSG","9122"]],
AUTHORITY["EPSG","4326"]]
>>> print srs.proj
+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs
>>> print srs.ellipsoid
(6378137.0, 6356752.3142451793, 298.25722356300003)
>>> print srs.projected, srs.geographic
False True
>>> srs.import_epsg(32140)
>>> print srs.name
NAD83 / Texas South Central
"""
import re
from ctypes import byref, c_char_p, c_int, c_void_p
# Getting the error checking routine and exceptions
from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.error import OGRException, SRSException
from django.contrib.gis.gdal.prototypes import srs as capi
#### Spatial Reference class. ####
class SpatialReference(GDALBase):
"""
A wrapper for the OGRSpatialReference object. According to the GDAL website,
the SpatialReference object "provide[s] services to represent coordinate
systems (projections and datums) and to transform between them."
"""
#### Python 'magic' routines ####
def __init__(self, srs_input=''):
"""
Creates a GDAL OSR Spatial Reference object from the given input.
The input may be string of OGC Well Known Text (WKT), an integer
EPSG code, a PROJ.4 string, and/or a projection "well known" shorthand
string (one of 'WGS84', 'WGS72', 'NAD27', 'NAD83').
"""
buf = c_char_p('')
srs_type = 'user'
if isinstance(srs_input, basestring):
# Encoding to ASCII if unicode passed in.
if isinstance(srs_input, unicode):
srs_input = srs_input.encode('ascii')
try:
# If SRID is a string, e.g., '4326', then make acceptable
# as user input.
srid = int(srs_input)
srs_input = 'EPSG:%d' % srid
except ValueError:
pass
elif isinstance(srs_input, (int, long)):
# EPSG integer code was input.
srs_type = 'epsg'
elif isinstance(srs_input, self.ptr_type):
srs = srs_input
srs_type = 'ogr'
else:
raise TypeError('Invalid SRS type "%s"' % srs_type)
if srs_type == 'ogr':
# Input is already an SRS pointer.
srs = srs_input
else:
# Creating a new SRS pointer, using the string buffer.
srs = capi.new_srs(buf)
# If the pointer is NULL, throw an exception.
if not srs:
raise SRSException('Could not create spatial reference from: %s' % srs_input)
else:
self.ptr = srs
# Importing from either the user input string or an integer SRID.
if srs_type == 'user':
self.import_user_input(srs_input)
elif srs_type == 'epsg':
self.import_epsg(srs_input)
def __del__(self):
"Destroys this spatial reference."
if self._ptr: capi.release_srs(self._ptr)
def __getitem__(self, target):
"""
Returns the value of the given string attribute node, None if the node
doesn't exist. Can also take a tuple as a parameter, (target, child),
where child is the index of the attribute in the WKT. For example:
>>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]')
>>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326
>>> print srs['GEOGCS']
WGS 84
>>> print srs['DATUM']
WGS_1984
>>> print srs['AUTHORITY']
EPSG
>>> print srs['AUTHORITY', 1] # The authority value
4326
>>> print srs['TOWGS84', 4] # the fourth value in this wkt
0
>>> print srs['UNIT|AUTHORITY'] # For the units authority, have to use the pipe symbole.
EPSG
>>> print srs['UNIT|AUTHORITY', 1] # The authority value for the untis
9122
"""
if isinstance(target, tuple):
return self.attr_value(*target)
else:
return self.attr_value(target)
def __str__(self):
"The string representation uses 'pretty' WKT."
return self.pretty_wkt
#### SpatialReference Methods ####
def attr_value(self, target, index=0):
"""
The attribute value for the given target node (e.g. 'PROJCS'). The index
keyword specifies an index of the child node to return.
"""
if not isinstance(target, basestring) or not isinstance(index, int):
raise TypeError
return capi.get_attr_value(self.ptr, target, index)
def auth_name(self, target):
"Returns the authority name for the given string target node."
return capi.get_auth_name(self.ptr, target)
def auth_code(self, target):
"Returns the authority code for the given string target node."
return capi.get_auth_code(self.ptr, target)
def clone(self):
"Returns a clone of this SpatialReference object."
return SpatialReference(capi.clone_srs(self.ptr))
def from_esri(self):
"Morphs this SpatialReference from ESRI's format to EPSG."
capi.morph_from_esri(self.ptr)
def identify_epsg(self):
"""
This method inspects the WKT of this SpatialReference, and will
add EPSG authority nodes where an EPSG identifier is applicable.
"""
capi.identify_epsg(self.ptr)
def to_esri(self):
"Morphs this SpatialReference to ESRI's format."
capi.morph_to_esri(self.ptr)
def validate(self):
"Checks to see if the given spatial reference is valid."
capi.srs_validate(self.ptr)
#### Name & SRID properties ####
@property
def name(self):
"Returns the name of this Spatial Reference."
if self.projected: return self.attr_value('PROJCS')
elif self.geographic: return self.attr_value('GEOGCS')
elif self.local: return self.attr_value('LOCAL_CS')
else: return None
@property
def srid(self):
"Returns the SRID of top-level authority, or None if undefined."
try:
return int(self.attr_value('AUTHORITY', 1))
except (TypeError, ValueError):
return None
#### Unit Properties ####
@property
def linear_name(self):
"Returns the name of the linear units."
units, name = capi.linear_units(self.ptr, byref(c_char_p()))
return name
@property
def linear_units(self):
"Returns the value of the linear units."
units, name = capi.linear_units(self.ptr, byref(c_char_p()))
return units
@property
def angular_name(self):
"Returns the name of the angular units."
units, name = capi.angular_units(self.ptr, byref(c_char_p()))
return name
@property
def angular_units(self):
"Returns the value of the angular units."
units, name = capi.angular_units(self.ptr, byref(c_char_p()))
return units
@property
def units(self):
"""
Returns a 2-tuple of the units value and the units name,
and will automatically determines whether to return the linear
or angular units.
"""
if self.projected or self.local:
return capi.linear_units(self.ptr, byref(c_char_p()))
elif self.geographic:
return capi.angular_units(self.ptr, byref(c_char_p()))
else:
return (None, None)
#### Spheroid/Ellipsoid Properties ####
@property
def ellipsoid(self):
"""
Returns a tuple of the ellipsoid parameters:
(semimajor axis, semiminor axis, and inverse flattening)
"""
return (self.semi_major, self.semi_minor, self.inverse_flattening)
@property
def semi_major(self):
"Returns the Semi Major Axis for this Spatial Reference."
return capi.semi_major(self.ptr, byref(c_int()))
@property
def semi_minor(self):
"Returns the Semi Minor Axis for this Spatial Reference."
return capi.semi_minor(self.ptr, byref(c_int()))
@property
def inverse_flattening(self):
"Returns the Inverse Flattening for this Spatial Reference."
return capi.invflattening(self.ptr, byref(c_int()))
#### Boolean Properties ####
@property
def geographic(self):
"""
Returns True if this SpatialReference is geographic
(root node is GEOGCS).
"""
return bool(capi.isgeographic(self.ptr))
@property
def local(self):
"Returns True if this SpatialReference is local (root node is LOCAL_CS)."
return bool(capi.islocal(self.ptr))
@property
def projected(self):
"""
Returns True if this SpatialReference is a projected coordinate system
(root node is PROJCS).
"""
return bool(capi.isprojected(self.ptr))
#### Import Routines #####
def import_epsg(self, epsg):
"Imports the Spatial Reference from the EPSG code (an integer)."
capi.from_epsg(self.ptr, epsg)
def import_proj(self, proj):
"Imports the Spatial Reference from a PROJ.4 string."
capi.from_proj(self.ptr, proj)
def import_user_input(self, user_input):
"Imports the Spatial Reference from the given user input string."
capi.from_user_input(self.ptr, user_input)
def import_wkt(self, wkt):
"Imports the Spatial Reference from OGC WKT (string)"
capi.from_wkt(self.ptr, byref(c_char_p(wkt)))
def import_xml(self, xml):
"Imports the Spatial Reference from an XML string."
capi.from_xml(self.ptr, xml)
#### Export Properties ####
@property
def wkt(self):
"Returns the WKT representation of this Spatial Reference."
return capi.to_wkt(self.ptr, byref(c_char_p()))
@property
def pretty_wkt(self, simplify=0):
"Returns the 'pretty' representation of the WKT."
return capi.to_pretty_wkt(self.ptr, byref(c_char_p()), simplify)
@property
def proj(self):
"Returns the PROJ.4 representation for this Spatial Reference."
return capi.to_proj(self.ptr, byref(c_char_p()))
@property
def proj4(self):
"Alias for proj()."
return self.proj
@property
def xml(self, dialect=''):
"Returns the XML representation of this Spatial Reference."
return capi.to_xml(self.ptr, byref(c_char_p()), dialect)
class CoordTransform(GDALBase):
"The coordinate system transformation object."
def __init__(self, source, target):
"Initializes on a source and target SpatialReference objects."
if not isinstance(source, SpatialReference) or not isinstance(target, SpatialReference):
raise TypeError('source and target must be of type SpatialReference')
self.ptr = capi.new_ct(source._ptr, target._ptr)
self._srs1_name = source.name
self._srs2_name = target.name
def __del__(self):
"Deletes this Coordinate Transformation object."
if self._ptr: capi.destroy_ct(self._ptr)
def __str__(self):
return 'Transform from "%s" to "%s"' % (self._srs1_name, self._srs2_name)
|
soarpenguin/ansible | refs/heads/devel | lib/ansible/plugins/callback/default.py | 25 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
'''
DOCUMENTATION:
callback: default
short_description: default Ansible screen output
version_added: historical
description:
- This is the default output callback for ansible-playbook.
'''
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import constants as C
from ansible.playbook.task_include import TaskInclude
from ansible.plugins.callback import CallbackBase
from ansible.utils.color import colorize, hostcolor
class CallbackModule(CallbackBase):
'''
This is the default callback interface, which simply prints messages
to stdout when new callback events are received.
'''
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'stdout'
CALLBACK_NAME = 'default'
def __init__(self):
self._play = None
self._last_task_banner = None
super(CallbackModule, self).__init__()
def v2_runner_on_failed(self, result, ignore_errors=False):
delegated_vars = result._result.get('_ansible_delegated_vars', None)
self._clean_results(result._result, result._task.action)
if self._play.strategy == 'free' and self._last_task_banner != result._task._uuid:
self._print_task_banner(result._task)
self._handle_exception(result._result)
self._handle_warnings(result._result)
if result._task.loop and 'results' in result._result:
self._process_items(result)
else:
if delegated_vars:
self._display.display("fatal: [%s -> %s]: FAILED! => %s" % (result._host.get_name(), delegated_vars['ansible_host'],
self._dump_results(result._result)), color=C.COLOR_ERROR)
else:
self._display.display("fatal: [%s]: FAILED! => %s" % (result._host.get_name(), self._dump_results(result._result)), color=C.COLOR_ERROR)
if ignore_errors:
self._display.display("...ignoring", color=C.COLOR_SKIP)
def v2_runner_on_ok(self, result):
delegated_vars = result._result.get('_ansible_delegated_vars', None)
self._clean_results(result._result, result._task.action)
if self._play.strategy == 'free' and self._last_task_banner != result._task._uuid:
self._print_task_banner(result._task)
if isinstance(result._task, TaskInclude):
return
elif result._result.get('changed', False):
if delegated_vars:
msg = "changed: [%s -> %s]" % (result._host.get_name(), delegated_vars['ansible_host'])
else:
msg = "changed: [%s]" % result._host.get_name()
color = C.COLOR_CHANGED
else:
if delegated_vars:
msg = "ok: [%s -> %s]" % (result._host.get_name(), delegated_vars['ansible_host'])
else:
msg = "ok: [%s]" % result._host.get_name()
color = C.COLOR_OK
self._handle_warnings(result._result)
if result._task.loop and 'results' in result._result:
self._process_items(result)
else:
if (self._display.verbosity > 0 or '_ansible_verbose_always' in result._result) and '_ansible_verbose_override' not in result._result:
msg += " => %s" % (self._dump_results(result._result),)
self._display.display(msg, color=color)
def v2_runner_on_skipped(self, result):
if C.DISPLAY_SKIPPED_HOSTS:
delegated_vars = result._result.get('_ansible_delegated_vars', None)
self._clean_results(result._result, result._task.action)
if self._play.strategy == 'free' and self._last_task_banner != result._task._uuid:
self._print_task_banner(result._task)
if result._task.loop and 'results' in result._result:
self._process_items(result)
else:
msg = "skipping: [%s]" % result._host.get_name()
if (self._display.verbosity > 0 or '_ansible_verbose_always' in result._result) and '_ansible_verbose_override' not in result._result:
msg += " => %s" % self._dump_results(result._result)
self._display.display(msg, color=C.COLOR_SKIP)
def v2_runner_on_unreachable(self, result):
if self._play.strategy == 'free' and self._last_task_banner != result._task._uuid:
self._print_task_banner(result._task)
delegated_vars = result._result.get('_ansible_delegated_vars', None)
if delegated_vars:
self._display.display("fatal: [%s -> %s]: UNREACHABLE! => %s" % (result._host.get_name(), delegated_vars['ansible_host'],
self._dump_results(result._result)),
color=C.COLOR_UNREACHABLE)
else:
self._display.display("fatal: [%s]: UNREACHABLE! => %s" % (result._host.get_name(), self._dump_results(result._result)), color=C.COLOR_UNREACHABLE)
def v2_playbook_on_no_hosts_matched(self):
self._display.display("skipping: no hosts matched", color=C.COLOR_SKIP)
def v2_playbook_on_no_hosts_remaining(self):
self._display.banner("NO MORE HOSTS LEFT")
def v2_playbook_on_task_start(self, task, is_conditional):
if self._play.strategy != 'free':
self._print_task_banner(task)
def _print_task_banner(self, task):
# args can be specified as no_log in several places: in the task or in
# the argument spec. We can check whether the task is no_log but the
# argument spec can't be because that is only run on the target
# machine and we haven't run it thereyet at this time.
#
# So we give people a config option to affect display of the args so
# that they can secure this if they feel that their stdout is insecure
# (shoulder surfing, logging stdout straight to a file, etc).
args = ''
if not task.no_log and C.DISPLAY_ARGS_TO_STDOUT:
args = u', '.join(u'%s=%s' % a for a in task.args.items())
args = u' %s' % args
self._display.banner(u"TASK [%s%s]" % (task.get_name().strip(), args))
if self._display.verbosity >= 2:
path = task.get_path()
if path:
self._display.display(u"task path: %s" % path, color=C.COLOR_DEBUG)
self._last_task_banner = task._uuid
def v2_playbook_on_cleanup_task_start(self, task):
self._display.banner("CLEANUP TASK [%s]" % task.get_name().strip())
def v2_playbook_on_handler_task_start(self, task):
self._display.banner("RUNNING HANDLER [%s]" % task.get_name().strip())
def v2_playbook_on_play_start(self, play):
name = play.get_name().strip()
if not name:
msg = u"PLAY"
else:
msg = u"PLAY [%s]" % name
self._play = play
self._display.banner(msg)
def v2_on_file_diff(self, result):
if result._task.loop and 'results' in result._result:
for res in result._result['results']:
if 'diff' in res and res['diff'] and res.get('changed', False):
diff = self._get_diff(res['diff'])
if diff:
self._display.display(diff)
elif 'diff' in result._result and result._result['diff'] and result._result.get('changed', False):
diff = self._get_diff(result._result['diff'])
if diff:
self._display.display(diff)
def v2_runner_item_on_ok(self, result):
delegated_vars = result._result.get('_ansible_delegated_vars', None)
self._clean_results(result._result, result._task.action)
if isinstance(result._task, TaskInclude):
return
elif result._result.get('changed', False):
msg = 'changed'
color = C.COLOR_CHANGED
else:
msg = 'ok'
color = C.COLOR_OK
if delegated_vars:
msg += ": [%s -> %s]" % (result._host.get_name(), delegated_vars['ansible_host'])
else:
msg += ": [%s]" % result._host.get_name()
msg += " => (item=%s)" % (self._get_item(result._result),)
if (self._display.verbosity > 0 or '_ansible_verbose_always' in result._result) and '_ansible_verbose_override' not in result._result:
msg += " => %s" % self._dump_results(result._result)
self._display.display(msg, color=color)
def v2_runner_item_on_failed(self, result):
delegated_vars = result._result.get('_ansible_delegated_vars', None)
self._clean_results(result._result, result._task.action)
self._handle_exception(result._result)
msg = "failed: "
if delegated_vars:
msg += "[%s -> %s]" % (result._host.get_name(), delegated_vars['ansible_host'])
else:
msg += "[%s]" % (result._host.get_name())
self._handle_warnings(result._result)
self._display.display(msg + " (item=%s) => %s" % (self._get_item(result._result), self._dump_results(result._result)), color=C.COLOR_ERROR)
def v2_runner_item_on_skipped(self, result):
if C.DISPLAY_SKIPPED_HOSTS:
self._clean_results(result._result, result._task.action)
msg = "skipping: [%s] => (item=%s) " % (result._host.get_name(), self._get_item(result._result))
if (self._display.verbosity > 0 or '_ansible_verbose_always' in result._result) and '_ansible_verbose_override' not in result._result:
msg += " => %s" % self._dump_results(result._result)
self._display.display(msg, color=C.COLOR_SKIP)
def v2_playbook_on_include(self, included_file):
msg = 'included: %s for %s' % (included_file._filename, ", ".join([h.name for h in included_file._hosts]))
self._display.display(msg, color=C.COLOR_SKIP)
def v2_playbook_on_stats(self, stats):
self._display.banner("PLAY RECAP")
hosts = sorted(stats.processed.keys())
for h in hosts:
t = stats.summarize(h)
self._display.display(u"%s : %s %s %s %s" % (
hostcolor(h, t),
colorize(u'ok', t['ok'], C.COLOR_OK),
colorize(u'changed', t['changed'], C.COLOR_CHANGED),
colorize(u'unreachable', t['unreachable'], C.COLOR_UNREACHABLE),
colorize(u'failed', t['failures'], C.COLOR_ERROR)),
screen_only=True
)
self._display.display(u"%s : %s %s %s %s" % (
hostcolor(h, t, False),
colorize(u'ok', t['ok'], None),
colorize(u'changed', t['changed'], None),
colorize(u'unreachable', t['unreachable'], None),
colorize(u'failed', t['failures'], None)),
log_only=True
)
self._display.display("", screen_only=True)
# print custom stats
if C.SHOW_CUSTOM_STATS and stats.custom:
self._display.banner("CUSTOM STATS: ")
# per host
# TODO: come up with 'pretty format'
for k in sorted(stats.custom.keys()):
if k == '_run':
continue
self._display.display('\t%s: %s' % (k, self._dump_results(stats.custom[k], indent=1).replace('\n', '')))
# print per run custom stats
if '_run' in stats.custom:
self._display.display("", screen_only=True)
self._display.display('\tRUN: %s' % self._dump_results(stats.custom['_run'], indent=1).replace('\n', ''))
self._display.display("", screen_only=True)
def v2_playbook_on_start(self, playbook):
if self._display.verbosity > 1:
from os.path import basename
self._display.banner("PLAYBOOK: %s" % basename(playbook._file_name))
if self._display.verbosity > 3:
if self._options is not None:
for option in dir(self._options):
if option.startswith('_') or option in ['read_file', 'ensure_value', 'read_module']:
continue
val = getattr(self._options, option)
if val:
self._display.vvvv('%s: %s' % (option, val))
def v2_runner_retry(self, result):
task_name = result.task_name or result._task
msg = "FAILED - RETRYING: %s (%d retries left)." % (task_name, result._result['retries'] - result._result['attempts'])
if (self._display.verbosity > 2 or '_ansible_verbose_always' in result._result) and '_ansible_verbose_override' not in result._result:
msg += "Result was: %s" % self._dump_results(result._result)
self._display.display(msg, color=C.COLOR_DEBUG)
|
mach0/QGIS | refs/heads/master | tests/src/python/test_qgsgeometry.py | 7 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsGeometry.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Tim Sutton'
__date__ = '20/08/2012'
__copyright__ = 'Copyright 2012, The QGIS Project'
import os
import csv
import math
from qgis.core import (
QgsGeometry,
QgsVectorLayer,
QgsFeature,
QgsPointXY,
QgsPoint,
QgsCircularString,
QgsCompoundCurve,
QgsCurvePolygon,
QgsGeometryCollection,
QgsLineString,
QgsMultiCurve,
QgsMultiLineString,
QgsMultiPoint,
QgsMultiPolygon,
QgsMultiSurface,
QgsPolygon,
QgsCoordinateTransform,
QgsRectangle,
QgsWkbTypes,
QgsTriangle,
QgsRenderChecker,
QgsCoordinateReferenceSystem,
QgsProject,
QgsVertexId,
QgsAbstractGeometryTransformer,
Qgis
)
from qgis.PyQt.QtCore import QDir, QPointF, QRectF
from qgis.PyQt.QtGui import QImage, QPainter, QPen, QColor, QBrush, QPainterPath, QPolygonF, QTransform
from qgis.testing import (
start_app,
unittest,
)
from utilities import (
compareWkt,
unitTestDataPath,
writeShape
)
# Convenience instances in case you may need them not used in this test
start_app()
TEST_DATA_DIR = unitTestDataPath()
class TestQgsGeometry(unittest.TestCase):
def setUp(self):
self.report = "<h1>Python QgsGeometry Tests</h1>\n"
self.geos39 = Qgis.geosVersionInt() >= 30900
def testBool(self):
""" Test boolean evaluation of QgsGeometry """
g = QgsGeometry()
self.assertFalse(g)
myWKT = 'Point (10 10)'
g = QgsGeometry.fromWkt(myWKT)
self.assertTrue(g)
g.set(None)
self.assertFalse(g)
def testIsEmpty(self):
"""
the bulk of these tests are in testqgsgeometry.cpp for each QgsAbstractGeometry subclass
this test just checks the QgsGeometry wrapper
"""
g = QgsGeometry()
self.assertTrue(g.isEmpty())
g = QgsGeometry.fromWkt('Point(10 10 )')
self.assertFalse(g.isEmpty())
g = QgsGeometry.fromWkt('MultiPoint ()')
self.assertTrue(g.isEmpty())
def testVertexIterator(self):
g = QgsGeometry.fromWkt('Linestring(11 12, 13 14)')
it = g.vertices()
self.assertEqual(next(it), QgsPoint(11, 12))
self.assertEqual(next(it), QgsPoint(13, 14))
with self.assertRaises(StopIteration):
next(it)
def testPartIterator(self):
g = QgsGeometry()
it = g.parts()
with self.assertRaises(StopIteration):
next(it)
with self.assertRaises(StopIteration):
next(it)
# single point geometry
g = QgsGeometry.fromWkt('Point (10 10)')
it = g.parts()
self.assertEqual(next(it).asWkt(), 'Point (10 10)')
with self.assertRaises(StopIteration):
next(it)
it = g.get().parts()
self.assertEqual(next(it).asWkt(), 'Point (10 10)')
with self.assertRaises(StopIteration):
next(it)
# multi point geometry
g = QgsGeometry.fromWkt('MultiPoint (10 10, 20 20, 10 20)')
it = g.parts()
self.assertEqual(next(it).asWkt(), 'Point (10 10)')
self.assertEqual(next(it).asWkt(), 'Point (20 20)')
self.assertEqual(next(it).asWkt(), 'Point (10 20)')
with self.assertRaises(StopIteration):
next(it)
it = g.get().parts()
self.assertEqual(next(it).asWkt(), 'Point (10 10)')
self.assertEqual(next(it).asWkt(), 'Point (20 20)')
self.assertEqual(next(it).asWkt(), 'Point (10 20)')
with self.assertRaises(StopIteration):
next(it)
# empty multi point geometry
g = QgsGeometry.fromWkt('MultiPoint ()')
it = g.parts()
with self.assertRaises(StopIteration):
next(it)
# single line geometry
g = QgsGeometry.fromWkt('LineString (10 10, 20 10, 30 10)')
it = g.parts()
self.assertEqual(next(it).asWkt(), 'LineString (10 10, 20 10, 30 10)')
with self.assertRaises(StopIteration):
next(it)
# multi line geometry
g = QgsGeometry.fromWkt('MultiLineString ((10 10, 20 20, 10 20),(5 7, 8 9))')
it = g.parts()
self.assertEqual(next(it).asWkt(), 'LineString (10 10, 20 20, 10 20)')
self.assertEqual(next(it).asWkt(), 'LineString (5 7, 8 9)')
with self.assertRaises(StopIteration):
next(it)
# empty multi line geometry
g = QgsGeometry.fromWkt('MultiLineString ()')
it = g.parts()
with self.assertRaises(StopIteration):
next(it)
# single polygon geometry
g = QgsGeometry.fromWkt('Polygon ((10 10, 100 10, 100 100, 10 100, 10 10),(50 50, 55 50, 55 55, 50 55, 50 50))')
it = g.parts()
self.assertEqual(next(it).asWkt(),
'Polygon ((10 10, 100 10, 100 100, 10 100, 10 10),(50 50, 55 50, 55 55, 50 55, 50 50))')
with self.assertRaises(StopIteration):
next(it)
# multi polygon geometry
g = QgsGeometry.fromWkt(
'MultiPolygon (((10 10, 100 10, 100 100, 10 100, 10 10),(50 50, 55 50, 55 55, 50 55, 50 50)),((20 2, 20 4, 22 4, 22 2, 20 2)))')
it = g.parts()
self.assertEqual(next(it).asWkt(),
'Polygon ((10 10, 100 10, 100 100, 10 100, 10 10),(50 50, 55 50, 55 55, 50 55, 50 50))')
self.assertEqual(next(it).asWkt(), 'Polygon ((20 2, 20 4, 22 4, 22 2, 20 2))')
with self.assertRaises(StopIteration):
next(it)
# empty multi polygon geometry
g = QgsGeometry.fromWkt('MultiPolygon ()')
it = g.parts()
with self.assertRaises(StopIteration):
next(it)
# geometry collection
g = QgsGeometry.fromWkt('GeometryCollection( Point( 1 2), LineString( 4 5, 8 7 ))')
it = g.parts()
self.assertEqual(next(it).asWkt(), 'Point (1 2)')
self.assertEqual(next(it).asWkt(), 'LineString (4 5, 8 7)')
with self.assertRaises(StopIteration):
next(it)
# empty geometry collection
g = QgsGeometry.fromWkt('GeometryCollection()')
it = g.parts()
with self.assertRaises(StopIteration):
next(it)
def testWktPointLoading(self):
myWKT = 'Point (10 10)'
myGeometry = QgsGeometry.fromWkt(myWKT)
self.assertEqual(myGeometry.wkbType(), QgsWkbTypes.Point)
def testWktMultiPointLoading(self):
# Standard format
wkt = 'MultiPoint ((10 15),(20 30))'
geom = QgsGeometry.fromWkt(wkt)
self.assertEqual(geom.wkbType(), QgsWkbTypes.MultiPoint,
('Expected:\n%s\nGot:\n%s\n' % (QgsWkbTypes.Point, geom.type())))
self.assertEqual(geom.constGet().numGeometries(), 2)
self.assertEqual(geom.constGet().geometryN(0).x(), 10)
self.assertEqual(geom.constGet().geometryN(0).y(), 15)
self.assertEqual(geom.constGet().geometryN(1).x(), 20)
self.assertEqual(geom.constGet().geometryN(1).y(), 30)
# Check MS SQL format
wkt = 'MultiPoint (11 16, 21 31)'
geom = QgsGeometry.fromWkt(wkt)
self.assertEqual(geom.wkbType(), QgsWkbTypes.MultiPoint,
('Expected:\n%s\nGot:\n%s\n' % (QgsWkbTypes.Point, geom.type())))
self.assertEqual(geom.constGet().numGeometries(), 2)
self.assertEqual(geom.constGet().geometryN(0).x(), 11)
self.assertEqual(geom.constGet().geometryN(0).y(), 16)
self.assertEqual(geom.constGet().geometryN(1).x(), 21)
self.assertEqual(geom.constGet().geometryN(1).y(), 31)
def testFromPoint(self):
myPoint = QgsGeometry.fromPointXY(QgsPointXY(10, 10))
self.assertEqual(myPoint.wkbType(), QgsWkbTypes.Point)
def testFromMultiPoint(self):
myMultiPoint = QgsGeometry.fromMultiPointXY([
(QgsPointXY(0, 0)), (QgsPointXY(1, 1))])
self.assertEqual(myMultiPoint.wkbType(), QgsWkbTypes.MultiPoint)
def testFromLine(self):
myLine = QgsGeometry.fromPolylineXY([QgsPointXY(1, 1), QgsPointXY(2, 2)])
self.assertEqual(myLine.wkbType(), QgsWkbTypes.LineString)
def testFromMultiLine(self):
myMultiPolyline = QgsGeometry.fromMultiPolylineXY(
[[QgsPointXY(0, 0), QgsPointXY(1, 1)], [QgsPointXY(0, 1), QgsPointXY(2, 1)]])
self.assertEqual(myMultiPolyline.wkbType(), QgsWkbTypes.MultiLineString)
def testFromPolygon(self):
myPolygon = QgsGeometry.fromPolygonXY(
[[QgsPointXY(1, 1), QgsPointXY(2, 2), QgsPointXY(1, 2), QgsPointXY(1, 1)]])
self.assertEqual(myPolygon.wkbType(), QgsWkbTypes.Polygon)
def testFromMultiPolygon(self):
myMultiPolygon = QgsGeometry.fromMultiPolygonXY([
[[QgsPointXY(1, 1),
QgsPointXY(2, 2),
QgsPointXY(1, 2),
QgsPointXY(1, 1)]],
[[QgsPointXY(2, 2),
QgsPointXY(3, 3),
QgsPointXY(3, 1),
QgsPointXY(2, 2)]]
])
self.assertEqual(myMultiPolygon.wkbType(), QgsWkbTypes.MultiPolygon)
def testLineStringPythonAdditions(self):
"""
Tests Python specific additions to the QgsLineString API
"""
ls = QgsLineString()
self.assertTrue(bool(ls))
self.assertEqual(len(ls), 0)
ls = QgsLineString([QgsPoint(1, 2), QgsPoint(11, 12)])
self.assertTrue(bool(ls))
self.assertEqual(len(ls), 2)
# pointN
with self.assertRaises(IndexError):
ls.pointN(-3)
with self.assertRaises(IndexError):
ls.pointN(2)
self.assertEqual(ls.pointN(0), QgsPoint(1, 2))
self.assertEqual(ls.pointN(1), QgsPoint(11, 12))
self.assertEqual(ls.pointN(-2), QgsPoint(1, 2))
self.assertEqual(ls.pointN(-1), QgsPoint(11, 12))
# xAt
with self.assertRaises(IndexError):
ls.xAt(-3)
with self.assertRaises(IndexError):
ls.xAt(2)
self.assertEqual(ls.xAt(0), 1)
self.assertEqual(ls.xAt(1), 11)
self.assertEqual(ls.xAt(-2), 1)
self.assertEqual(ls.xAt(-1), 11)
# yAt
with self.assertRaises(IndexError):
ls.yAt(-3)
with self.assertRaises(IndexError):
ls.yAt(2)
self.assertEqual(ls.yAt(0), 2)
self.assertEqual(ls.yAt(1), 12)
self.assertEqual(ls.yAt(-2), 2)
self.assertEqual(ls.yAt(-1), 12)
# zAt
with self.assertRaises(IndexError):
ls.zAt(-3)
with self.assertRaises(IndexError):
ls.zAt(2)
# mAt
with self.assertRaises(IndexError):
ls.mAt(-3)
with self.assertRaises(IndexError):
ls.mAt(2)
ls = QgsLineString([QgsPoint(1, 2, 3, 4), QgsPoint(11, 12, 13, 14)])
self.assertEqual(ls.zAt(0), 3)
self.assertEqual(ls.zAt(1), 13)
self.assertEqual(ls.zAt(-2), 3)
self.assertEqual(ls.zAt(-1), 13)
self.assertEqual(ls.mAt(0), 4)
self.assertEqual(ls.mAt(1), 14)
self.assertEqual(ls.mAt(-2), 4)
self.assertEqual(ls.mAt(-1), 14)
# setXAt
with self.assertRaises(IndexError):
ls.setXAt(-3, 55)
with self.assertRaises(IndexError):
ls.setXAt(2, 55)
ls.setXAt(0, 5)
ls.setXAt(1, 15)
self.assertEqual(ls.xAt(0), 5)
self.assertEqual(ls.xAt(1), 15)
ls.setXAt(-2, 25)
ls.setXAt(-1, 26)
self.assertEqual(ls.xAt(0), 25)
self.assertEqual(ls.xAt(1), 26)
# setYAt
with self.assertRaises(IndexError):
ls.setYAt(-3, 66)
with self.assertRaises(IndexError):
ls.setYAt(2, 66)
ls.setYAt(0, 6)
ls.setYAt(1, 16)
self.assertEqual(ls.yAt(0), 6)
self.assertEqual(ls.yAt(1), 16)
ls.setYAt(-2, 16)
ls.setYAt(-1, 22)
self.assertEqual(ls.yAt(0), 16)
self.assertEqual(ls.yAt(1), 22)
# setZAt
with self.assertRaises(IndexError):
ls.setZAt(-3, 77)
with self.assertRaises(IndexError):
ls.setZAt(2, 77)
ls.setZAt(0, 7)
ls.setZAt(1, 17)
self.assertEqual(ls.zAt(0), 7)
self.assertEqual(ls.zAt(1), 17)
ls.setZAt(-2, 37)
ls.setZAt(-1, 47)
self.assertEqual(ls.zAt(0), 37)
self.assertEqual(ls.zAt(1), 47)
# setMAt
with self.assertRaises(IndexError):
ls.setMAt(-3, 88)
with self.assertRaises(IndexError):
ls.setMAt(2, 88)
ls.setMAt(0, 8)
ls.setMAt(1, 18)
self.assertEqual(ls.mAt(0), 8)
self.assertEqual(ls.mAt(1), 18)
ls.setMAt(-2, 58)
ls.setMAt(-1, 68)
self.assertEqual(ls.mAt(0), 58)
self.assertEqual(ls.mAt(1), 68)
# get item
with self.assertRaises(IndexError):
ls[-3]
with self.assertRaises(IndexError):
ls[2]
self.assertEqual(ls[0], QgsPoint(25, 16, 37, 58))
self.assertEqual(ls[1], QgsPoint(26, 22, 47, 68))
self.assertEqual(ls[-2], QgsPoint(25, 16, 37, 58))
self.assertEqual(ls[-1], QgsPoint(26, 22, 47, 68))
# set item
with self.assertRaises(IndexError):
ls[-3] = QgsPoint(33, 34)
with self.assertRaises(IndexError):
ls[2] = QgsPoint(33, 34)
ls[0] = QgsPoint(33, 34, 35, 36)
ls[1] = QgsPoint(43, 44, 45, 46)
self.assertEqual(ls[0], QgsPoint(33, 34, 35, 36))
self.assertEqual(ls[1], QgsPoint(43, 44, 45, 46))
ls[-2] = QgsPoint(133, 134, 135, 136)
ls[-1] = QgsPoint(143, 144, 145, 146)
self.assertEqual(ls[0], QgsPoint(133, 134, 135, 136))
self.assertEqual(ls[1], QgsPoint(143, 144, 145, 146))
# set item, z/m handling
ls[0] = QgsPoint(66, 67)
self.assertEqual(ls[0], QgsPoint(66, 67, None, None, QgsWkbTypes.PointZM))
ls[0] = QgsPoint(77, 78, 79)
self.assertEqual(ls[0], QgsPoint(77, 78, 79, None, QgsWkbTypes.PointZM))
ls[0] = QgsPoint(77, 78, None, 80, QgsWkbTypes.PointZM)
self.assertEqual(ls[0], QgsPoint(77, 78, None, 80, QgsWkbTypes.PointZM))
ls = QgsLineString([QgsPoint(1, 2), QgsPoint(11, 12)])
ls[0] = QgsPoint(66, 67)
self.assertEqual(ls[0], QgsPoint(66, 67))
ls[0] = QgsPoint(86, 87, 89, 90)
self.assertEqual(ls[0], QgsPoint(86, 87))
# del item
ls = QgsLineString([QgsPoint(1, 2), QgsPoint(11, 12), QgsPoint(33, 34)])
with self.assertRaises(IndexError):
del ls[-4]
with self.assertRaises(IndexError):
del ls[3]
del ls[1]
self.assertEqual(len(ls), 2)
self.assertEqual(ls[0], QgsPoint(1, 2))
self.assertEqual(ls[1], QgsPoint(33, 34))
with self.assertRaises(IndexError):
del ls[2]
ls = QgsLineString([QgsPoint(1, 2), QgsPoint(11, 12), QgsPoint(33, 34)])
del ls[-3]
self.assertEqual(len(ls), 2)
self.assertEqual(ls[0], QgsPoint(11, 12))
self.assertEqual(ls[1], QgsPoint(33, 34))
with self.assertRaises(IndexError):
del ls[-3]
def testQgsLineStringPythonConstructors(self):
"""
Test various constructors for QgsLineString in Python
"""
line = QgsLineString()
self.assertEqual(line.asWkt(), 'LineString EMPTY')
# empty array
line = QgsLineString([])
self.assertEqual(line.asWkt(), 'LineString EMPTY')
# invalid array
with self.assertRaises(TypeError):
line = QgsLineString([1, 2, 3])
# array of QgsPoint
line = QgsLineString([QgsPoint(1, 2), QgsPoint(3, 4), QgsPoint(11, 12)])
self.assertEqual(line.asWkt(), 'LineString (1 2, 3 4, 11 12)')
# array of QgsPoint with Z
line = QgsLineString([QgsPoint(1, 2, 11), QgsPoint(3, 4, 13), QgsPoint(11, 12, 14)])
self.assertEqual(line.asWkt(), 'LineStringZ (1 2 11, 3 4 13, 11 12 14)')
# array of QgsPoint with Z, only first has z
line = QgsLineString([QgsPoint(1, 2, 11), QgsPoint(3, 4), QgsPoint(11, 12)])
self.assertEqual(line.asWkt(), 'LineStringZ (1 2 11, 3 4 nan, 11 12 nan)')
# array of QgsPoint with M
line = QgsLineString([QgsPoint(1, 2, None, 11), QgsPoint(3, 4, None, 13), QgsPoint(11, 12, None, 14)])
self.assertEqual(line.asWkt(), 'LineStringM (1 2 11, 3 4 13, 11 12 14)')
# array of QgsPoint with M, only first has M
line = QgsLineString([QgsPoint(1, 2, None, 11), QgsPoint(3, 4), QgsPoint(11, 12)])
self.assertEqual(line.asWkt(), 'LineStringM (1 2 11, 3 4 nan, 11 12 nan)')
# array of QgsPoint with ZM
line = QgsLineString([QgsPoint(1, 2, 22, 11), QgsPoint(3, 4, 23, 13), QgsPoint(11, 12, 24, 14)])
self.assertEqual(line.asWkt(), 'LineStringZM (1 2 22 11, 3 4 23 13, 11 12 24 14)')
# array of QgsPoint with ZM, only first has ZM
line = QgsLineString([QgsPoint(1, 2, 33, 11), QgsPoint(3, 4), QgsPoint(11, 12)])
self.assertEqual(line.asWkt(), 'LineStringZM (1 2 33 11, 3 4 nan nan, 11 12 nan nan)')
# array of QgsPointXY
line = QgsLineString([QgsPointXY(1, 2), QgsPointXY(3, 4), QgsPointXY(11, 12)])
self.assertEqual(line.asWkt(), 'LineString (1 2, 3 4, 11 12)')
# array of array of bad values
with self.assertRaises(TypeError):
line = QgsLineString([[QgsPolygon(), QgsPoint()]])
with self.assertRaises(TypeError):
line = QgsLineString([[1, 2], [QgsPolygon(), QgsPoint()]])
# array of array of 1d floats
with self.assertRaises(TypeError):
line = QgsLineString([[1], [3], [5]])
# array of array of floats
line = QgsLineString([[1, 2], [3, 4], [5, 6]])
self.assertEqual(line.asWkt(), 'LineString (1 2, 3 4, 5 6)')
# tuple of tuple of floats
line = QgsLineString(((1, 2), (3, 4), (5, 6)))
self.assertEqual(line.asWkt(), 'LineString (1 2, 3 4, 5 6)')
# sequence
line = QgsLineString([[c + 10, c + 11] for c in range(5)])
self.assertEqual(line.asWkt(), 'LineString (10 11, 11 12, 12 13, 13 14, 14 15)')
# array of array of 3d floats
line = QgsLineString([[1, 2, 11], [3, 4, 12], [5, 6, 13]])
self.assertEqual(line.asWkt(), 'LineStringZ (1 2 11, 3 4 12, 5 6 13)')
# array of array of inconsistent 3d floats
line = QgsLineString([[1, 2, 11], [3, 4], [5, 6]])
self.assertEqual(line.asWkt(), 'LineStringZ (1 2 11, 3 4 nan, 5 6 nan)')
# array of array of 4d floats
line = QgsLineString([[1, 2, 11, 21], [3, 4, 12, 22], [5, 6, 13, 23]])
self.assertEqual(line.asWkt(), 'LineStringZM (1 2 11 21, 3 4 12 22, 5 6 13 23)')
# array of array of inconsistent 4d floats
line = QgsLineString([[1, 2, 11, 21], [3, 4, 12], [5, 6]])
self.assertEqual(line.asWkt(), 'LineStringZM (1 2 11 21, 3 4 12 nan, 5 6 nan nan)')
# array of array of 5 floats
with self.assertRaises(TypeError):
line = QgsLineString([[1, 2, 11, 21, 22], [3, 4, 12, 22, 23], [5, 6, 13, 23, 24]])
# mixed array, because hey, why not?? :D
line = QgsLineString([QgsPoint(1, 2), QgsPointXY(3, 4), [5, 6], (7, 8)])
self.assertEqual(line.asWkt(), 'LineString (1 2, 3 4, 5 6, 7 8)')
def testGeometryCollectionPythonAdditions(self):
"""
Tests Python specific additions to the QgsGeometryCollection API
"""
g = QgsGeometryCollection()
self.assertTrue(bool(g))
self.assertEqual(len(g), 0)
g = QgsMultiPoint()
g.fromWkt('MultiPoint( (1 2), (11 12))')
self.assertTrue(bool(g))
self.assertEqual(len(g), 2)
# geometryN
with self.assertRaises(IndexError):
g.geometryN(-1)
with self.assertRaises(IndexError):
g.geometryN(2)
self.assertEqual(g.geometryN(0), QgsPoint(1, 2))
self.assertEqual(g.geometryN(1), QgsPoint(11, 12))
# pointN
with self.assertRaises(IndexError):
g.pointN(-1)
with self.assertRaises(IndexError):
g.pointN(2)
self.assertEqual(g.pointN(0), QgsPoint(1, 2))
self.assertEqual(g.pointN(1), QgsPoint(11, 12))
# removeGeometry
g = QgsGeometryCollection()
g.fromWkt('GeometryCollection( Point(1 2), Point(11 12), Point(33 34))')
with self.assertRaises(IndexError):
g.removeGeometry(-1)
with self.assertRaises(IndexError):
g.removeGeometry(3)
g.removeGeometry(1)
self.assertEqual(len(g), 2)
self.assertEqual(g.geometryN(0), QgsPoint(1, 2))
self.assertEqual(g.geometryN(1), QgsPoint(33, 34))
with self.assertRaises(IndexError):
g.removeGeometry(2)
g.fromWkt('GeometryCollection( Point(25 16 37 58), Point(26 22 47 68))')
# get item
with self.assertRaises(IndexError):
g[-3]
with self.assertRaises(IndexError):
g[2]
self.assertEqual(g[0], QgsPoint(25, 16, 37, 58))
self.assertEqual(g[1], QgsPoint(26, 22, 47, 68))
self.assertEqual(g[-2], QgsPoint(25, 16, 37, 58))
self.assertEqual(g[-1], QgsPoint(26, 22, 47, 68))
# del item
g.fromWkt('GeometryCollection( Point(1 2), Point(11 12), Point(33 34))')
with self.assertRaises(IndexError):
del g[-4]
with self.assertRaises(IndexError):
del g[3]
del g[1]
self.assertEqual(len(g), 2)
self.assertEqual(g[0], QgsPoint(1, 2))
self.assertEqual(g[1], QgsPoint(33, 34))
with self.assertRaises(IndexError):
del g[2]
g.fromWkt('GeometryCollection( Point(1 2), Point(11 12), Point(33 34))')
del g[-3]
self.assertEqual(len(g), 2)
self.assertEqual(g[0], QgsPoint(11, 12))
self.assertEqual(g[1], QgsPoint(33, 34))
with self.assertRaises(IndexError):
del g[-3]
# iteration
g = QgsGeometryCollection()
self.assertFalse([p for p in g])
g.fromWkt('GeometryCollection( Point(1 2), Point(11 12), LineString(33 34, 44 45))')
self.assertEqual([p.asWkt() for p in g], ['Point (1 2)', 'Point (11 12)', 'LineString (33 34, 44 45)'])
g = QgsGeometryCollection()
g.fromWkt('GeometryCollection( Point(1 2), Point(11 12))')
self.assertTrue(bool(g))
self.assertEqual(len(g), 2)
# lineStringN
g = QgsMultiLineString()
g.fromWkt('MultiLineString( (1 2, 3 4), (11 12, 13 14))')
with self.assertRaises(IndexError):
g.lineStringN(-1)
with self.assertRaises(IndexError):
g.lineStringN(2)
self.assertEqual(g.lineStringN(0).asWkt(), 'LineString (1 2, 3 4)')
self.assertEqual(g.lineStringN(1).asWkt(), 'LineString (11 12, 13 14)')
# curveN
g = QgsMultiCurve()
g.fromWkt('MultiCurve( LineString(1 2, 3 4), LineString(11 12, 13 14))')
with self.assertRaises(IndexError):
g.curveN(-1)
with self.assertRaises(IndexError):
g.curveN(2)
self.assertEqual(g.curveN(0).asWkt(), 'LineString (1 2, 3 4)')
self.assertEqual(g.curveN(1).asWkt(), 'LineString (11 12, 13 14)')
# polygonN
g = QgsMultiPolygon()
g.fromWkt('MultiPolygon( ((1 2, 3 4, 3 6, 1 2)), ((11 12, 13 14, 13 16, 11 12)))')
with self.assertRaises(IndexError):
g.polygonN(-1)
with self.assertRaises(IndexError):
g.polygonN(2)
self.assertEqual(g.polygonN(0).asWkt(), 'Polygon ((1 2, 3 4, 3 6, 1 2))')
self.assertEqual(g.polygonN(1).asWkt(), 'Polygon ((11 12, 13 14, 13 16, 11 12))')
# surfaceN
g = QgsMultiSurface()
g.fromWkt('MultiSurface( Polygon((1 2, 3 4, 3 6, 1 2)), Polygon((11 12, 13 14, 13 16, 11 12)))')
with self.assertRaises(IndexError):
g.surfaceN(-1)
with self.assertRaises(IndexError):
g.surfaceN(2)
self.assertEqual(g.surfaceN(0).asWkt(), 'Polygon ((1 2, 3 4, 3 6, 1 2))')
self.assertEqual(g.surfaceN(1).asWkt(), 'Polygon ((11 12, 13 14, 13 16, 11 12))')
def testCurvePolygonPythonAdditions(self):
"""
Tests Python specific additions to the QgsCurvePolygon API
"""
# interiorRing
g = QgsPolygon()
with self.assertRaises(IndexError):
g.interiorRing(-1)
with self.assertRaises(IndexError):
g.interiorRing(0)
g.fromWkt(
'Polygon((0 0, 1 0, 1 1, 0 0),(0.1 0.1, 0.2 0.1, 0.2 0.2, 0.1 0.1),(0.8 0.8, 0.9 0.8, 0.9 0.9, 0.8 0.8))')
with self.assertRaises(IndexError):
g.interiorRing(-1)
with self.assertRaises(IndexError):
g.interiorRing(2)
self.assertEqual(g.interiorRing(0).asWkt(1), 'LineString (0.1 0.1, 0.2 0.1, 0.2 0.2, 0.1 0.1)')
self.assertEqual(g.interiorRing(1).asWkt(1), 'LineString (0.8 0.8, 0.9 0.8, 0.9 0.9, 0.8 0.8)')
# removeInteriorRing
g = QgsPolygon()
with self.assertRaises(IndexError):
g.removeInteriorRing(-1)
with self.assertRaises(IndexError):
g.removeInteriorRing(0)
g.fromWkt(
'Polygon((0 0, 1 0, 1 1, 0 0),(0.1 0.1, 0.2 0.1, 0.2 0.2, 0.1 0.1),(0.8 0.8, 0.9 0.8, 0.9 0.9, 0.8 0.8))')
with self.assertRaises(IndexError):
g.removeInteriorRing(-1)
with self.assertRaises(IndexError):
g.removeInteriorRing(2)
g.removeInteriorRing(1)
self.assertEqual(g.asWkt(1), 'Polygon ((0 0, 1 0, 1 1, 0 0),(0.1 0.1, 0.2 0.1, 0.2 0.2, 0.1 0.1))')
with self.assertRaises(IndexError):
g.removeInteriorRing(1)
g.removeInteriorRing(0)
self.assertEqual(g.asWkt(1), 'Polygon ((0 0, 1 0, 1 1, 0 0))')
with self.assertRaises(IndexError):
g.removeInteriorRing(0)
def testPointXY(self):
"""
Test the QgsPointXY conversion methods
"""
self.assertEqual(QgsGeometry.fromWkt('Point(11 13)').asPoint(), QgsPointXY(11, 13))
self.assertEqual(QgsGeometry.fromWkt('PointZ(11 13 14)').asPoint(), QgsPointXY(11, 13))
self.assertEqual(QgsGeometry.fromWkt('PointM(11 13 14)').asPoint(), QgsPointXY(11, 13))
self.assertEqual(QgsGeometry.fromWkt('PointZM(11 13 14 15)').asPoint(), QgsPointXY(11, 13))
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('MultiPoint(11 13,14 15)').asPoint()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('LineString(11 13,14 15)').asPoint()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('Polygon((11 13,14 15, 14 13, 11 13))').asPoint()
with self.assertRaises(ValueError):
QgsGeometry().asPoint()
# as polyline
self.assertEqual(QgsGeometry.fromWkt('LineString(11 13,14 15)').asPolyline(),
[QgsPointXY(11, 13), QgsPointXY(14, 15)])
self.assertEqual(QgsGeometry.fromWkt('LineStringZ(11 13 1,14 15 2)').asPolyline(),
[QgsPointXY(11, 13), QgsPointXY(14, 15)])
self.assertEqual(QgsGeometry.fromWkt('LineStringM(11 13 1,14 15 2)').asPolyline(),
[QgsPointXY(11, 13), QgsPointXY(14, 15)])
self.assertEqual(QgsGeometry.fromWkt('LineStringZM(11 13 1 2,14 15 3 4)').asPolyline(),
[QgsPointXY(11, 13), QgsPointXY(14, 15)])
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('Point(11 13)').asPolyline()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('MultiPoint(11 13,14 15)').asPolyline()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('MultiLineString((11 13, 14 15),(1 2, 3 4))').asPolyline()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('Polygon((11 13,14 15, 14 13, 11 13))').asPolyline()
with self.assertRaises(ValueError):
QgsGeometry().asPolyline()
# as polygon
self.assertEqual(QgsGeometry.fromWkt('Polygon((11 13,14 15, 11 15, 11 13))').asPolygon(),
[[QgsPointXY(11, 13), QgsPointXY(14, 15), QgsPointXY(11, 15), QgsPointXY(11, 13)]])
self.assertEqual(QgsGeometry.fromWkt('PolygonZ((11 13 1,14 15 2, 11 15 3, 11 13 1))').asPolygon(),
[[QgsPointXY(11, 13), QgsPointXY(14, 15), QgsPointXY(11, 15), QgsPointXY(11, 13)]])
self.assertEqual(QgsGeometry.fromWkt('PolygonM((11 13 1,14 15 2, 11 15 3, 11 13 1))').asPolygon(),
[[QgsPointXY(11, 13), QgsPointXY(14, 15), QgsPointXY(11, 15), QgsPointXY(11, 13)]])
self.assertEqual(
QgsGeometry.fromWkt('PolygonZM((11 13 1 11,14 15 2 12 , 11 15 3 13 , 11 13 1 11))').asPolygon(),
[[QgsPointXY(11, 13), QgsPointXY(14, 15), QgsPointXY(11, 15), QgsPointXY(11, 13)]])
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('Point(11 13)').asPolygon()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('MultiPoint(11 13,14 15)').asPolygon()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('MultiLineString((11 13, 14 15),(1 2, 3 4))').asPolygon()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('LineString(11 13,14 15)').asPolygon()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('MultiPolygon(((11 13,14 15, 11 15, 11 13)))').asPolygon()
with self.assertRaises(ValueError):
QgsGeometry().asPolygon()
# as multipoint
self.assertEqual(QgsGeometry.fromWkt('MultiPoint(11 13,14 15)').asMultiPoint(),
[QgsPointXY(11, 13), QgsPointXY(14, 15)])
self.assertEqual(QgsGeometry.fromWkt('MultiPointZ(11 13 1,14 15 2)').asMultiPoint(),
[QgsPointXY(11, 13), QgsPointXY(14, 15)])
self.assertEqual(QgsGeometry.fromWkt('MultiPointM(11 13 1,14 15 2)').asMultiPoint(),
[QgsPointXY(11, 13), QgsPointXY(14, 15)])
self.assertEqual(QgsGeometry.fromWkt('MultiPointZM(11 13 1 2,14 15 3 4)').asMultiPoint(),
[QgsPointXY(11, 13), QgsPointXY(14, 15)])
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('Point(11 13)').asMultiPoint()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('LineString(11 13,14 15)').asMultiPoint()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('MultiLineString((11 13, 14 15),(1 2, 3 4))').asMultiPoint()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('Polygon((11 13,14 15, 14 13, 11 13))').asMultiPoint()
with self.assertRaises(ValueError):
QgsGeometry().asMultiPoint()
# as multilinestring
self.assertEqual(QgsGeometry.fromWkt('MultiLineString((11 13,14 15, 11 15, 11 13))').asMultiPolyline(),
[[QgsPointXY(11, 13), QgsPointXY(14, 15), QgsPointXY(11, 15), QgsPointXY(11, 13)]])
self.assertEqual(QgsGeometry.fromWkt('MultiLineStringZ((11 13 1,14 15 2, 11 15 3, 11 13 1))').asMultiPolyline(),
[[QgsPointXY(11, 13), QgsPointXY(14, 15), QgsPointXY(11, 15), QgsPointXY(11, 13)]])
self.assertEqual(QgsGeometry.fromWkt('MultiLineStringM((11 13 1,14 15 2, 11 15 3, 11 13 1))').asMultiPolyline(),
[[QgsPointXY(11, 13), QgsPointXY(14, 15), QgsPointXY(11, 15), QgsPointXY(11, 13)]])
self.assertEqual(QgsGeometry.fromWkt(
'MultiLineStringZM((11 13 1 11,14 15 2 12 , 11 15 3 13 , 11 13 1 11))').asMultiPolyline(),
[[QgsPointXY(11, 13), QgsPointXY(14, 15), QgsPointXY(11, 15), QgsPointXY(11, 13)]])
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('Point(11 13)').asMultiPolyline()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('MultiPoint(11 13,14 15)').asMultiPolyline()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('Polygon((11 13, 14 15, 17 18, 11 13))').asMultiPolyline()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('LineString(11 13,14 15)').asPolygon()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('MultiPolygon(((11 13,14 15, 11 15, 11 13)))').asMultiPolyline()
with self.assertRaises(ValueError):
QgsGeometry().asPolygon()
# as multipolygon
self.assertEqual(QgsGeometry.fromWkt('MultiPolygon(((11 13,14 15, 11 15, 11 13)))').asMultiPolygon(),
[[[QgsPointXY(11, 13), QgsPointXY(14, 15), QgsPointXY(11, 15), QgsPointXY(11, 13)]]])
self.assertEqual(
QgsGeometry.fromWkt('MultiPolygonZ(((11 13 1,14 15 2, 11 15 3 , 11 13 1)))').asMultiPolygon(),
[[[QgsPointXY(11, 13), QgsPointXY(14, 15), QgsPointXY(11, 15), QgsPointXY(11, 13)]]])
self.assertEqual(
QgsGeometry.fromWkt('MultiPolygonM(((11 13 1,14 15 2, 11 15 3 , 11 13 1)))').asMultiPolygon(),
[[[QgsPointXY(11, 13), QgsPointXY(14, 15), QgsPointXY(11, 15), QgsPointXY(11, 13)]]])
self.assertEqual(QgsGeometry.fromWkt(
'MultiPolygonZM(((11 13 1 11,14 15 2 12, 11 15 3 13, 11 13 1 11)))').asMultiPolygon(),
[[[QgsPointXY(11, 13), QgsPointXY(14, 15), QgsPointXY(11, 15), QgsPointXY(11, 13)]]])
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('Point(11 13)').asMultiPolygon()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('MultiPoint(11 13,14 15)').asMultiPolygon()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('Polygon((11 13, 14 15, 17 18, 11 13))').asMultiPolygon()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('LineString(11 13,14 15)').asPolygon()
with self.assertRaises(TypeError):
QgsGeometry.fromWkt('MultiLineString((11 13,14 15, 11 15, 11 13))').asMultiPolygon()
with self.assertRaises(ValueError):
QgsGeometry().asPolygon()
def testReferenceGeometry(self):
""" Test parsing a whole range of valid reference wkt formats and variants, and checking
expected values such as length, area, centroids, bounding boxes, etc of the resultant geometry.
Note the bulk of this test data was taken from the PostGIS WKT test data """
with open(os.path.join(TEST_DATA_DIR, 'geom_data.csv'), 'r') as f:
reader = csv.DictReader(f)
for i, row in enumerate(reader):
# test that geometry can be created from WKT
geom = QgsGeometry.fromWkt(row['wkt'])
if row['valid_wkt']:
assert geom, "WKT conversion {} failed: could not create geom:\n{}\n".format(i + 1, row['wkt'])
else:
assert not geom, "Corrupt WKT {} was incorrectly converted to geometry:\n{}\n".format(i + 1,
row['wkt'])
continue
# test exporting to WKT results in expected string
result = geom.asWkt()
exp = row['valid_wkt']
assert compareWkt(result, exp,
0.000001), "WKT conversion {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp,
result)
# test num points in geometry
exp_nodes = int(row['num_points'])
self.assertEqual(geom.constGet().nCoordinates(), exp_nodes,
"Node count {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp_nodes,
geom.constGet().nCoordinates()))
# test num geometries in collections
exp_geometries = int(row['num_geometries'])
try:
self.assertEqual(geom.constGet().numGeometries(), exp_geometries,
"Geometry count {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1,
exp_geometries,
geom.constGet().numGeometries()))
except:
# some geometry types don't have numGeometries()
assert exp_geometries <= 1, "Geometry count {}: Expected:\n{} geometries but could not call numGeometries()\n".format(
i + 1, exp_geometries)
# test count of rings
exp_rings = int(row['num_rings'])
try:
self.assertEqual(geom.constGet().numInteriorRings(), exp_rings,
"Ring count {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp_rings,
geom.constGet().numInteriorRings()))
except:
# some geometry types don't have numInteriorRings()
assert exp_rings <= 1, "Ring count {}: Expected:\n{} rings but could not call numInteriorRings()\n{}".format(
i + 1, exp_rings, geom.constGet())
# test isClosed
exp = (row['is_closed'] == '1')
try:
self.assertEqual(geom.constGet().isClosed(), exp,
"isClosed {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, True,
geom.constGet().isClosed()))
except:
# some geometry types don't have isClosed()
assert not exp, "isClosed {}: Expected:\n isClosed() but could not call isClosed()\n".format(i + 1)
# test geometry centroid
exp = row['centroid']
result = geom.centroid().asWkt()
assert compareWkt(result, exp, 0.00001), "Centroid {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1,
exp,
result)
# test bounding box limits
bbox = geom.constGet().boundingBox()
exp = float(row['x_min'])
result = bbox.xMinimum()
self.assertAlmostEqual(result, exp, 5,
"Min X {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result))
exp = float(row['y_min'])
result = bbox.yMinimum()
self.assertAlmostEqual(result, exp, 5,
"Min Y {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result))
exp = float(row['x_max'])
result = bbox.xMaximum()
self.assertAlmostEqual(result, exp, 5,
"Max X {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result))
exp = float(row['y_max'])
result = bbox.yMaximum()
self.assertAlmostEqual(result, exp, 5,
"Max Y {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result))
# test area calculation
exp = float(row['area'])
result = geom.constGet().area()
self.assertAlmostEqual(result, exp, 5,
"Area {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result))
# test length calculation
exp = float(row['length'])
result = geom.constGet().length()
self.assertAlmostEqual(result, exp, 5,
"Length {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result))
# test perimeter calculation
exp = float(row['perimeter'])
result = geom.constGet().perimeter()
self.assertAlmostEqual(result, exp, 5,
"Perimeter {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result))
def testCollection(self):
g = QgsGeometry.fromWkt('MultiLineString EMPTY')
self.assertEqual(len(g.get()), 0)
self.assertTrue(g.get())
g = QgsGeometry.fromWkt('MultiLineString((0 0, 1 1),(13 2, 14 1))')
self.assertEqual(len(g.get()), 2)
self.assertTrue(g.get())
self.assertEqual(g.get().geometryN(0).asWkt(), 'LineString (0 0, 1 1)')
self.assertEqual(g.get().geometryN(1).asWkt(), 'LineString (13 2, 14 1)')
with self.assertRaises(IndexError):
g.get().geometryN(-1)
with self.assertRaises(IndexError):
g.get().geometryN(2)
def testIntersection(self):
myLine = QgsGeometry.fromPolylineXY([
QgsPointXY(0, 0),
QgsPointXY(1, 1),
QgsPointXY(2, 2)])
myPoint = QgsGeometry.fromPointXY(QgsPointXY(1, 1))
intersectionGeom = QgsGeometry.intersection(myLine, myPoint)
self.assertEqual(intersectionGeom.wkbType(), QgsWkbTypes.Point)
layer = QgsVectorLayer("Point", "intersection", "memory")
assert layer.isValid(), "Failed to create valid point memory layer"
provider = layer.dataProvider()
ft = QgsFeature()
ft.setGeometry(intersectionGeom)
provider.addFeatures([ft])
self.assertEqual(layer.featureCount(), 1)
def testBuffer(self):
myPoint = QgsGeometry.fromPointXY(QgsPointXY(1, 1))
bufferGeom = myPoint.buffer(10, 5)
self.assertEqual(bufferGeom.wkbType(), QgsWkbTypes.Polygon)
myTestPoint = QgsGeometry.fromPointXY(QgsPointXY(3, 3))
self.assertTrue(bufferGeom.intersects(myTestPoint))
def testContains(self):
myPoly = QgsGeometry.fromPolygonXY(
[[QgsPointXY(0, 0),
QgsPointXY(2, 0),
QgsPointXY(2, 2),
QgsPointXY(0, 2),
QgsPointXY(0, 0)]])
myPoint = QgsGeometry.fromPointXY(QgsPointXY(1, 1))
self.assertTrue(QgsGeometry.contains(myPoly, myPoint))
def testTouches(self):
myLine = QgsGeometry.fromPolylineXY([
QgsPointXY(0, 0),
QgsPointXY(1, 1),
QgsPointXY(2, 2)])
myPoly = QgsGeometry.fromPolygonXY([[
QgsPointXY(0, 0),
QgsPointXY(1, 1),
QgsPointXY(2, 0),
QgsPointXY(0, 0)]])
touchesGeom = QgsGeometry.touches(myLine, myPoly)
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
("True", touchesGeom))
assert touchesGeom, myMessage
def testOverlaps(self):
myPolyA = QgsGeometry.fromPolygonXY([[
QgsPointXY(0, 0),
QgsPointXY(1, 3),
QgsPointXY(2, 0),
QgsPointXY(0, 0)]])
myPolyB = QgsGeometry.fromPolygonXY([[
QgsPointXY(0, 0),
QgsPointXY(2, 0),
QgsPointXY(2, 2),
QgsPointXY(0, 2),
QgsPointXY(0, 0)]])
overlapsGeom = QgsGeometry.overlaps(myPolyA, myPolyB)
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
("True", overlapsGeom))
assert overlapsGeom, myMessage
def testWithin(self):
myLine = QgsGeometry.fromPolylineXY([
QgsPointXY(0.5, 0.5),
QgsPointXY(1, 1),
QgsPointXY(1.5, 1.5)
])
myPoly = QgsGeometry.fromPolygonXY([[
QgsPointXY(0, 0),
QgsPointXY(2, 0),
QgsPointXY(2, 2),
QgsPointXY(0, 2),
QgsPointXY(0, 0)]])
withinGeom = QgsGeometry.within(myLine, myPoly)
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
("True", withinGeom))
assert withinGeom, myMessage
def testEquals(self):
myPointA = QgsGeometry.fromPointXY(QgsPointXY(1, 1))
myPointB = QgsGeometry.fromPointXY(QgsPointXY(1, 1))
equalsGeom = QgsGeometry.equals(myPointA, myPointB)
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
("True", equalsGeom))
assert equalsGeom, myMessage
def testCrosses(self):
myLine = QgsGeometry.fromPolylineXY([
QgsPointXY(0, 0),
QgsPointXY(1, 1),
QgsPointXY(3, 3)])
myPoly = QgsGeometry.fromPolygonXY([[
QgsPointXY(1, 0),
QgsPointXY(2, 0),
QgsPointXY(2, 2),
QgsPointXY(1, 2),
QgsPointXY(1, 0)]])
crossesGeom = QgsGeometry.crosses(myLine, myPoly)
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
("True", crossesGeom))
assert crossesGeom, myMessage
def testSimplifyIssue4189(self):
"""Test we can simplify a complex geometry.
Note: there is a ticket related to this issue here:
https://github.com/qgis/QGIS/issues/14164
Backstory: Ole Nielson pointed out an issue to me
(Tim Sutton) where simplify ftools was dropping
features. This test replicates that issues.
Interestingly we could replicate the issue in PostGIS too:
- doing straight simplify returned no feature
- transforming to UTM49, then simplify with e.g. 200 threshold is OK
- as above with 500 threshold drops the feature
pgsql2shp -f /tmp/dissolve500.shp gis 'select *,
transform(simplify(transform(geom,32649),500), 4326) as
simplegeom from dissolve;'
"""
with open(os.path.join(unitTestDataPath('wkt'), 'simplify_error.wkt'), 'rt') as myWKTFile:
myWKT = myWKTFile.readline()
# print myWKT
myGeometry = QgsGeometry().fromWkt(myWKT)
assert myGeometry is not None
myStartLength = len(myWKT)
myTolerance = 0.00001
mySimpleGeometry = myGeometry.simplify(myTolerance)
myEndLength = len(mySimpleGeometry.asWkt())
myMessage = 'Before simplify: %i\nAfter simplify: %i\n : Tolerance %e' % (
myStartLength, myEndLength, myTolerance)
myMinimumLength = len('Polygon(())')
assert myEndLength > myMinimumLength, myMessage
def testClipping(self):
"""Test that we can clip geometries using other geometries."""
myMemoryLayer = QgsVectorLayer(
('LineString?crs=epsg:4326&field=name:string(20)&index=yes'),
'clip-in',
'memory')
assert myMemoryLayer is not None, 'Provider not initialized'
myProvider = myMemoryLayer.dataProvider()
assert myProvider is not None
myFeature1 = QgsFeature()
myFeature1.setGeometry(QgsGeometry.fromPolylineXY([
QgsPointXY(10, 10),
QgsPointXY(20, 10),
QgsPointXY(30, 10),
QgsPointXY(40, 10),
]))
myFeature1.setAttributes(['Johny'])
myFeature2 = QgsFeature()
myFeature2.setGeometry(QgsGeometry.fromPolylineXY([
QgsPointXY(10, 10),
QgsPointXY(20, 20),
QgsPointXY(30, 30),
QgsPointXY(40, 40),
]))
myFeature2.setAttributes(['Be'])
myFeature3 = QgsFeature()
myFeature3.setGeometry(QgsGeometry.fromPolylineXY([
QgsPointXY(10, 10),
QgsPointXY(10, 20),
QgsPointXY(10, 30),
QgsPointXY(10, 40),
]))
myFeature3.setAttributes(['Good'])
myResult, myFeatures = myProvider.addFeatures(
[myFeature1, myFeature2, myFeature3])
assert myResult
self.assertEqual(len(myFeatures), 3)
myClipPolygon = QgsGeometry.fromPolygonXY([[
QgsPointXY(20, 20),
QgsPointXY(20, 30),
QgsPointXY(30, 30),
QgsPointXY(30, 20),
QgsPointXY(20, 20),
]])
print(('Clip: %s' % myClipPolygon.asWkt()))
writeShape(myMemoryLayer, 'clipGeometryBefore.shp')
fit = myProvider.getFeatures()
myFeatures = []
myFeature = QgsFeature()
while fit.nextFeature(myFeature):
myGeometry = myFeature.geometry()
if myGeometry.intersects(myClipPolygon):
# Adds nodes where the clip and the line intersec
myCombinedGeometry = myGeometry.combine(myClipPolygon)
# Gives you the areas inside the clip
mySymmetricalGeometry = myGeometry.symDifference(
myCombinedGeometry)
# Gives you areas outside the clip area
# myDifferenceGeometry = myCombinedGeometry.difference(
# myClipPolygon)
# print 'Original: %s' % myGeometry.asWkt()
# print 'Combined: %s' % myCombinedGeometry.asWkt()
# print 'Difference: %s' % myDifferenceGeometry.asWkt()
print(('Symmetrical: %s' % mySymmetricalGeometry.asWkt()))
if self.geos39:
myExpectedWkt = 'Polygon ((20 30, 30 30, 30 20, 20 20, 20 30))'
else:
myExpectedWkt = 'Polygon ((20 20, 20 30, 30 30, 30 20, 20 20))'
# There should only be one feature that intersects this clip
# poly so this assertion should work.
assert compareWkt(myExpectedWkt,
mySymmetricalGeometry.asWkt())
myNewFeature = QgsFeature()
myNewFeature.setAttributes(myFeature.attributes())
myNewFeature.setGeometry(mySymmetricalGeometry)
myFeatures.append(myNewFeature)
myNewMemoryLayer = QgsVectorLayer(
('Polygon?crs=epsg:4326&field=name:string(20)&index=yes'),
'clip-out',
'memory')
myNewProvider = myNewMemoryLayer.dataProvider()
myResult, myFeatures = myNewProvider.addFeatures(myFeatures)
self.assertTrue(myResult)
self.assertEqual(len(myFeatures), 1)
writeShape(myNewMemoryLayer, 'clipGeometryAfter.shp')
def testClosestVertex(self):
# 2-+-+-+-+-3
# | |
# + 6-+-+-7 +
# | | | |
# + + 9-+-8 +
# | | |
# ! 5-+-+-+-4 !
# |
# 1-+-+-+-+-0 !
polyline = QgsGeometry.fromPolylineXY(
[QgsPointXY(5, 0), QgsPointXY(0, 0), QgsPointXY(0, 4), QgsPointXY(5, 4), QgsPointXY(5, 1), QgsPointXY(1, 1),
QgsPointXY(1, 3), QgsPointXY(4, 3), QgsPointXY(4, 2), QgsPointXY(2, 2)]
)
(point, atVertex, beforeVertex, afterVertex, dist) = polyline.closestVertex(QgsPointXY(6, 1))
self.assertEqual(point, QgsPointXY(5, 1))
self.assertEqual(beforeVertex, 3)
self.assertEqual(atVertex, 4)
self.assertEqual(afterVertex, 5)
self.assertEqual(dist, 1)
(dist, minDistPoint, afterVertex, leftOf) = polyline.closestSegmentWithContext(QgsPointXY(6, 2))
self.assertEqual(dist, 1)
self.assertEqual(minDistPoint, QgsPointXY(5, 2))
self.assertEqual(afterVertex, 4)
self.assertEqual(leftOf, -1)
(point, atVertex, beforeVertex, afterVertex, dist) = polyline.closestVertex(QgsPointXY(6, 0))
self.assertEqual(point, QgsPointXY(5, 0))
self.assertEqual(beforeVertex, -1)
self.assertEqual(atVertex, 0)
self.assertEqual(afterVertex, 1)
self.assertEqual(dist, 1)
(dist, minDistPoint, afterVertex, leftOf) = polyline.closestSegmentWithContext(QgsPointXY(6, 0))
self.assertEqual(dist, 1)
self.assertEqual(minDistPoint, QgsPointXY(5, 0))
self.assertEqual(afterVertex, 1)
self.assertEqual(leftOf, 0)
(point, atVertex, beforeVertex, afterVertex, dist) = polyline.closestVertex(QgsPointXY(0, -1))
self.assertEqual(point, QgsPointXY(0, 0))
self.assertEqual(beforeVertex, 0)
self.assertEqual(atVertex, 1)
self.assertEqual(afterVertex, 2)
self.assertEqual(dist, 1)
(dist, minDistPoint, afterVertex, leftOf) = polyline.closestSegmentWithContext(QgsPointXY(0, 1))
self.assertEqual(dist, 0)
self.assertEqual(minDistPoint, QgsPointXY(0, 1))
self.assertEqual(afterVertex, 2)
self.assertEqual(leftOf, 0)
# 2-3 6-+-7 !
# | | | |
# 0-1 4 5 8-9
polyline = QgsGeometry.fromMultiPolylineXY(
[
[QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 0), ],
[QgsPointXY(3, 0), QgsPointXY(3, 1), QgsPointXY(5, 1), QgsPointXY(5, 0), QgsPointXY(6, 0), ]
]
)
(point, atVertex, beforeVertex, afterVertex, dist) = polyline.closestVertex(QgsPointXY(5, 2))
self.assertEqual(point, QgsPointXY(5, 1))
self.assertEqual(beforeVertex, 6)
self.assertEqual(atVertex, 7)
self.assertEqual(afterVertex, 8)
self.assertEqual(dist, 1)
(dist, minDistPoint, afterVertex, leftOf) = polyline.closestSegmentWithContext(QgsPointXY(7, 0))
self.assertEqual(dist, 1)
self.assertEqual(minDistPoint, QgsPointXY(6, 0))
self.assertEqual(afterVertex, 9)
self.assertEqual(leftOf, 0)
# 5---4
# |! |
# | 2-3
# | |
# 0-1
polygon = QgsGeometry.fromPolygonXY(
[[
QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 2),
QgsPointXY(0, 2), QgsPointXY(0, 0),
]]
)
(point, atVertex, beforeVertex, afterVertex, dist) = polygon.closestVertex(QgsPointXY(0.7, 1.1))
self.assertEqual(point, QgsPointXY(1, 1))
self.assertEqual(beforeVertex, 1)
self.assertEqual(atVertex, 2)
self.assertEqual(afterVertex, 3)
assert abs(dist - 0.1) < 0.00001, "Expected: %f; Got:%f" % (dist, 0.1)
(dist, minDistPoint, afterVertex, leftOf) = polygon.closestSegmentWithContext(QgsPointXY(0.7, 1.1))
self.assertEqual(afterVertex, 2)
self.assertEqual(minDistPoint, QgsPointXY(1, 1))
exp = 0.3 ** 2 + 0.1 ** 2
assert abs(dist - exp) < 0.00001, "Expected: %f; Got:%f" % (exp, dist)
self.assertEqual(leftOf, -1)
# 3-+-+-2
# | |
# + 8-7 +
# | |!| |
# + 5-6 +
# | |
# 0-+-+-1
polygon = QgsGeometry.fromPolygonXY(
[
[QgsPointXY(0, 0), QgsPointXY(3, 0), QgsPointXY(3, 3), QgsPointXY(0, 3), QgsPointXY(0, 0)],
[QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 2), QgsPointXY(1, 2), QgsPointXY(1, 1)],
]
)
(point, atVertex, beforeVertex, afterVertex, dist) = polygon.closestVertex(QgsPointXY(1.1, 1.9))
self.assertEqual(point, QgsPointXY(1, 2))
self.assertEqual(beforeVertex, 7)
self.assertEqual(atVertex, 8)
self.assertEqual(afterVertex, 9)
assert abs(dist - 0.02) < 0.00001, "Expected: %f; Got:%f" % (dist, 0.02)
(dist, minDistPoint, afterVertex, leftOf) = polygon.closestSegmentWithContext(QgsPointXY(1.2, 1.9))
self.assertEqual(afterVertex, 8)
self.assertEqual(minDistPoint, QgsPointXY(1.2, 2))
exp = 0.01
assert abs(dist - exp) < 0.00001, "Expected: %f; Got:%f" % (exp, dist)
self.assertEqual(leftOf, -1)
# 5-+-4 0-+-9
# | | | |
# 6 2-3 1-2!+
# | | | |
# 0-1 7-8
polygon = QgsGeometry.fromMultiPolygonXY(
[
[[QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 2),
QgsPointXY(0, 2), QgsPointXY(0, 0), ]],
[[QgsPointXY(4, 0), QgsPointXY(5, 0), QgsPointXY(5, 2), QgsPointXY(3, 2), QgsPointXY(3, 1),
QgsPointXY(4, 1), QgsPointXY(4, 0), ]]
]
)
(point, atVertex, beforeVertex, afterVertex, dist) = polygon.closestVertex(QgsPointXY(4.1, 1.1))
self.assertEqual(point, QgsPointXY(4, 1))
self.assertEqual(beforeVertex, 11)
self.assertEqual(atVertex, 12)
self.assertEqual(afterVertex, 13)
assert abs(dist - 0.02) < 0.00001, "Expected: %f; Got:%f" % (dist, 0.02)
(dist, minDistPoint, afterVertex, leftOf) = polygon.closestSegmentWithContext(QgsPointXY(4.1, 1.1))
self.assertEqual(afterVertex, 12)
self.assertEqual(minDistPoint, QgsPointXY(4, 1))
exp = 0.02
assert abs(dist - exp) < 0.00001, "Expected: %f; Got:%f" % (exp, dist)
self.assertEqual(leftOf, -1)
(point, atVertex, beforeVertex, afterVertex, dist) = polygon.closestVertex(QgsPointXY())
self.assertTrue(point.isEmpty())
self.assertEqual(dist, -1)
(point, atVertex, beforeVertex, afterVertex, dist) = QgsGeometry().closestVertex(QgsPointXY(42, 42))
self.assertTrue(point.isEmpty())
def testAdjacentVertex(self):
# 2-+-+-+-+-3
# | |
# + 6-+-+-7 +
# | | | |
# + + 9-+-8 +
# | | |
# ! 5-+-+-+-4 !
# |
# 1-+-+-+-+-0 !
polyline = QgsGeometry.fromPolylineXY(
[QgsPointXY(5, 0), QgsPointXY(0, 0), QgsPointXY(0, 4), QgsPointXY(5, 4), QgsPointXY(5, 1), QgsPointXY(1, 1),
QgsPointXY(1, 3), QgsPointXY(4, 3), QgsPointXY(4, 2), QgsPointXY(2, 2)]
)
# don't crash
(before, after) = polyline.adjacentVertices(-100)
self.assertEqual(before == -1 and after, -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after))
for i in range(0, 10):
(before, after) = polyline.adjacentVertices(i)
if i == 0:
self.assertEqual(before == -1 and after, 1, "Expected (0,1), Got:(%d,%d)" % (before, after))
elif i == 9:
self.assertEqual(before == i - 1 and after, -1, "Expected (0,1), Got:(%d,%d)" % (before, after))
else:
self.assertEqual(before == i - 1 and after, i + 1, "Expected (0,1), Got:(%d,%d)" % (before, after))
(before, after) = polyline.adjacentVertices(100)
self.assertEqual(before == -1 and after, -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after))
# 2-3 6-+-7
# | | | |
# 0-1 4 5 8-9
polyline = QgsGeometry.fromMultiPolylineXY(
[
[QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 0), ],
[QgsPointXY(3, 0), QgsPointXY(3, 1), QgsPointXY(5, 1), QgsPointXY(5, 0), QgsPointXY(6, 0), ]
]
)
(before, after) = polyline.adjacentVertices(-100)
self.assertEqual(before == -1 and after, -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after))
for i in range(0, 10):
(before, after) = polyline.adjacentVertices(i)
if i == 0 or i == 5:
self.assertEqual(before == -1 and after, i + 1,
"Expected (-1,%d), Got:(%d,%d)" % (i + 1, before, after))
elif i == 4 or i == 9:
self.assertEqual(before == i - 1 and after, -1,
"Expected (%d,-1), Got:(%d,%d)" % (i - 1, before, after))
else:
self.assertEqual(before == i - 1 and after, i + 1,
"Expected (%d,%d), Got:(%d,%d)" % (i - 1, i + 1, before, after))
(before, after) = polyline.adjacentVertices(100)
self.assertEqual(before == -1 and after, -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after))
# 5---4
# | |
# | 2-3
# | |
# 0-1
polygon = QgsGeometry.fromPolygonXY(
[[
QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 2),
QgsPointXY(0, 2), QgsPointXY(0, 0),
]]
)
(before, after) = polygon.adjacentVertices(-100)
self.assertEqual(before == -1 and after, -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after))
for i in range(0, 7):
(before, after) = polygon.adjacentVertices(i)
if i == 0 or i == 6:
self.assertEqual(before == 5 and after, 1, "Expected (5,1), Got:(%d,%d)" % (before, after))
else:
self.assertEqual(before == i - 1 and after, i + 1,
"Expected (%d,%d), Got:(%d,%d)" % (i - 1, i + 1, before, after))
(before, after) = polygon.adjacentVertices(100)
self.assertEqual(before == -1 and after, -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after))
# 3-+-+-2
# | |
# + 8-7 +
# | | | |
# + 5-6 +
# | |
# 0-+-+-1
polygon = QgsGeometry.fromPolygonXY(
[
[QgsPointXY(0, 0), QgsPointXY(3, 0), QgsPointXY(3, 3), QgsPointXY(0, 3), QgsPointXY(0, 0)],
[QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 2), QgsPointXY(1, 2), QgsPointXY(1, 1)],
]
)
(before, after) = polygon.adjacentVertices(-100)
self.assertEqual(before == -1 and after, -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after))
for i in range(0, 8):
(before, after) = polygon.adjacentVertices(i)
if i == 0 or i == 4:
self.assertEqual(before == 3 and after, 1, "Expected (3,1), Got:(%d,%d)" % (before, after))
elif i == 5:
self.assertEqual(before == 8 and after, 6, "Expected (2,0), Got:(%d,%d)" % (before, after))
else:
self.assertEqual(before == i - 1 and after, i + 1,
"Expected (%d,%d), Got:(%d,%d)" % (i - 1, i + 1, before, after))
(before, after) = polygon.adjacentVertices(100)
self.assertEqual(before == -1 and after, -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after))
# 5-+-4 0-+-9
# | | | |
# | 2-3 1-2 |
# | | | |
# 0-1 7-8
polygon = QgsGeometry.fromMultiPolygonXY(
[
[[QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 2),
QgsPointXY(0, 2), QgsPointXY(0, 0), ]],
[[QgsPointXY(4, 0), QgsPointXY(5, 0), QgsPointXY(5, 2), QgsPointXY(3, 2), QgsPointXY(3, 1),
QgsPointXY(4, 1), QgsPointXY(4, 0), ]]
]
)
(before, after) = polygon.adjacentVertices(-100)
self.assertEqual(before == -1 and after, -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after))
for i in range(0, 14):
(before, after) = polygon.adjacentVertices(i)
if i == 0 or i == 6:
self.assertEqual(before == 5 and after, 1, "Expected (5,1), Got:(%d,%d)" % (before, after))
elif i == 7 or i == 13:
self.assertEqual(before == 12 and after, 8, "Expected (12,8), Got:(%d,%d)" % (before, after))
else:
self.assertEqual(before == i - 1 and after, i + 1,
"Expected (%d,%d), Got:(%d,%d)" % (i - 1, i + 1, before, after))
(before, after) = polygon.adjacentVertices(100)
self.assertEqual(before == -1 and after, -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after))
def testVertexAt(self):
# 2-+-+-+-+-3
# | |
# + 6-+-+-7 +
# | | | |
# + + 9-+-8 +
# | | |
# ! 5-+-+-+-4 !
# |
# 1-+-+-+-+-0 !
points = [QgsPointXY(5, 0), QgsPointXY(0, 0), QgsPointXY(0, 4), QgsPointXY(5, 4), QgsPointXY(5, 1),
QgsPointXY(1, 1), QgsPointXY(1, 3), QgsPointXY(4, 3), QgsPointXY(4, 2), QgsPointXY(2, 2)]
polyline = QgsGeometry.fromPolylineXY(points)
for i in range(0, len(points)):
# WORKAROUND to avoid a system error
# self.assertEqual(QgsPoint(points[i]), polyline.vertexAt(i), "Mismatch at %d" % i)
self.assertEqual(QgsPoint(points[i].x(), points[i].y()), polyline.vertexAt(i), "Mismatch at %d" % i)
# 2-3 6-+-7
# | | | |
# 0-1 4 5 8-9
points = [
[QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 0), ],
[QgsPointXY(3, 0), QgsPointXY(3, 1), QgsPointXY(5, 1), QgsPointXY(5, 0), QgsPointXY(6, 0), ]
]
polyline = QgsGeometry.fromMultiPolylineXY(points)
p = polyline.vertexAt(-100)
self.assertEqual(p, QgsPoint(math.nan, math.nan), "Expected 0,0, Got {}.{}".format(p.x(), p.y()))
p = polyline.vertexAt(100)
self.assertEqual(p, QgsPoint(math.nan, math.nan), "Expected 0,0, Got {}.{}".format(p.x(), p.y()))
i = 0
for j in range(0, len(points)):
for k in range(0, len(points[j])):
# WORKAROUND
# self.assertEqual(QgsPoint(points[j][k]), polyline.vertexAt(i), "Mismatch at %d / %d,%d" % (i, j, k))
pt = points[j][k]
self.assertEqual(QgsPoint(pt.x(), pt.y()), polyline.vertexAt(i), "Mismatch at %d / %d,%d" % (i, j, k))
i += 1
# 5---4
# | |
# | 2-3
# | |
# 0-1
points = [[
QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 2), QgsPointXY(0, 2),
QgsPointXY(0, 0),
]]
polygon = QgsGeometry.fromPolygonXY(points)
p = polygon.vertexAt(-100)
self.assertEqual(p, QgsPoint(), "Expected 0,0, Got {}.{}".format(p.x(), p.y()))
p = polygon.vertexAt(100)
self.assertEqual(p, QgsPoint(), "Expected 0,0, Got {}.{}".format(p.x(), p.y()))
i = 0
for j in range(0, len(points)):
for k in range(0, len(points[j])):
# WORKAROUND
# self.assertEqual(QgsPoint(points[j][k]), polygon.vertexAt(i), "Mismatch at %d / %d,%d" % (i, j, k))
pt = points[j][k]
self.assertEqual(QgsPoint(pt.x(), pt.y()), polygon.vertexAt(i), "Mismatch at %d / %d,%d" % (i, j, k))
i += 1
# 3-+-+-2
# | |
# + 8-7 +
# | | | |
# + 5-6 +
# | |
# 0-+-+-1
points = [
[QgsPointXY(0, 0), QgsPointXY(3, 0), QgsPointXY(3, 3), QgsPointXY(0, 3), QgsPointXY(0, 0)],
[QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 2), QgsPointXY(1, 2), QgsPointXY(1, 1)],
]
polygon = QgsGeometry.fromPolygonXY(points)
p = polygon.vertexAt(-100)
self.assertEqual(p, QgsPoint(), "Expected 0,0, Got {}.{}".format(p.x(), p.y()))
p = polygon.vertexAt(100)
self.assertEqual(p, QgsPoint(), "Expected 0,0, Got {}.{}".format(p.x(), p.y()))
i = 0
for j in range(0, len(points)):
for k in range(0, len(points[j])):
# WORKAROUND
# self.assertEqual(QgsPoint(points[j][k]), polygon.vertexAt(i), "Mismatch at %d / %d,%d" % (i, j, k))
pt = points[j][k]
self.assertEqual(QgsPoint(pt.x(), pt.y()), polygon.vertexAt(i), "Mismatch at %d / %d,%d" % (i, j, k))
i += 1
# 5-+-4 0-+-9
# | | | |
# | 2-3 1-2 |
# | | | |
# 0-1 7-8
points = [
[[QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 2),
QgsPointXY(0, 2), QgsPointXY(0, 0), ]],
[[QgsPointXY(4, 0), QgsPointXY(5, 0), QgsPointXY(5, 2), QgsPointXY(3, 2), QgsPointXY(3, 1),
QgsPointXY(4, 1), QgsPointXY(4, 0), ]]
]
polygon = QgsGeometry.fromMultiPolygonXY(points)
p = polygon.vertexAt(-100)
self.assertEqual(p, QgsPoint(), "Expected 0,0, Got {}.{}".format(p.x(), p.y()))
p = polygon.vertexAt(100)
self.assertEqual(p, QgsPoint(), "Expected 0,0, Got {}.{}".format(p.x(), p.y()))
i = 0
for j in range(0, len(points)):
for k in range(0, len(points[j])):
for l in range(0, len(points[j][k])):
p = polygon.vertexAt(i)
# WORKAROUND
# self.assertEqual(QgsPoint(points[j][k][l]), p, "Got {},{} Expected {} at {} / {},{},{}".format(p.x(), p.y(), points[j][k][l].toString(), i, j, k, l))
pt = points[j][k][l]
self.assertEqual(QgsPoint(pt.x(), pt.y()), p,
"Got {},{} Expected {} at {} / {},{},{}".format(p.x(), p.y(), pt.toString(), i, j,
k, l))
i += 1
def testMultipoint(self):
# #9423
points = [QgsPointXY(10, 30), QgsPointXY(40, 20), QgsPointXY(30, 10), QgsPointXY(20, 10)]
wkt = "MultiPoint ((10 30),(40 20),(30 10),(20 10))"
multipoint = QgsGeometry.fromWkt(wkt)
assert multipoint.isMultipart(), "Expected MultiPoint to be multipart"
self.assertEqual(multipoint.wkbType(), QgsWkbTypes.MultiPoint, "Expected wkbType to be WKBMultipoint")
i = 0
for p in multipoint.asMultiPoint():
self.assertEqual(p, points[i], "Expected %s at %d, got %s" % (points[i].toString(), i, p.toString()))
i += 1
multipoint = QgsGeometry.fromWkt("MultiPoint ((5 5))")
self.assertEqual(multipoint.vertexAt(0), QgsPoint(5, 5), "MULTIPOINT fromWkt failed")
assert multipoint.insertVertex(4, 4, 0), "MULTIPOINT insert 4,4 at 0 failed"
expwkt = "MultiPoint ((4 4),(5 5))"
wkt = multipoint.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert multipoint.insertVertex(7, 7, 2), "MULTIPOINT append 7,7 at 2 failed"
expwkt = "MultiPoint ((4 4),(5 5),(7 7))"
wkt = multipoint.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert multipoint.insertVertex(6, 6, 2), "MULTIPOINT append 6,6 at 2 failed"
expwkt = "MultiPoint ((4 4),(5 5),(6 6),(7 7))"
wkt = multipoint.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert not multipoint.deleteVertex(4), "MULTIPOINT delete at 4 unexpectedly succeeded"
assert not multipoint.deleteVertex(-1), "MULTIPOINT delete at -1 unexpectedly succeeded"
assert multipoint.deleteVertex(1), "MULTIPOINT delete at 1 failed"
expwkt = "MultiPoint ((4 4),(6 6),(7 7))"
wkt = multipoint.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert multipoint.deleteVertex(2), "MULTIPOINT delete at 2 failed"
expwkt = "MultiPoint ((4 4),(6 6))"
wkt = multipoint.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert multipoint.deleteVertex(0), "MULTIPOINT delete at 2 failed"
expwkt = "MultiPoint ((6 6))"
wkt = multipoint.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
multipoint = QgsGeometry.fromWkt("MultiPoint ((5 5))")
self.assertEqual(multipoint.vertexAt(0), QgsPoint(5, 5), "MultiPoint fromWkt failed")
def testMoveVertex(self):
multipoint = QgsGeometry.fromWkt("MultiPoint ((5 0),(0 0),(0 4),(5 4),(5 1),(1 1),(1 3),(4 3),(4 2),(2 2))")
# try moving invalid vertices
assert not multipoint.moveVertex(9, 9, -1), "move vertex succeeded when it should have failed"
assert not multipoint.moveVertex(9, 9, 10), "move vertex succeeded when it should have failed"
assert not multipoint.moveVertex(9, 9, 11), "move vertex succeeded when it should have failed"
for i in range(0, 10):
assert multipoint.moveVertex(i + 1, -1 - i, i), "move vertex %d failed" % i
expwkt = "MultiPoint ((1 -1),(2 -2),(3 -3),(4 -4),(5 -5),(6 -6),(7 -7),(8 -8),(9 -9),(10 -10))"
wkt = multipoint.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# 2-+-+-+-+-3
# | |
# + 6-+-+-7 +
# | | | |
# + + 9-+-8 +
# | | |
# ! 5-+-+-+-4 !
# |
# 1-+-+-+-+-0 !
polyline = QgsGeometry.fromWkt("LineString (5 0, 0 0, 0 4, 5 4, 5 1, 1 1, 1 3, 4 3, 4 2, 2 2)")
# try moving invalid vertices
assert not polyline.moveVertex(9, 9, -1), "move vertex succeeded when it should have failed"
assert not polyline.moveVertex(9, 9, 10), "move vertex succeeded when it should have failed"
assert not polyline.moveVertex(9, 9, 11), "move vertex succeeded when it should have failed"
assert polyline.moveVertex(5.5, 4.5, 3), "move vertex failed"
expwkt = "LineString (5 0, 0 0, 0 4, 5.5 4.5, 5 1, 1 1, 1 3, 4 3, 4 2, 2 2)"
wkt = polyline.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# 5-+-4
# | |
# 6 2-3
# | |
# 0-1
polygon = QgsGeometry.fromWkt("Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))")
assert not polygon.moveVertex(3, 4, -10), "move vertex unexpectedly succeeded"
assert not polygon.moveVertex(3, 4, 7), "move vertex unexpectedly succeeded"
assert not polygon.moveVertex(3, 4, 8), "move vertex unexpectedly succeeded"
assert polygon.moveVertex(1, 2, 0), "move vertex failed"
expwkt = "Polygon ((1 2, 1 0, 1 1, 2 1, 2 2, 0 2, 1 2))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.moveVertex(3, 4, 3), "move vertex failed"
expwkt = "Polygon ((1 2, 1 0, 1 1, 3 4, 2 2, 0 2, 1 2))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.moveVertex(2, 3, 6), "move vertex failed"
expwkt = "Polygon ((2 3, 1 0, 1 1, 3 4, 2 2, 0 2, 2 3))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# 5-+-4 0-+-9
# | | | |
# 6 2-3 1-2!+
# | | | |
# 0-1 7-8
polygon = QgsGeometry.fromWkt(
"MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))")
assert not polygon.moveVertex(3, 4, -10), "move vertex unexpectedly succeeded"
assert not polygon.moveVertex(3, 4, 14), "move vertex unexpectedly succeeded"
assert not polygon.moveVertex(3, 4, 15), "move vertex unexpectedly succeeded"
assert polygon.moveVertex(6, 2, 9), "move vertex failed"
expwkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 6 2, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.moveVertex(1, 2, 0), "move vertex failed"
expwkt = "MultiPolygon (((1 2, 1 0, 1 1, 2 1, 2 2, 0 2, 1 2)),((4 0, 5 0, 6 2, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.moveVertex(2, 1, 7), "move vertex failed"
expwkt = "MultiPolygon (((1 2, 1 0, 1 1, 2 1, 2 2, 0 2, 1 2)),((2 1, 5 0, 6 2, 3 2, 3 1, 4 1, 2 1)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
def testDeleteVertex(self):
# 2-+-+-+-+-3
# | |
# + 6-+-+-7 +
# | | | |
# + + 9-+-8 +
# | | |
# ! 5-+-+-+-4
# |
# 1-+-+-+-+-0
polyline = QgsGeometry.fromWkt("LineString (5 0, 0 0, 0 4, 5 4, 5 1, 1 1, 1 3, 4 3, 4 2, 2 2)")
assert polyline.deleteVertex(3), "Delete vertex 5 4 failed"
expwkt = "LineString (5 0, 0 0, 0 4, 5 1, 1 1, 1 3, 4 3, 4 2, 2 2)"
wkt = polyline.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert not polyline.deleteVertex(-5), "Delete vertex -5 unexpectedly succeeded"
assert not polyline.deleteVertex(100), "Delete vertex 100 unexpectedly succeeded"
# 2-3 6-+-7
# | | | |
# 0-1 4 5 8-9
polyline = QgsGeometry.fromWkt("MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 0),(3 0, 3 1, 5 1, 5 0, 6 0))")
assert polyline.deleteVertex(5), "Delete vertex 5 failed"
expwkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 0), (3 1, 5 1, 5 0, 6 0))"
wkt = polyline.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert not polyline.deleteVertex(-100), "Delete vertex -100 unexpectedly succeeded"
assert not polyline.deleteVertex(100), "Delete vertex 100 unexpectedly succeeded"
assert polyline.deleteVertex(0), "Delete vertex 0 failed"
expwkt = "MultiLineString ((1 0, 1 1, 2 1, 2 0), (3 1, 5 1, 5 0, 6 0))"
wkt = polyline.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
polyline = QgsGeometry.fromWkt("MultiLineString ((0 0, 1 0, 1 1, 2 1,2 0),(3 0, 3 1, 5 1, 5 0, 6 0))")
for i in range(4):
assert polyline.deleteVertex(5), "Delete vertex 5 failed"
expwkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 0))"
wkt = polyline.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# 5---4
# | |
# | 2-3
# | |
# 0-1
polygon = QgsGeometry.fromWkt("Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))")
assert polygon.deleteVertex(2), "Delete vertex 2 failed"
expwkt = "Polygon ((0 0, 1 0, 2 1, 2 2, 0 2, 0 0))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.deleteVertex(0), "Delete vertex 0 failed"
expwkt = "Polygon ((1 0, 2 1, 2 2, 0 2, 1 0))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.deleteVertex(4), "Delete vertex 4 failed"
# "Polygon ((2 1, 2 2, 0 2, 2 1))" #several possibilities are correct here
expwkt = "Polygon ((0 2, 2 1, 2 2, 0 2))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert not polygon.deleteVertex(-100), "Delete vertex -100 unexpectedly succeeded"
assert not polygon.deleteVertex(100), "Delete vertex 100 unexpectedly succeeded"
# 5-+-4 0-+-9
# | | | |
# 6 2-3 1-2 +
# | | | |
# 0-1 7-8
polygon = QgsGeometry.fromWkt(
"MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))")
assert polygon.deleteVertex(9), "Delete vertex 5 2 failed"
expwkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.deleteVertex(0), "Delete vertex 0 failed"
expwkt = "MultiPolygon (((1 0, 1 1, 2 1, 2 2, 0 2, 1 0)),((4 0, 5 0, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.deleteVertex(6), "Delete vertex 6 failed"
expwkt = "MultiPolygon (((1 0, 1 1, 2 1, 2 2, 0 2, 1 0)),((5 0, 3 2, 3 1, 4 1, 5 0)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
polygon = QgsGeometry.fromWkt(
"MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))")
for i in range(4):
assert polygon.deleteVertex(0), "Delete vertex 0 failed"
expwkt = "MultiPolygon (((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# 3-+-+-+-+-+-+-+-+-2
# | |
# + 8-7 3-2 8-7 3-2 +
# | | | | | | | | | |
# + 5-6 0-1 5-6 0-1 +
# | |
# 0-+-+-+-+---+-+-+-1
polygon = QgsGeometry.fromWkt(
"Polygon ((0 0, 9 0, 9 3, 0 3, 0 0),(1 1, 2 1, 2 2, 1 2, 1 1),(3 1, 4 1, 4 2, 3 2, 3 1),(5 1, 6 1, 6 2, 5 2, 5 1),(7 1, 8 1, 8 2, 7 2, 7 1))")
# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
for i in range(2):
assert polygon.deleteVertex(16), "Delete vertex 16 failed" % i
expwkt = "Polygon ((0 0, 9 0, 9 3, 0 3, 0 0),(1 1, 2 1, 2 2, 1 2, 1 1),(3 1, 4 1, 4 2, 3 2, 3 1),(7 1, 8 1, 8 2, 7 2, 7 1))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
for i in range(3):
for j in range(2):
assert polygon.deleteVertex(5), "Delete vertex 5 failed" % i
expwkt = "Polygon ((0 0, 9 0, 9 3, 0 3, 0 0))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# Remove whole outer ring, inner ring should become outer
polygon = QgsGeometry.fromWkt("Polygon ((0 0, 9 0, 9 3, 0 3, 0 0),(1 1, 2 1, 2 2, 1 2, 1 1))")
for i in range(2):
assert polygon.deleteVertex(0), "Delete vertex 16 failed" % i
expwkt = "Polygon ((1 1, 2 1, 2 2, 1 2, 1 1))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
def testInsertVertex(self):
linestring = QgsGeometry.fromWkt("LineString(1 0, 2 0)")
assert linestring.insertVertex(0, 0, 0), "Insert vertex 0 0 at 0 failed"
expwkt = "LineString (0 0, 1 0, 2 0)"
wkt = linestring.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert linestring.insertVertex(1.5, 0, 2), "Insert vertex 1.5 0 at 2 failed"
expwkt = "LineString (0 0, 1 0, 1.5 0, 2 0)"
wkt = linestring.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert not linestring.insertVertex(3, 0, 5), "Insert vertex 3 0 at 5 should have failed"
polygon = QgsGeometry.fromWkt(
"MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))")
assert polygon.insertVertex(0, 0, 8), "Insert vertex 0 0 at 8 failed"
expwkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 0 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
polygon = QgsGeometry.fromWkt(
"MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))")
assert polygon.insertVertex(0, 0, 7), "Insert vertex 0 0 at 7 failed"
expwkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((0 0, 4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 0 0)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
def testTranslate(self):
point = QgsGeometry.fromWkt("Point (1 1)")
self.assertEqual(point.translate(1, 2), 0, "Translate failed")
expwkt = "Point (2 3)"
wkt = point.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
point = QgsGeometry.fromWkt("MultiPoint ((1 1),(2 2),(3 3))")
self.assertEqual(point.translate(1, 2), 0, "Translate failed")
expwkt = "MultiPoint ((2 3),(3 4),(4 5))"
wkt = point.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
linestring = QgsGeometry.fromWkt("LineString (1 0, 2 0)")
self.assertEqual(linestring.translate(1, 2), 0, "Translate failed")
expwkt = "LineString (2 2, 3 2)"
wkt = linestring.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
polygon = QgsGeometry.fromWkt(
"MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))")
self.assertEqual(polygon.translate(1, 2), 0, "Translate failed")
expwkt = "MultiPolygon (((1 2, 2 2, 2 3, 3 3, 3 4, 1 4, 1 2)),((5 2, 6 2, 6 4, 4 4, 4 3, 5 3, 5 2)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
def testTransform(self):
# null transform
ct = QgsCoordinateTransform()
point = QgsGeometry.fromWkt("Point (1 1)")
self.assertEqual(point.transform(ct), 0, "Transform failed")
expwkt = "Point (1 1)"
wkt = point.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
point = QgsGeometry.fromWkt("MultiPoint ((1 1),(2 2),(3 3))")
self.assertEqual(point.transform(ct), 0, "Transform failed")
expwkt = "MultiPoint ((1 1),(2 2),(3 3))"
wkt = point.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
linestring = QgsGeometry.fromWkt("LineString (1 0, 2 0)")
self.assertEqual(linestring.transform(ct), 0, "Transform failed")
expwkt = "LineString (1 0, 2 0)"
wkt = linestring.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
polygon = QgsGeometry.fromWkt("MultiPolygon(((0 0,1 0,1 1,2 1,2 2,0 2,0 0)),((4 0,5 0,5 2,3 2,3 1,4 1,4 0)))")
self.assertEqual(polygon.transform(ct), 0, "Transform failed")
expwkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# valid transform
ct = QgsCoordinateTransform(QgsCoordinateReferenceSystem(4326), QgsCoordinateReferenceSystem(3857),
QgsProject.instance())
point = QgsGeometry.fromWkt("Point (1 1)")
self.assertEqual(point.transform(ct), 0, "Transform failed")
expwkt = "Point (111319 111325)"
wkt = point.asWkt()
assert compareWkt(expwkt, wkt, tol=100), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
point = QgsGeometry.fromWkt("MultiPoint ((1 1),(2 2),(3 3))")
self.assertEqual(point.transform(ct), 0, "Transform failed")
expwkt = "MultiPoint ((111319 111325),(222638 222684),(333958 334111))"
wkt = point.asWkt()
assert compareWkt(expwkt, wkt, tol=100), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
linestring = QgsGeometry.fromWkt("LineString (1 0, 2 0)")
self.assertEqual(linestring.transform(ct), 0, "Transform failed")
expwkt = "LineString (111319 0, 222638 0)"
wkt = linestring.asWkt()
assert compareWkt(expwkt, wkt, tol=100), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
polygon = QgsGeometry.fromWkt("MultiPolygon(((0 0,1 0,1 1,2 1,2 2,0 2,0 0)),((4 0,5 0,5 2,3 2,3 1,4 1,4 0)))")
self.assertEqual(polygon.transform(ct), 0, "Transform failed")
expwkt = "MultiPolygon (((0 0, 111319 0, 111319 111325, 222638 111325, 222638 222684, 0 222684, 0 0)),((445277 0, 556597 0, 556597 222684, 333958 222684, 333958 111325, 445277 111325, 445277 0)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt, tol=100), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# reverse transform
point = QgsGeometry.fromWkt("Point (111319 111325)")
self.assertEqual(point.transform(ct, QgsCoordinateTransform.ReverseTransform), 0, "Transform failed")
expwkt = "Point (1 1)"
wkt = point.asWkt()
assert compareWkt(expwkt, wkt, tol=0.01), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
point = QgsGeometry.fromWkt("MultiPoint ((111319 111325),(222638 222684),(333958 334111))")
self.assertEqual(point.transform(ct, QgsCoordinateTransform.ReverseTransform), 0, "Transform failed")
expwkt = "MultiPoint ((1 1),(2 2),(3 3))"
wkt = point.asWkt()
assert compareWkt(expwkt, wkt, tol=0.01), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
linestring = QgsGeometry.fromWkt("LineString (111319 0, 222638 0)")
self.assertEqual(linestring.transform(ct, QgsCoordinateTransform.ReverseTransform), 0, "Transform failed")
expwkt = "LineString (1 0, 2 0)"
wkt = linestring.asWkt()
assert compareWkt(expwkt, wkt, tol=0.01), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
polygon = QgsGeometry.fromWkt(
"MultiPolygon (((0 0, 111319 0, 111319 111325, 222638 111325, 222638 222684, 0 222684, 0 0)),((445277 0, 556597 0, 556597 222684, 333958 222684, 333958 111325, 445277 111325, 445277 0)))")
self.assertEqual(polygon.transform(ct, QgsCoordinateTransform.ReverseTransform), 0, "Transform failed")
expwkt = "MultiPolygon(((0 0,1 0,1 1,2 1,2 2,0 2,0 0)),((4 0,5 0,5 2,3 2,3 1,4 1,4 0)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt, tol=0.01), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
def testExtrude(self):
# test with empty geometry
g = QgsGeometry()
self.assertTrue(g.extrude(1, 2).isNull())
points = [QgsPointXY(1, 2), QgsPointXY(3, 2), QgsPointXY(4, 3)]
line = QgsGeometry.fromPolylineXY(points)
expected = QgsGeometry.fromWkt('Polygon ((1 2, 3 2, 4 3, 5 5, 4 4, 2 4, 1 2))')
self.assertEqual(line.extrude(1, 2).asWkt(), expected.asWkt())
points2 = [[QgsPointXY(1, 2), QgsPointXY(3, 2)], [QgsPointXY(4, 3), QgsPointXY(8, 3)]]
multiline = QgsGeometry.fromMultiPolylineXY(points2)
expected = QgsGeometry.fromWkt('MultiPolygon (((1 2, 3 2, 4 4, 2 4, 1 2)),((4 3, 8 3, 9 5, 5 5, 4 3)))')
self.assertEqual(multiline.extrude(1, 2).asWkt(), expected.asWkt())
def testNearestPoint(self):
# test with empty geometries
g1 = QgsGeometry()
g2 = QgsGeometry()
self.assertTrue(g1.nearestPoint(g2).isNull())
g1 = QgsGeometry.fromWkt('LineString( 1 1, 5 1, 5 5 )')
self.assertTrue(g1.nearestPoint(g2).isNull())
self.assertTrue(g2.nearestPoint(g1).isNull())
g2 = QgsGeometry.fromWkt('Point( 6 3 )')
expWkt = 'Point( 5 3 )'
wkt = g1.nearestPoint(g2).asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
expWkt = 'Point( 6 3 )'
wkt = g2.nearestPoint(g1).asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
g1 = QgsGeometry.fromWkt('Polygon ((1 1, 5 1, 5 5, 1 5, 1 1))')
g2 = QgsGeometry.fromWkt('Point( 6 3 )')
expWkt = 'Point( 5 3 )'
wkt = g1.nearestPoint(g2).asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
expWkt = 'Point( 6 3 )'
wkt = g2.nearestPoint(g1).asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
g2 = QgsGeometry.fromWkt('Point( 2 3 )')
expWkt = 'Point( 2 3 )'
wkt = g1.nearestPoint(g2).asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
# trivial point case
expWkt = 'Point (3 4)'
wkt = QgsGeometry.fromWkt('Point(3 4)').nearestPoint(QgsGeometry.fromWkt('Point(-1 -8)')).asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
wkt = QgsGeometry.fromWkt('Point(3 4)').nearestPoint(QgsGeometry.fromWkt('LineString( 1 1, 5 1, 5 5 )')).asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
def testShortestLine(self):
# test with empty geometries
g1 = QgsGeometry()
g2 = QgsGeometry()
self.assertTrue(g1.shortestLine(g2).isNull())
g1 = QgsGeometry.fromWkt('LineString( 1 1, 5 1, 5 5 )')
self.assertTrue(g1.shortestLine(g2).isNull())
self.assertTrue(g2.shortestLine(g1).isNull())
g2 = QgsGeometry.fromWkt('Point( 6 3 )')
expWkt = 'LineString( 5 3, 6 3 )'
wkt = g1.shortestLine(g2).asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
expWkt = 'LineString( 6 3, 5 3 )'
wkt = g2.shortestLine(g1).asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
g1 = QgsGeometry.fromWkt('Polygon ((1 1, 5 1, 5 5, 1 5, 1 1))')
g2 = QgsGeometry.fromWkt('Point( 6 3 )')
expWkt = 'LineString( 5 3, 6 3 )'
wkt = g1.shortestLine(g2).asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
expWkt = 'LineString( 6 3, 5 3 )'
wkt = g2.shortestLine(g1).asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
g2 = QgsGeometry.fromWkt('Point( 2 3 )')
expWkt = 'LineString( 2 3, 2 3 )'
wkt = g1.shortestLine(g2).asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
# trivial point to point case
expWkt = 'LineString (3 4, -1 -8)'
wkt = QgsGeometry.fromWkt('Point(3 4)').shortestLine(QgsGeometry.fromWkt('Point(-1 -8)')).asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
def testBoundingBox(self):
# 2-+-+-+-+-3
# | |
# + 6-+-+-7 +
# | | | |
# + + 9-+-8 +
# | | |
# ! 5-+-+-+-4 !
# |
# 1-+-+-+-+-0 !
points = [QgsPointXY(5, 0), QgsPointXY(0, 0), QgsPointXY(0, 4), QgsPointXY(5, 4), QgsPointXY(5, 1),
QgsPointXY(1, 1), QgsPointXY(1, 3), QgsPointXY(4, 3), QgsPointXY(4, 2), QgsPointXY(2, 2)]
polyline = QgsGeometry.fromPolylineXY(points)
expbb = QgsRectangle(0, 0, 5, 4)
bb = polyline.boundingBox()
self.assertEqual(expbb, bb, "Expected:\n%s\nGot:\n%s\n" % (expbb.toString(), bb.toString()))
# 2-3 6-+-7
# | | | |
# 0-1 4 5 8-9
points = [
[QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 0), ],
[QgsPointXY(3, 0), QgsPointXY(3, 1), QgsPointXY(5, 1), QgsPointXY(5, 0), QgsPointXY(6, 0), ]
]
polyline = QgsGeometry.fromMultiPolylineXY(points)
expbb = QgsRectangle(0, 0, 6, 1)
bb = polyline.boundingBox()
self.assertEqual(expbb, bb, "Expected:\n%s\nGot:\n%s\n" % (expbb.toString(), bb.toString()))
# 5---4
# | |
# | 2-3
# | |
# 0-1
points = [[
QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 2), QgsPointXY(0, 2),
QgsPointXY(0, 0),
]]
polygon = QgsGeometry.fromPolygonXY(points)
expbb = QgsRectangle(0, 0, 2, 2)
bb = polygon.boundingBox()
self.assertEqual(expbb, bb, "Expected:\n%s\nGot:\n%s\n" % (expbb.toString(), bb.toString()))
# 3-+-+-2
# | |
# + 8-7 +
# | | | |
# + 5-6 +
# | |
# 0-+-+-1
points = [
[QgsPointXY(0, 0), QgsPointXY(3, 0), QgsPointXY(3, 3), QgsPointXY(0, 3), QgsPointXY(0, 0)],
[QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 2), QgsPointXY(1, 2), QgsPointXY(1, 1)],
]
polygon = QgsGeometry.fromPolygonXY(points)
expbb = QgsRectangle(0, 0, 3, 3)
bb = polygon.boundingBox()
self.assertEqual(expbb, bb, "Expected:\n%s\nGot:\n%s\n" % (expbb.toString(), bb.toString()))
# 5-+-4 0-+-9
# | | | |
# | 2-3 1-2 |
# | | | |
# 0-1 7-8
points = [
[[QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 2),
QgsPointXY(0, 2), QgsPointXY(0, 0), ]],
[[QgsPointXY(4, 0), QgsPointXY(5, 0), QgsPointXY(5, 2), QgsPointXY(3, 2), QgsPointXY(3, 1),
QgsPointXY(4, 1), QgsPointXY(4, 0), ]]
]
polygon = QgsGeometry.fromMultiPolygonXY(points)
expbb = QgsRectangle(0, 0, 5, 2)
bb = polygon.boundingBox()
self.assertEqual(expbb, bb, "Expected:\n%s\nGot:\n%s\n" % (expbb.toString(), bb.toString()))
# NULL
points = []
line = QgsGeometry.fromPolylineXY(points)
assert line.boundingBox().isNull()
def testCollectGeometry(self):
# collect points
geometries = [QgsGeometry.fromPointXY(QgsPointXY(0, 0)), QgsGeometry.fromPointXY(QgsPointXY(1, 1))]
geometry = QgsGeometry.collectGeometry(geometries)
expwkt = "MultiPoint ((0 0), (1 1))"
wkt = geometry.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# collect lines
points = [
[QgsPointXY(0, 0), QgsPointXY(1, 0)],
[QgsPointXY(2, 0), QgsPointXY(3, 0)]
]
geometries = [QgsGeometry.fromPolylineXY(points[0]), QgsGeometry.fromPolylineXY(points[1])]
geometry = QgsGeometry.collectGeometry(geometries)
expwkt = "MultiLineString ((0 0, 1 0), (2 0, 3 0))"
wkt = geometry.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# collect polygons
points = [
[[QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(0, 1), QgsPointXY(0, 0)]],
[[QgsPointXY(2, 0), QgsPointXY(3, 0), QgsPointXY(3, 1), QgsPointXY(2, 1), QgsPointXY(2, 0)]]
]
geometries = [QgsGeometry.fromPolygonXY(points[0]), QgsGeometry.fromPolygonXY(points[1])]
geometry = QgsGeometry.collectGeometry(geometries)
expwkt = "MultiPolygon (((0 0, 1 0, 1 1, 0 1, 0 0)),((2 0, 3 0, 3 1, 2 1, 2 0)))"
wkt = geometry.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# collect some geometries which are already multipart
geometries = [QgsGeometry.fromWkt('LineString( 0 0, 1 1)'),
QgsGeometry.fromWkt('MultiLineString((2 2, 3 3),(4 4, 5 5))')]
geometry = QgsGeometry.collectGeometry(geometries)
expwkt = "MultiLineString ((0 0, 1 1),(2 2, 3 3),(4 4, 5 5))"
wkt = geometry.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
geometries = [QgsGeometry.fromWkt('MultiLineString((2 2, 3 3),(4 4, 5 5))'),
QgsGeometry.fromWkt('LineString( 0 0, 1 1)')]
geometry = QgsGeometry.collectGeometry(geometries)
expwkt = "MultiLineString ((2 2, 3 3),(4 4, 5 5),(0 0, 1 1))"
wkt = geometry.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
geometries = [QgsGeometry.fromWkt('Polygon((100 100, 101 100, 101 101, 100 100))'),
QgsGeometry.fromWkt('MultiPolygon (((0 0, 1 0, 1 1, 0 1, 0 0)),((2 0, 3 0, 3 1, 2 1, 2 0)))')]
geometry = QgsGeometry.collectGeometry(geometries)
expwkt = "MultiPolygon (((100 100, 101 100, 101 101, 100 100)),((0 0, 1 0, 1 1, 0 1, 0 0)),((2 0, 3 0, 3 1, 2 1, 2 0)))"
wkt = geometry.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
geometries = [QgsGeometry.fromWkt('MultiPolygon (((0 0, 1 0, 1 1, 0 1, 0 0)),((2 0, 3 0, 3 1, 2 1, 2 0)))'),
QgsGeometry.fromWkt('Polygon((100 100, 101 100, 101 101, 100 100))')]
geometry = QgsGeometry.collectGeometry(geometries)
expwkt = "MultiPolygon (((0 0, 1 0, 1 1, 0 1, 0 0)),((2 0, 3 0, 3 1, 2 1, 2 0)),((100 100, 101 100, 101 101, 100 100)))"
wkt = geometry.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
geometries = [QgsGeometry(QgsTriangle(QgsPoint(0, 0, 5), QgsPoint(1, 0, 6), QgsPoint(1, 1, 7))),
QgsGeometry(QgsTriangle(QgsPoint(100, 100, 9), QgsPoint(101, 100, -1), QgsPoint(101, 101, 4)))]
geometry = QgsGeometry.collectGeometry(geometries)
expwkt = "MultiPolygonZ (((0 0 5, 1 0 6, 1 1 7, 0 0 5)),((100 100 9, 101 100 -1, 101 101 4, 100 100 9)))"
wkt = geometry.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# test empty list
geometries = []
geometry = QgsGeometry.collectGeometry(geometries)
assert geometry.isNull(), "Expected geometry to be empty"
# check that the resulting geometry is multi
geometry = QgsGeometry.collectGeometry([QgsGeometry.fromWkt('Point (0 0)')])
assert geometry.isMultipart(), "Expected collected geometry to be multipart"
def testAddPart(self):
# add a part to a multipoint
points = [QgsPointXY(0, 0), QgsPointXY(1, 0)]
point = QgsGeometry.fromPointXY(points[0])
self.assertEqual(point.addPointsXY([points[1]]), 0)
expwkt = "MultiPoint ((0 0), (1 0))"
wkt = point.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# test adding a part with Z values
point = QgsGeometry.fromPointXY(points[0])
point.get().addZValue(4.0)
self.assertEqual(point.addPoints([QgsPoint(points[1][0], points[1][1], 3.0, wkbType=QgsWkbTypes.PointZ)]), 0)
expwkt = "MultiPointZ ((0 0 4), (1 0 3))"
wkt = point.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# 2-3 6-+-7
# | | | |
# 0-1 4 5 8-9
points = [
[QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 0), ],
[QgsPointXY(3, 0), QgsPointXY(3, 1), QgsPointXY(5, 1), QgsPointXY(5, 0), QgsPointXY(6, 0), ]
]
polyline = QgsGeometry.fromPolylineXY(points[0])
self.assertEqual(polyline.addPointsXY(points[1][0:1]), QgsGeometry.InvalidInputGeometryType,
"addPoints with one point line unexpectedly succeeded.")
self.assertEqual(polyline.addPointsXY(points[1][0:2]), QgsGeometry.Success,
"addPoints with two point line failed.")
expwkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 0), (3 0, 3 1))"
wkt = polyline.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
polyline = QgsGeometry.fromPolylineXY(points[0])
self.assertEqual(polyline.addPointsXY(points[1]), QgsGeometry.Success,
"addPoints with %d point line failed." % len(points[1]))
expwkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 0), (3 0, 3 1, 5 1, 5 0, 6 0))"
wkt = polyline.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# test adding a part with Z values
polyline = QgsGeometry.fromPolylineXY(points[0])
polyline.get().addZValue(4.0)
points2 = [QgsPoint(p[0], p[1], 3.0, wkbType=QgsWkbTypes.PointZ) for p in points[1]]
self.assertEqual(polyline.addPoints(points2), QgsGeometry.Success)
expwkt = "MultiLineStringZ ((0 0 4, 1 0 4, 1 1 4, 2 1 4, 2 0 4),(3 0 3, 3 1 3, 5 1 3, 5 0 3, 6 0 3))"
wkt = polyline.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# 5-+-4 0-+-9
# | | | |
# | 2-3 1-2 |
# | | | |
# 0-1 7-8
points = [
[[QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 2),
QgsPointXY(0, 2), QgsPointXY(0, 0), ]],
[[QgsPointXY(4, 0), QgsPointXY(5, 0), QgsPointXY(5, 2), QgsPointXY(3, 2), QgsPointXY(3, 1),
QgsPointXY(4, 1), QgsPointXY(4, 0), ]]
]
polygon = QgsGeometry.fromPolygonXY(points[0])
self.assertEqual(polygon.addPointsXY(points[1][0][0:1]), QgsGeometry.InvalidInputGeometryType,
"addPoints with one point ring unexpectedly succeeded.")
self.assertEqual(polygon.addPointsXY(points[1][0][0:2]), QgsGeometry.InvalidInputGeometryType,
"addPoints with two point ring unexpectedly succeeded.")
self.assertEqual(polygon.addPointsXY(points[1][0][0:3]), QgsGeometry.InvalidInputGeometryType,
"addPoints with unclosed three point ring unexpectedly succeeded.")
self.assertEqual(polygon.addPointsXY([QgsPointXY(4, 0), QgsPointXY(5, 0), QgsPointXY(4, 0)]),
QgsGeometry.InvalidInputGeometryType,
"addPoints with 'closed' three point ring unexpectedly succeeded.")
self.assertEqual(polygon.addPointsXY(points[1][0]), QgsGeometry.Success, "addPoints failed")
expwkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
mp = QgsGeometry.fromMultiPolygonXY(points[:1])
p = QgsGeometry.fromPolygonXY(points[1])
self.assertEqual(mp.addPartGeometry(p), QgsGeometry.Success)
wkt = mp.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
mp = QgsGeometry.fromMultiPolygonXY(points[:1])
mp2 = QgsGeometry.fromMultiPolygonXY(points[1:])
self.assertEqual(mp.addPartGeometry(mp2), QgsGeometry.Success)
wkt = mp.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# test adding a part with Z values
polygon = QgsGeometry.fromPolygonXY(points[0])
polygon.get().addZValue(4.0)
points2 = [QgsPoint(pi[0], pi[1], 3.0, wkbType=QgsWkbTypes.PointZ) for pi in points[1][0]]
self.assertEqual(polygon.addPoints(points2), QgsGeometry.Success)
expwkt = "MultiPolygonZ (((0 0 4, 1 0 4, 1 1 4, 2 1 4, 2 2 4, 0 2 4, 0 0 4)),((4 0 3, 5 0 3, 5 2 3, 3 2 3, 3 1 3, 4 1 3, 4 0 3)))"
wkt = polygon.asWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# test adding a part to a multisurface
geom = QgsGeometry.fromWkt('MultiSurface(((0 0,0 1,1 1,0 0)))')
g2 = QgsGeometry.fromWkt('CurvePolygon ((0 0,0 1,1 1,0 0))')
geom.addPart(g2.get().clone())
wkt = geom.asWkt()
expwkt = 'MultiSurface (Polygon ((0 0, 0 1, 1 1, 0 0)),CurvePolygon ((0 0, 0 1, 1 1, 0 0)))'
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# test adding a multisurface to a multisurface
geom = QgsGeometry.fromWkt('MultiSurface(((20 0,20 1,21 1,20 0)))')
g2 = QgsGeometry.fromWkt('MultiSurface (Polygon ((0 0, 0 1, 1 1, 0 0)),CurvePolygon ((0 0, 0 1, 1 1, 0 0)))')
geom.addPart(g2.get().clone())
wkt = geom.asWkt()
expwkt = 'MultiSurface (Polygon ((20 0, 20 1, 21 1, 20 0)),Polygon ((0 0, 0 1, 1 1, 0 0)),CurvePolygon ((0 0, 0 1, 1 1, 0 0)))'
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# Test adding parts to empty geometry, should become first part
empty = QgsGeometry()
# if not default type specified, addPart should fail
result = empty.addPointsXY([QgsPointXY(4, 0)])
assert result != QgsGeometry.Success, 'Got return code {}'.format(result)
result = empty.addPointsXY([QgsPointXY(4, 0)], QgsWkbTypes.PointGeometry)
self.assertEqual(result, QgsGeometry.Success, 'Got return code {}'.format(result))
wkt = empty.asWkt()
expwkt = 'MultiPoint ((4 0))'
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
result = empty.addPointsXY([QgsPointXY(5, 1)])
self.assertEqual(result, QgsGeometry.Success, 'Got return code {}'.format(result))
wkt = empty.asWkt()
expwkt = 'MultiPoint ((4 0),(5 1))'
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# next try with lines
empty = QgsGeometry()
result = empty.addPointsXY(points[0][0], QgsWkbTypes.LineGeometry)
self.assertEqual(result, QgsGeometry.Success, 'Got return code {}'.format(result))
wkt = empty.asWkt()
expwkt = 'MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))'
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
result = empty.addPointsXY(points[1][0])
self.assertEqual(result, QgsGeometry.Success, 'Got return code {}'.format(result))
wkt = empty.asWkt()
expwkt = 'MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0),(4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0))'
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# finally try with polygons
empty = QgsGeometry()
result = empty.addPointsXY(points[0][0], QgsWkbTypes.PolygonGeometry)
self.assertEqual(result, QgsGeometry.Success, 'Got return code {}'.format(result))
wkt = empty.asWkt()
expwkt = 'MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)))'
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
result = empty.addPointsXY(points[1][0])
self.assertEqual(result, QgsGeometry.Success, 'Got return code {}'.format(result))
wkt = empty.asWkt()
expwkt = 'MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))'
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
def testConvertToType(self):
# 5-+-4 0-+-9 13-+-+-12
# | | | | | |
# | 2-3 1-2 | + 18-17 +
# | | | | | | | |
# 0-1 7-8 + 15-16 +
# | |
# 10-+-+-11
points = [
[[QgsPointXY(0, 0), QgsPointXY(1, 0), QgsPointXY(1, 1), QgsPointXY(2, 1), QgsPointXY(2, 2),
QgsPointXY(0, 2), QgsPointXY(0, 0)], ],
[[QgsPointXY(4, 0), QgsPointXY(5, 0), QgsPointXY(5, 2), QgsPointXY(3, 2), QgsPointXY(3, 1),
QgsPointXY(4, 1), QgsPointXY(4, 0)], ],
[[QgsPointXY(10, 0), QgsPointXY(13, 0), QgsPointXY(13, 3), QgsPointXY(10, 3), QgsPointXY(10, 0)],
[QgsPointXY(11, 1), QgsPointXY(12, 1), QgsPointXY(12, 2), QgsPointXY(11, 2), QgsPointXY(11, 1)]]
]
# ####### TO POINT ########
# POINT TO POINT
point = QgsGeometry.fromPointXY(QgsPointXY(1, 1))
wkt = point.convertToType(QgsWkbTypes.PointGeometry, False).asWkt()
expWkt = "Point (1 1)"
assert compareWkt(expWkt, wkt), "convertToType failed: from point to point. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# POINT TO MultiPoint
wkt = point.convertToType(QgsWkbTypes.PointGeometry, True).asWkt()
expWkt = "MultiPoint ((1 1))"
assert compareWkt(expWkt, wkt), "convertToType failed: from point to multipoint. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# LINE TO MultiPoint
line = QgsGeometry.fromPolylineXY(points[0][0])
wkt = line.convertToType(QgsWkbTypes.PointGeometry, True).asWkt()
expWkt = "MultiPoint ((0 0),(1 0),(1 1),(2 1),(2 2),(0 2),(0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from line to multipoint. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# MULTILINE TO MultiPoint
multiLine = QgsGeometry.fromMultiPolylineXY(points[2])
wkt = multiLine.convertToType(QgsWkbTypes.PointGeometry, True).asWkt()
expWkt = "MultiPoint ((10 0),(13 0),(13 3),(10 3),(10 0),(11 1),(12 1),(12 2),(11 2),(11 1))"
assert compareWkt(expWkt,
wkt), "convertToType failed: from multiline to multipoint. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# Polygon TO MultiPoint
polygon = QgsGeometry.fromPolygonXY(points[0])
wkt = polygon.convertToType(QgsWkbTypes.PointGeometry, True).asWkt()
expWkt = "MultiPoint ((0 0),(1 0),(1 1),(2 1),(2 2),(0 2),(0 0))"
assert compareWkt(expWkt,
wkt), "convertToType failed: from poylgon to multipoint. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# MultiPolygon TO MultiPoint
multiPolygon = QgsGeometry.fromMultiPolygonXY(points)
wkt = multiPolygon.convertToType(QgsWkbTypes.PointGeometry, True).asWkt()
expWkt = "MultiPoint ((0 0),(1 0),(1 1),(2 1),(2 2),(0 2),(0 0),(4 0),(5 0),(5 2),(3 2),(3 1),(4 1),(4 0),(10 0),(13 0),(13 3),(10 3),(10 0),(11 1),(12 1),(12 2),(11 2),(11 1))"
assert compareWkt(expWkt,
wkt), "convertToType failed: from multipoylgon to multipoint. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# ####### TO LINE ########
# POINT TO LINE
point = QgsGeometry.fromPointXY(QgsPointXY(1, 1))
self.assertFalse(point.convertToType(QgsWkbTypes.LineGeometry,
False)), "convertToType with a point should return a null geometry"
# MultiPoint TO LINE
multipoint = QgsGeometry.fromMultiPointXY(points[0][0])
wkt = multipoint.convertToType(QgsWkbTypes.LineGeometry, False).asWkt()
expWkt = "LineString (0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)"
assert compareWkt(expWkt, wkt), "convertToType failed: from multipoint to line. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# MultiPoint TO MULTILINE
multipoint = QgsGeometry.fromMultiPointXY(points[0][0])
wkt = multipoint.convertToType(QgsWkbTypes.LineGeometry, True).asWkt()
expWkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))"
assert compareWkt(expWkt,
wkt), "convertToType failed: from multipoint to multiline. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# MULTILINE (which has a single part) TO LINE
multiLine = QgsGeometry.fromMultiPolylineXY(points[0])
wkt = multiLine.convertToType(QgsWkbTypes.LineGeometry, False).asWkt()
expWkt = "LineString (0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)"
assert compareWkt(expWkt, wkt), "convertToType failed: from multiline to line. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# LINE TO MULTILINE
line = QgsGeometry.fromPolylineXY(points[0][0])
wkt = line.convertToType(QgsWkbTypes.LineGeometry, True).asWkt()
expWkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from line to multiline. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# Polygon TO LINE
polygon = QgsGeometry.fromPolygonXY(points[0])
wkt = polygon.convertToType(QgsWkbTypes.LineGeometry, False).asWkt()
expWkt = "LineString (0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)"
assert compareWkt(expWkt, wkt), "convertToType failed: from polygon to line. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# Polygon TO MULTILINE
polygon = QgsGeometry.fromPolygonXY(points[0])
wkt = polygon.convertToType(QgsWkbTypes.LineGeometry, True).asWkt()
expWkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from polygon to multiline. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# Polygon with ring TO MULTILINE
polygon = QgsGeometry.fromPolygonXY(points[2])
wkt = polygon.convertToType(QgsWkbTypes.LineGeometry, True).asWkt()
expWkt = "MultiLineString ((10 0, 13 0, 13 3, 10 3, 10 0), (11 1, 12 1, 12 2, 11 2, 11 1))"
assert compareWkt(expWkt,
wkt), "convertToType failed: from polygon with ring to multiline. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# MultiPolygon (which has a single part) TO LINE
multiPolygon = QgsGeometry.fromMultiPolygonXY([points[0]])
wkt = multiPolygon.convertToType(QgsWkbTypes.LineGeometry, False).asWkt()
expWkt = "LineString (0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)"
assert compareWkt(expWkt,
wkt), "convertToType failed: from multipolygon to multiline. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# MultiPolygon TO MULTILINE
multiPolygon = QgsGeometry.fromMultiPolygonXY(points)
wkt = multiPolygon.convertToType(QgsWkbTypes.LineGeometry, True).asWkt()
expWkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0), (4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0), (10 0, 13 0, 13 3, 10 3, 10 0), (11 1, 12 1, 12 2, 11 2, 11 1))"
assert compareWkt(expWkt,
wkt), "convertToType failed: from multipolygon to multiline. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# ####### TO Polygon ########
# MultiPoint TO Polygon
multipoint = QgsGeometry.fromMultiPointXY(points[0][0])
wkt = multipoint.convertToType(QgsWkbTypes.PolygonGeometry, False).asWkt()
expWkt = "Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))"
assert compareWkt(expWkt,
wkt), "convertToType failed: from multipoint to polygon. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# MultiPoint TO MultiPolygon
multipoint = QgsGeometry.fromMultiPointXY(points[0][0])
wkt = multipoint.convertToType(QgsWkbTypes.PolygonGeometry, True).asWkt()
expWkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)))"
assert compareWkt(expWkt,
wkt), "convertToType failed: from multipoint to multipolygon. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# LINE TO Polygon
line = QgsGeometry.fromPolylineXY(points[0][0])
wkt = line.convertToType(QgsWkbTypes.PolygonGeometry, False).asWkt()
expWkt = "Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from line to polygon. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# LINE ( 3 vertices, with first = last ) TO Polygon
line = QgsGeometry.fromPolylineXY([QgsPointXY(1, 1), QgsPointXY(0, 0), QgsPointXY(1, 1)])
self.assertFalse(line.convertToType(QgsWkbTypes.PolygonGeometry, False),
"convertToType to polygon of a 3 vertices lines with first and last vertex identical should return a null geometry")
# MULTILINE ( with a part of 3 vertices, with first = last ) TO MultiPolygon
multiline = QgsGeometry.fromMultiPolylineXY(
[points[0][0], [QgsPointXY(1, 1), QgsPointXY(0, 0), QgsPointXY(1, 1)]])
self.assertFalse(multiline.convertToType(QgsWkbTypes.PolygonGeometry, True),
"convertToType to polygon of a 3 vertices lines with first and last vertex identical should return a null geometry")
# LINE TO MultiPolygon
line = QgsGeometry.fromPolylineXY(points[0][0])
wkt = line.convertToType(QgsWkbTypes.PolygonGeometry, True).asWkt()
expWkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)))"
assert compareWkt(expWkt, wkt), "convertToType failed: from line to multipolygon. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# MULTILINE (which has a single part) TO Polygon
multiLine = QgsGeometry.fromMultiPolylineXY(points[0])
wkt = multiLine.convertToType(QgsWkbTypes.PolygonGeometry, False).asWkt()
expWkt = "Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from multiline to polygon. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# MULTILINE TO MultiPolygon
multiLine = QgsGeometry.fromMultiPolylineXY([points[0][0], points[1][0]])
wkt = multiLine.convertToType(QgsWkbTypes.PolygonGeometry, True).asWkt()
expWkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))"
assert compareWkt(expWkt,
wkt), "convertToType failed: from multiline to multipolygon. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# Polygon TO MultiPolygon
polygon = QgsGeometry.fromPolygonXY(points[0])
wkt = polygon.convertToType(QgsWkbTypes.PolygonGeometry, True).asWkt()
expWkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)))"
assert compareWkt(expWkt,
wkt), "convertToType failed: from polygon to multipolygon. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# MultiPolygon (which has a single part) TO Polygon
multiPolygon = QgsGeometry.fromMultiPolygonXY([points[0]])
wkt = multiPolygon.convertToType(QgsWkbTypes.PolygonGeometry, False).asWkt()
expWkt = "Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from multiline to polygon. Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
def testRegression13053(self):
""" See https://github.com/qgis/QGIS/issues/21125 """
p = QgsGeometry.fromWkt(
'MULTIPOLYGON(((62.0 18.0, 62.0 19.0, 63.0 19.0, 63.0 18.0, 62.0 18.0)), ((63.0 19.0, 63.0 20.0, 64.0 20.0, 64.0 19.0, 63.0 19.0)))')
assert p is not None
expWkt = 'MultiPolygon (((62 18, 62 19, 63 19, 63 18, 62 18)),((63 19, 63 20, 64 20, 64 19, 63 19)))'
wkt = p.asWkt()
assert compareWkt(expWkt, wkt), "testRegression13053 failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def testRegression13055(self):
""" See https://github.com/qgis/QGIS/issues/21127
Testing that invalid WKT with z values but not using PolygonZ is still parsed
by QGIS.
"""
p = QgsGeometry.fromWkt('Polygon((0 0 0, 0 1 0, 1 1 0, 0 0 0 ))')
assert p is not None
expWkt = 'PolygonZ ((0 0 0, 0 1 0, 1 1 0, 0 0 0 ))'
wkt = p.asWkt()
assert compareWkt(expWkt, wkt), "testRegression13055 failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def testRegression13274(self):
""" See https://github.com/qgis/QGIS/issues/21334
Testing that two combined linestrings produce another line string if possible
"""
a = QgsGeometry.fromWkt('LineString (0 0, 1 0)')
b = QgsGeometry.fromWkt('LineString (1 0, 2 0)')
c = a.combine(b)
expWkt = 'LineString (0 0, 1 0, 2 0)'
wkt = c.asWkt()
assert compareWkt(expWkt, wkt), "testRegression13274 failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def testReshape(self):
""" Test geometry reshaping """
# no overlap
g = QgsGeometry.fromWkt('LineString (0 0, 5 0, 5 1, 6 1, 6 0, 7 0)')
self.assertEqual(g.reshapeGeometry(QgsLineString([QgsPoint(4, 2), QgsPoint(7, 2)])), 0)
expWkt = 'LineString (0 0, 5 0, 5 1, 6 1, 6 0, 7 0)'
wkt = g.asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "testReshape failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
g = QgsGeometry.fromWkt('Polygon ((0 0, 1 0, 1 1, 0 1, 0 0))')
g.reshapeGeometry(QgsLineString([QgsPoint(0, 1.5), QgsPoint(1.5, 0)]))
expWkt = 'Polygon ((0.5 1, 0 1, 0 0, 1 0, 1 0.5, 0.5 1))'
wkt = g.asWkt()
assert compareWkt(expWkt, wkt), "testReshape failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# Test reshape a geometry involving the first/last vertex (https://github.com/qgis/QGIS/issues/22422)
g.reshapeGeometry(QgsLineString([QgsPoint(0.5, 1), QgsPoint(0, 0.5)]))
expWkt = 'Polygon ((0 0.5, 0 0, 1 0, 1 0.5, 0.5 1, 0 0.5))'
wkt = g.asWkt()
assert compareWkt(expWkt, wkt), "testReshape failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# Test reshape a polygon with a line starting or ending at the polygon's first vertex, no change expexted
g = QgsGeometry.fromWkt('Polygon ((0 0, 1 0, 1 1, 0 1, 0 0))')
expWkt = g.asWkt()
g.reshapeGeometry(QgsLineString([QgsPoint(0, 0), QgsPoint(-1, -1)]))
self.assertTrue(compareWkt(g.asWkt(), expWkt),
"testReshape failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
# Test reshape a polygon with a line starting or ending at the polygon's first vertex
g = QgsGeometry.fromWkt('Polygon ((0 0, 1 0, 1 1, 0 1, 0 0))')
self.assertEqual(g.reshapeGeometry(QgsLineString([QgsPoint(0, 0), QgsPoint(0.5, 0.5), QgsPoint(0, 1)])),
QgsGeometry.Success)
expWkt = 'Polygon ((0 0, 1 0, 1 1, 0 1, 0.5 0.5, 0 0))'
wkt = g.asWkt()
self.assertTrue(compareWkt(wkt, expWkt),
"testReshape failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
# Test reshape a line from first/last vertex
g = QgsGeometry.fromWkt('LineString (0 0, 5 0, 5 1)')
# extend start
self.assertEqual(g.reshapeGeometry(QgsLineString([QgsPoint(0, 0), QgsPoint(-1, 0)])), 0)
expWkt = 'LineString (-1 0, 0 0, 5 0, 5 1)'
wkt = g.asWkt()
assert compareWkt(expWkt, wkt), "testReshape failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# extend end
self.assertEqual(g.reshapeGeometry(QgsLineString([QgsPoint(5, 1), QgsPoint(10, 1), QgsPoint(10, 2)])), 0)
expWkt = 'LineString (-1 0, 0 0, 5 0, 5 1, 10 1, 10 2)'
wkt = g.asWkt()
assert compareWkt(expWkt, wkt), "testReshape failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# test with reversed lines
g = QgsGeometry.fromWkt('LineString (0 0, 5 0, 5 1)')
# extend start
self.assertEqual(g.reshapeGeometry(QgsLineString([QgsPoint(-1, 0), QgsPoint(0, 0)])), 0)
expWkt = 'LineString (-1 0, 0 0, 5 0, 5 1)'
wkt = g.asWkt()
assert compareWkt(expWkt, wkt), "testReshape failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# extend end
self.assertEqual(g.reshapeGeometry(QgsLineString([QgsPoint(10, 2), QgsPoint(10, 1), QgsPoint(5, 1)])), 0)
expWkt = 'LineString (-1 0, 0 0, 5 0, 5 1, 10 1, 10 2)'
wkt = g.asWkt()
assert compareWkt(expWkt, wkt), "testReshape failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# reshape where reshape line exactly overlaps some portions of geometry
g = QgsGeometry.fromWkt('LineString (0 0, 5 0, 5 1, 6 1, 6 0, 7 0)')
self.assertEqual(g.reshapeGeometry(QgsLineString([QgsPoint(2, 0), QgsPoint(6, 0)])), 0)
expWkt = 'LineString (0 0, 2 0, 5 0, 6 0, 7 0)'
wkt = g.asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "testReshape failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
g = QgsGeometry.fromWkt('LineString (0 0, 5 0, 5 1, 6 1, 6 0, 7 0)')
self.assertEqual(g.reshapeGeometry(QgsLineString([QgsPoint(5, 0), QgsPoint(7, 0)])), 0)
expWkt = 'LineString (0 0, 5 0, 6 0, 7 0)'
wkt = g.asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "testReshape failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
# reshape line overlaps at both start and end
g = QgsGeometry.fromWkt('LineString (0 0, 5 0, 5 1, 6 1, 6 0, 7 0)')
self.assertEqual(g.reshapeGeometry(QgsLineString([QgsPoint(4, 0), QgsPoint(7, 0)])), 0)
expWkt = 'LineString (0 0, 4 0, 5 0, 6 0, 7 0)'
wkt = g.asWkt()
self.assertTrue(compareWkt(expWkt, wkt), "testReshape failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
# test that tolerance is correctly handled
g = QgsGeometry.fromWkt(
'LineString(152.96370660521466789 -25.60915858374441356, 152.96370887800003402 -25.60912889999996978, 152.9640088780000724 -25.60858889999996535, 152.96423077601289719 -25.60858080133134962, 152.96423675797717578 -25.60854355430449658, 152.96427575123991005 -25.60857916087011432, 152.96537884400004259 -25.60853889999992106, 152.96576355343805176 -25.60880035169972047)')
self.assertEqual(g.reshapeGeometry(QgsLineString([QgsPoint(152.9634281, -25.6079985),
QgsPoint(152.9640088780000724, -25.60858889999996535),
QgsPoint(152.96537884400004259, -25.60853889999992106),
QgsPoint(152.9655739, -25.6083169)])), 0)
expWkt = 'LineString (152.96371 -25.60916, 152.96371 -25.60913, 152.96401 -25.60859, 152.96423 -25.60858, 152.96423 -25.60858, 152.96428 -25.60858, 152.96538 -25.60854, 152.96576 -25.6088)'
wkt = g.asWkt(5)
self.assertTrue(compareWkt(expWkt, wkt), "testReshape failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
def testConvertToMultiType(self):
""" Test converting geometries to multi type """
point = QgsGeometry.fromWkt('Point (1 2)')
assert point.convertToMultiType()
expWkt = 'MultiPoint ((1 2))'
wkt = point.asWkt()
assert compareWkt(expWkt, wkt), "testConvertToMultiType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# test conversion of MultiPoint
assert point.convertToMultiType()
assert compareWkt(expWkt, wkt), "testConvertToMultiType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
line = QgsGeometry.fromWkt('LineString (1 0, 2 0)')
assert line.convertToMultiType()
expWkt = 'MultiLineString ((1 0, 2 0))'
wkt = line.asWkt()
assert compareWkt(expWkt, wkt), "testConvertToMultiType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# test conversion of MultiLineString
assert line.convertToMultiType()
assert compareWkt(expWkt, wkt), "testConvertToMultiType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
poly = QgsGeometry.fromWkt('Polygon ((1 0, 2 0, 2 1, 1 1, 1 0))')
assert poly.convertToMultiType()
expWkt = 'MultiPolygon (((1 0, 2 0, 2 1, 1 1, 1 0)))'
wkt = poly.asWkt()
assert compareWkt(expWkt, wkt), "testConvertToMultiType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# test conversion of MultiPolygon
assert poly.convertToMultiType()
assert compareWkt(expWkt, wkt), "testConvertToMultiType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
def testConvertToSingleType(self):
""" Test converting geometries to single type """
point = QgsGeometry.fromWkt('MultiPoint ((1 2),(2 3))')
assert point.convertToSingleType()
expWkt = 'Point (1 2)'
wkt = point.asWkt()
assert compareWkt(expWkt, wkt), "testConvertToSingleType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# test conversion of Point
assert point.convertToSingleType()
assert compareWkt(expWkt, wkt), "testConvertToSingleType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
line = QgsGeometry.fromWkt('MultiLineString ((1 0, 2 0),(2 3, 4 5))')
assert line.convertToSingleType()
expWkt = 'LineString (1 0, 2 0)'
wkt = line.asWkt()
assert compareWkt(expWkt, wkt), "testConvertToSingleType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# test conversion of LineString
assert line.convertToSingleType()
assert compareWkt(expWkt, wkt), "testConvertToSingleType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
poly = QgsGeometry.fromWkt('MultiPolygon (((1 0, 2 0, 2 1, 1 1, 1 0)),((2 3,2 4, 3 4, 3 3, 2 3)))')
assert poly.convertToSingleType()
expWkt = 'Polygon ((1 0, 2 0, 2 1, 1 1, 1 0))'
wkt = poly.asWkt()
assert compareWkt(expWkt, wkt), "testConvertToSingleType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# test conversion of Polygon
assert poly.convertToSingleType()
assert compareWkt(expWkt, wkt), "testConvertToSingleType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
def testAddZValue(self):
""" Test adding z dimension to geometries """
# circular string
geom = QgsGeometry.fromWkt('CircularString (1 5, 6 2, 7 3)')
assert geom.constGet().addZValue(2)
self.assertEqual(geom.constGet().wkbType(), QgsWkbTypes.CircularStringZ)
expWkt = 'CircularStringZ (1 5 2, 6 2 2, 7 3 2)'
wkt = geom.asWkt()
assert compareWkt(expWkt, wkt), "addZValue to CircularString failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# compound curve
geom = QgsGeometry.fromWkt(
'CompoundCurve ((5 3, 5 13),CircularString (5 13, 7 15, 9 13),(9 13, 9 3),CircularString (9 3, 7 1, 5 3))')
assert geom.constGet().addZValue(2)
self.assertEqual(geom.constGet().wkbType(), QgsWkbTypes.CompoundCurveZ)
expWkt = 'CompoundCurveZ ((5 3 2, 5 13 2),CircularStringZ (5 13 2, 7 15 2, 9 13 2),(9 13 2, 9 3 2),CircularStringZ (9 3 2, 7 1 2, 5 3 2))'
wkt = geom.asWkt()
assert compareWkt(expWkt, wkt), "addZValue to CompoundCurve failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# curve polygon
geom = QgsGeometry.fromWkt('Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))')
assert geom.constGet().addZValue(3)
self.assertEqual(geom.constGet().wkbType(), QgsWkbTypes.PolygonZ)
self.assertEqual(geom.wkbType(), QgsWkbTypes.PolygonZ)
expWkt = 'PolygonZ ((0 0 3, 1 0 3, 1 1 3, 2 1 3, 2 2 3, 0 2 3, 0 0 3))'
wkt = geom.asWkt()
assert compareWkt(expWkt, wkt), "addZValue to CurvePolygon failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# geometry collection
geom = QgsGeometry.fromWkt('MultiPoint ((1 2),(2 3))')
assert geom.constGet().addZValue(4)
self.assertEqual(geom.constGet().wkbType(), QgsWkbTypes.MultiPointZ)
self.assertEqual(geom.wkbType(), QgsWkbTypes.MultiPointZ)
expWkt = 'MultiPointZ ((1 2 4),(2 3 4))'
wkt = geom.asWkt()
assert compareWkt(expWkt, wkt), "addZValue to GeometryCollection failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# LineString
geom = QgsGeometry.fromWkt('LineString (1 2, 2 3)')
assert geom.constGet().addZValue(4)
self.assertEqual(geom.constGet().wkbType(), QgsWkbTypes.LineStringZ)
self.assertEqual(geom.wkbType(), QgsWkbTypes.LineStringZ)
expWkt = 'LineStringZ (1 2 4, 2 3 4)'
wkt = geom.asWkt()
assert compareWkt(expWkt, wkt), "addZValue to LineString failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# Point
geom = QgsGeometry.fromWkt('Point (1 2)')
assert geom.constGet().addZValue(4)
self.assertEqual(geom.constGet().wkbType(), QgsWkbTypes.PointZ)
self.assertEqual(geom.wkbType(), QgsWkbTypes.PointZ)
expWkt = 'PointZ (1 2 4)'
wkt = geom.asWkt()
assert compareWkt(expWkt, wkt), "addZValue to Point failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def testAddMValue(self):
""" Test adding m dimension to geometries """
# circular string
geom = QgsGeometry.fromWkt('CircularString (1 5, 6 2, 7 3)')
assert geom.constGet().addMValue(2)
self.assertEqual(geom.constGet().wkbType(), QgsWkbTypes.CircularStringM)
expWkt = 'CircularStringM (1 5 2, 6 2 2, 7 3 2)'
wkt = geom.asWkt()
assert compareWkt(expWkt, wkt), "addMValue to CircularString failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# compound curve
geom = QgsGeometry.fromWkt(
'CompoundCurve ((5 3, 5 13),CircularString (5 13, 7 15, 9 13),(9 13, 9 3),CircularString (9 3, 7 1, 5 3))')
assert geom.constGet().addMValue(2)
self.assertEqual(geom.constGet().wkbType(), QgsWkbTypes.CompoundCurveM)
expWkt = 'CompoundCurveM ((5 3 2, 5 13 2),CircularStringM (5 13 2, 7 15 2, 9 13 2),(9 13 2, 9 3 2),CircularStringM (9 3 2, 7 1 2, 5 3 2))'
wkt = geom.asWkt()
assert compareWkt(expWkt, wkt), "addMValue to CompoundCurve failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# curve polygon
geom = QgsGeometry.fromWkt('Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))')
assert geom.constGet().addMValue(3)
self.assertEqual(geom.constGet().wkbType(), QgsWkbTypes.PolygonM)
expWkt = 'PolygonM ((0 0 3, 1 0 3, 1 1 3, 2 1 3, 2 2 3, 0 2 3, 0 0 3))'
wkt = geom.asWkt()
assert compareWkt(expWkt, wkt), "addMValue to CurvePolygon failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# geometry collection
geom = QgsGeometry.fromWkt('MultiPoint ((1 2),(2 3))')
assert geom.constGet().addMValue(4)
self.assertEqual(geom.constGet().wkbType(), QgsWkbTypes.MultiPointM)
expWkt = 'MultiPointM ((1 2 4),(2 3 4))'
wkt = geom.asWkt()
assert compareWkt(expWkt, wkt), "addMValue to GeometryCollection failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# LineString
geom = QgsGeometry.fromWkt('LineString (1 2, 2 3)')
assert geom.constGet().addMValue(4)
self.assertEqual(geom.constGet().wkbType(), QgsWkbTypes.LineStringM)
expWkt = 'LineStringM (1 2 4, 2 3 4)'
wkt = geom.asWkt()
assert compareWkt(expWkt, wkt), "addMValue to LineString failed: mismatch Expected:\n%s\nGot:\n%s\n" % (
expWkt, wkt)
# Point
geom = QgsGeometry.fromWkt('Point (1 2)')
assert geom.constGet().addMValue(4)
self.assertEqual(geom.constGet().wkbType(), QgsWkbTypes.PointM)
expWkt = 'PointM (1 2 4)'
wkt = geom.asWkt()
assert compareWkt(expWkt, wkt), "addMValue to Point failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def testDistanceToVertex(self):
""" Test distanceToVertex calculation """
g = QgsGeometry()
self.assertEqual(g.distanceToVertex(0), -1)
g = QgsGeometry.fromWkt('LineString ()')
self.assertEqual(g.distanceToVertex(0), -1)
g = QgsGeometry.fromWkt('Polygon ((0 0, 1 0, 1 1, 0 1, 0 0))')
self.assertEqual(g.distanceToVertex(0), 0)
self.assertEqual(g.distanceToVertex(1), 1)
self.assertEqual(g.distanceToVertex(2), 2)
self.assertEqual(g.distanceToVertex(3), 3)
self.assertEqual(g.distanceToVertex(4), 4)
self.assertEqual(g.distanceToVertex(5), -1)
def testTypeInformation(self):
""" Test type information """
types = [
(QgsCircularString, "CircularString", QgsWkbTypes.CircularString),
(QgsCompoundCurve, "CompoundCurve", QgsWkbTypes.CompoundCurve),
(QgsCurvePolygon, "CurvePolygon", QgsWkbTypes.CurvePolygon),
(QgsGeometryCollection, "GeometryCollection", QgsWkbTypes.GeometryCollection),
(QgsLineString, "LineString", QgsWkbTypes.LineString),
(QgsMultiCurve, "MultiCurve", QgsWkbTypes.MultiCurve),
(QgsMultiLineString, "MultiLineString", QgsWkbTypes.MultiLineString),
(QgsMultiPoint, "MultiPoint", QgsWkbTypes.MultiPoint),
(QgsMultiPolygon, "MultiPolygon", QgsWkbTypes.MultiPolygon),
(QgsMultiSurface, "MultiSurface", QgsWkbTypes.MultiSurface),
(QgsPoint, "Point", QgsWkbTypes.Point),
(QgsPolygon, "Polygon", QgsWkbTypes.Polygon),
]
for geomtype in types:
geom = geomtype[0]()
self.assertEqual(geom.geometryType(), geomtype[1])
self.assertEqual(geom.wkbType(), geomtype[2])
geom.clear()
self.assertEqual(geom.geometryType(), geomtype[1])
self.assertEqual(geom.wkbType(), geomtype[2])
clone = geom.clone()
self.assertEqual(clone.geometryType(), geomtype[1])
self.assertEqual(clone.wkbType(), geomtype[2])
def testRelates(self):
""" Test relationships between geometries. Note the bulk of these tests were taken from the PostGIS relate testdata """
with open(os.path.join(TEST_DATA_DIR, 'relates_data.csv'), 'r') as d:
for i, t in enumerate(d):
test_data = t.strip().split('|')
geom1 = QgsGeometry.fromWkt(test_data[0])
assert geom1, "Relates {} failed: could not create geom:\n{}\n".format(i + 1, test_data[0])
geom2 = QgsGeometry.fromWkt(test_data[1])
assert geom2, "Relates {} failed: could not create geom:\n{}\n".format(i + 1, test_data[1])
result = QgsGeometry.createGeometryEngine(geom1.constGet()).relate(geom2.constGet())
exp = test_data[2]
self.assertEqual(result, exp,
"Relates {} failed: mismatch Expected:\n{}\nGot:\n{}\nGeom1:\n{}\nGeom2:\n{}\n".format(
i + 1, exp, result, test_data[0], test_data[1]))
def testWkbTypes(self):
""" Test QgsWkbTypes methods """
# test singleType method
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.Unknown), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.Point), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.PointZ), QgsWkbTypes.PointZ)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.PointM), QgsWkbTypes.PointM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.PointZM), QgsWkbTypes.PointZM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiPoint), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiPointZ), QgsWkbTypes.PointZ)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiPointM), QgsWkbTypes.PointM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiPointZM), QgsWkbTypes.PointZM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.LineString), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.LineStringZ), QgsWkbTypes.LineStringZ)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.LineStringM), QgsWkbTypes.LineStringM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.LineStringZM), QgsWkbTypes.LineStringZM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiLineString), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiLineStringZ), QgsWkbTypes.LineStringZ)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiLineStringM), QgsWkbTypes.LineStringM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiLineStringZM), QgsWkbTypes.LineStringZM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.Polygon), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.PolygonZ), QgsWkbTypes.PolygonZ)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.PolygonM), QgsWkbTypes.PolygonM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.PolygonZM), QgsWkbTypes.PolygonZM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiPolygon), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiPolygonZ), QgsWkbTypes.PolygonZ)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiPolygonM), QgsWkbTypes.PolygonM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiPolygonZM), QgsWkbTypes.PolygonZM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.GeometryCollection), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.GeometryCollectionZ), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.GeometryCollectionM), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.GeometryCollectionZM), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.CircularString), QgsWkbTypes.CircularString)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.CircularStringZ), QgsWkbTypes.CircularStringZ)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.CircularStringM), QgsWkbTypes.CircularStringM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.CircularStringZM), QgsWkbTypes.CircularStringZM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.CompoundCurve), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.CompoundCurveZ), QgsWkbTypes.CompoundCurveZ)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.CompoundCurveM), QgsWkbTypes.CompoundCurveM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.CompoundCurveZM), QgsWkbTypes.CompoundCurveZM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.CurvePolygon), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.CurvePolygonZ), QgsWkbTypes.CurvePolygonZ)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.CurvePolygonM), QgsWkbTypes.CurvePolygonM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.CurvePolygonZM), QgsWkbTypes.CurvePolygonZM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiCurve), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiCurveZ), QgsWkbTypes.CompoundCurveZ)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiCurveM), QgsWkbTypes.CompoundCurveM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiCurveZM), QgsWkbTypes.CompoundCurveZM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiSurface), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiSurfaceZ), QgsWkbTypes.CurvePolygonZ)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiSurfaceM), QgsWkbTypes.CurvePolygonM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiSurfaceZM), QgsWkbTypes.CurvePolygonZM)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.NoGeometry), QgsWkbTypes.NoGeometry)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.Point25D), QgsWkbTypes.Point25D)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.LineString25D), QgsWkbTypes.LineString25D)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.Polygon25D), QgsWkbTypes.Polygon25D)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiPoint25D), QgsWkbTypes.Point25D)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiLineString25D), QgsWkbTypes.LineString25D)
self.assertEqual(QgsWkbTypes.singleType(QgsWkbTypes.MultiPolygon25D), QgsWkbTypes.Polygon25D)
# test multiType method
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.Unknown), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.Point), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.PointZ), QgsWkbTypes.MultiPointZ)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.PointM), QgsWkbTypes.MultiPointM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.PointZM), QgsWkbTypes.MultiPointZM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiPoint), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiPointZ), QgsWkbTypes.MultiPointZ)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiPointM), QgsWkbTypes.MultiPointM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiPointZM), QgsWkbTypes.MultiPointZM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.LineString), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.LineStringZ), QgsWkbTypes.MultiLineStringZ)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.LineStringM), QgsWkbTypes.MultiLineStringM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.LineStringZM), QgsWkbTypes.MultiLineStringZM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiLineString), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiLineStringZ), QgsWkbTypes.MultiLineStringZ)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiLineStringM), QgsWkbTypes.MultiLineStringM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiLineStringZM), QgsWkbTypes.MultiLineStringZM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.Polygon), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.PolygonZ), QgsWkbTypes.MultiPolygonZ)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.PolygonM), QgsWkbTypes.MultiPolygonM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.PolygonZM), QgsWkbTypes.MultiPolygonZM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiPolygon), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiPolygonZ), QgsWkbTypes.MultiPolygonZ)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiPolygonM), QgsWkbTypes.MultiPolygonM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiPolygonZM), QgsWkbTypes.MultiPolygonZM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.GeometryCollection), QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.GeometryCollectionZ), QgsWkbTypes.GeometryCollectionZ)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.GeometryCollectionM), QgsWkbTypes.GeometryCollectionM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.GeometryCollectionZM), QgsWkbTypes.GeometryCollectionZM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.CircularString), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.CircularStringZ), QgsWkbTypes.MultiCurveZ)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.CircularStringM), QgsWkbTypes.MultiCurveM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.CircularStringZM), QgsWkbTypes.MultiCurveZM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.CompoundCurve), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.CompoundCurveZ), QgsWkbTypes.MultiCurveZ)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.CompoundCurveM), QgsWkbTypes.MultiCurveM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.CompoundCurveZM), QgsWkbTypes.MultiCurveZM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.CurvePolygon), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.CurvePolygonZ), QgsWkbTypes.MultiSurfaceZ)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.CurvePolygonM), QgsWkbTypes.MultiSurfaceM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.CurvePolygonZM), QgsWkbTypes.MultiSurfaceZM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiCurve), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiCurveZ), QgsWkbTypes.MultiCurveZ)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiCurveM), QgsWkbTypes.MultiCurveM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiCurveZM), QgsWkbTypes.MultiCurveZM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiSurface), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiSurfaceZ), QgsWkbTypes.MultiSurfaceZ)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiSurfaceM), QgsWkbTypes.MultiSurfaceM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiSurfaceZM), QgsWkbTypes.MultiSurfaceZM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.NoGeometry), QgsWkbTypes.NoGeometry)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.Point25D), QgsWkbTypes.MultiPoint25D)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.LineString25D), QgsWkbTypes.MultiLineString25D)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.Polygon25D), QgsWkbTypes.MultiPolygon25D)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiPoint25D), QgsWkbTypes.MultiPoint25D)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiLineString25D), QgsWkbTypes.MultiLineString25D)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.MultiPolygon25D), QgsWkbTypes.MultiPolygon25D)
# until we have tin types, these should return multipolygons
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.Triangle), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.TriangleZ), QgsWkbTypes.MultiPolygonZ)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.TriangleM), QgsWkbTypes.MultiPolygonM)
self.assertEqual(QgsWkbTypes.multiType(QgsWkbTypes.TriangleZM), QgsWkbTypes.MultiPolygonZM)
# test curveType method
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.Unknown), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.Point), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.PointZ), QgsWkbTypes.PointZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.PointM), QgsWkbTypes.PointM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.PointZM), QgsWkbTypes.PointZM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiPoint), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiPointZ), QgsWkbTypes.MultiPointZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiPointM), QgsWkbTypes.MultiPointM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiPointZM), QgsWkbTypes.MultiPointZM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.LineString), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.LineStringZ), QgsWkbTypes.CompoundCurveZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.LineStringM), QgsWkbTypes.CompoundCurveM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.LineStringZM), QgsWkbTypes.CompoundCurveZM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiLineString), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiLineStringZ), QgsWkbTypes.MultiCurveZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiLineStringM), QgsWkbTypes.MultiCurveM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiLineStringZM), QgsWkbTypes.MultiCurveZM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.Polygon), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.PolygonZ), QgsWkbTypes.CurvePolygonZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.PolygonM), QgsWkbTypes.CurvePolygonM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.PolygonZM), QgsWkbTypes.CurvePolygonZM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiPolygon), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiPolygonZ), QgsWkbTypes.MultiSurfaceZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiPolygonM), QgsWkbTypes.MultiSurfaceM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiPolygonZM), QgsWkbTypes.MultiSurfaceZM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.GeometryCollection), QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.GeometryCollectionZ), QgsWkbTypes.GeometryCollectionZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.GeometryCollectionM), QgsWkbTypes.GeometryCollectionM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.GeometryCollectionZM), QgsWkbTypes.GeometryCollectionZM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.CircularString), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.CircularStringZ), QgsWkbTypes.CompoundCurveZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.CircularStringM), QgsWkbTypes.CompoundCurveM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.CircularStringZM), QgsWkbTypes.CompoundCurveZM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.CompoundCurve), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.CompoundCurveZ), QgsWkbTypes.CompoundCurveZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.CompoundCurveM), QgsWkbTypes.CompoundCurveM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.CompoundCurveZM), QgsWkbTypes.CompoundCurveZM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.CurvePolygon), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.CurvePolygonZ), QgsWkbTypes.CurvePolygonZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.CurvePolygonM), QgsWkbTypes.CurvePolygonM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.CurvePolygonZM), QgsWkbTypes.CurvePolygonZM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiCurve), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiCurveZ), QgsWkbTypes.MultiCurveZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiCurveM), QgsWkbTypes.MultiCurveM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiCurveZM), QgsWkbTypes.MultiCurveZM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiSurface), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiSurfaceZ), QgsWkbTypes.MultiSurfaceZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiSurfaceM), QgsWkbTypes.MultiSurfaceM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiSurfaceZM), QgsWkbTypes.MultiSurfaceZM)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.NoGeometry), QgsWkbTypes.NoGeometry)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.Point25D), QgsWkbTypes.MultiPoint25D)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.LineString25D), QgsWkbTypes.CompoundCurveZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.Polygon25D), QgsWkbTypes.CurvePolygonZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiPoint25D), QgsWkbTypes.MultiPoint25D)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiLineString25D), QgsWkbTypes.MultiCurveZ)
self.assertEqual(QgsWkbTypes.curveType(QgsWkbTypes.MultiPolygon25D), QgsWkbTypes.MultiSurfaceZ)
# test linearType method
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.Unknown), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.Point), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.PointZ), QgsWkbTypes.PointZ)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.PointM), QgsWkbTypes.PointM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.PointZM), QgsWkbTypes.PointZM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiPoint), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiPointZ), QgsWkbTypes.MultiPointZ)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiPointM), QgsWkbTypes.MultiPointM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiPointZM), QgsWkbTypes.MultiPointZM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.LineString), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.LineStringZ), QgsWkbTypes.LineStringZ)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.LineStringM), QgsWkbTypes.LineStringM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.LineStringZM), QgsWkbTypes.LineStringZM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiLineString), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiLineStringZ), QgsWkbTypes.MultiLineStringZ)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiLineStringM), QgsWkbTypes.MultiLineStringM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiLineStringZM), QgsWkbTypes.MultiLineStringZM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.Polygon), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.PolygonZ), QgsWkbTypes.PolygonZ)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.PolygonM), QgsWkbTypes.PolygonM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.PolygonZM), QgsWkbTypes.PolygonZM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiPolygon), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiPolygonZ), QgsWkbTypes.MultiPolygonZ)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiPolygonM), QgsWkbTypes.MultiPolygonM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiPolygonZM), QgsWkbTypes.MultiPolygonZM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.GeometryCollection), QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.GeometryCollectionZ), QgsWkbTypes.GeometryCollectionZ)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.GeometryCollectionM), QgsWkbTypes.GeometryCollectionM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.GeometryCollectionZM), QgsWkbTypes.GeometryCollectionZM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.CircularString), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.CircularStringZ), QgsWkbTypes.LineStringZ)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.CircularStringM), QgsWkbTypes.LineStringM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.CircularStringZM), QgsWkbTypes.LineStringZM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.CompoundCurve), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.CompoundCurveZ), QgsWkbTypes.LineStringZ)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.CompoundCurveM), QgsWkbTypes.LineStringM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.CompoundCurveZM), QgsWkbTypes.LineStringZM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.CurvePolygon), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.CurvePolygonZ), QgsWkbTypes.PolygonZ)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.CurvePolygonM), QgsWkbTypes.PolygonM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.CurvePolygonZM), QgsWkbTypes.PolygonZM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiCurve), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiCurveZ), QgsWkbTypes.MultiLineStringZ)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiCurveM), QgsWkbTypes.MultiLineStringM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiCurveZM), QgsWkbTypes.MultiLineStringZM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiSurface), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiSurfaceZ), QgsWkbTypes.MultiPolygonZ)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiSurfaceM), QgsWkbTypes.MultiPolygonM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiSurfaceZM), QgsWkbTypes.MultiPolygonZM)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.NoGeometry), QgsWkbTypes.NoGeometry)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.Point25D), QgsWkbTypes.Point25D)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.LineString25D), QgsWkbTypes.LineString25D)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.Polygon25D), QgsWkbTypes.Polygon25D)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiPoint25D), QgsWkbTypes.MultiPoint25D)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiLineString25D), QgsWkbTypes.MultiLineString25D)
self.assertEqual(QgsWkbTypes.linearType(QgsWkbTypes.MultiPolygon25D), QgsWkbTypes.MultiPolygon25D)
# test flatType method
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.Unknown), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.Point), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.PointZ), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.PointM), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.PointZM), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiPoint), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiPointZ), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiPointM), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiPointZM), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.LineString), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.LineStringZ), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.LineStringM), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.LineStringZM), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiLineString), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiLineStringZ), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiLineStringM), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiLineStringZM), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.Polygon), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.PolygonZ), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.PolygonM), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.PolygonZM), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiPolygon), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiPolygonZ), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiPolygonM), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiPolygonZM), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.GeometryCollection), QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.GeometryCollectionZ), QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.GeometryCollectionM), QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.GeometryCollectionZM), QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.CircularString), QgsWkbTypes.CircularString)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.CircularStringZ), QgsWkbTypes.CircularString)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.CircularStringM), QgsWkbTypes.CircularString)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.CircularStringZM), QgsWkbTypes.CircularString)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.CompoundCurve), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.CompoundCurveZ), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.CompoundCurveM), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.CompoundCurveZM), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.CurvePolygon), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.CurvePolygonZ), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.CurvePolygonM), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.CurvePolygonZM), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiCurve), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiCurveZ), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiCurveM), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiCurveZM), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiSurface), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiSurfaceZ), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiSurfaceM), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiSurfaceZM), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.NoGeometry), QgsWkbTypes.NoGeometry)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.Point25D), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.LineString25D), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.Polygon25D), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiPoint25D), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiLineString25D), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.flatType(QgsWkbTypes.MultiPolygon25D), QgsWkbTypes.MultiPolygon)
# test geometryType method
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.Unknown), QgsWkbTypes.UnknownGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.Point), QgsWkbTypes.PointGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.PointZ), QgsWkbTypes.PointGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.PointM), QgsWkbTypes.PointGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.PointZM), QgsWkbTypes.PointGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiPoint), QgsWkbTypes.PointGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiPointZ), QgsWkbTypes.PointGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiPointM), QgsWkbTypes.PointGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiPointZM), QgsWkbTypes.PointGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.LineString), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.LineStringZ), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.LineStringM), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.LineStringZM), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiLineString), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiLineStringZ), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiLineStringM), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiLineStringZM), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.Polygon), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.PolygonZ), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.PolygonM), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.PolygonZM), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiPolygon), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiPolygonZ), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiPolygonM), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiPolygonZM), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.GeometryCollection), QgsWkbTypes.UnknownGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.GeometryCollectionZ), QgsWkbTypes.UnknownGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.GeometryCollectionM), QgsWkbTypes.UnknownGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.GeometryCollectionZM), QgsWkbTypes.UnknownGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.CircularString), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.CircularStringZ), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.CircularStringM), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.CircularStringZM), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.CompoundCurve), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.CompoundCurveZ), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.CompoundCurveM), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.CompoundCurveZM), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.CurvePolygon), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.CurvePolygonZ), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.CurvePolygonM), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.CurvePolygonZM), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiCurve), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiCurveZ), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiCurveM), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiCurveZM), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiSurface), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiSurfaceZ), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiSurfaceM), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiSurfaceZM), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.NoGeometry), QgsWkbTypes.NullGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.Point25D), QgsWkbTypes.PointGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.LineString25D), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.Polygon25D), QgsWkbTypes.PolygonGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiPoint25D), QgsWkbTypes.PointGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiLineString25D), QgsWkbTypes.LineGeometry)
self.assertEqual(QgsWkbTypes.geometryType(QgsWkbTypes.MultiPolygon25D), QgsWkbTypes.PolygonGeometry)
# test displayString method
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.Unknown), 'Unknown')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.Point), 'Point')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.PointZ), 'PointZ')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.PointM), 'PointM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.PointZM), 'PointZM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiPoint), 'MultiPoint')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiPointZ), 'MultiPointZ')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiPointM), 'MultiPointM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiPointZM), 'MultiPointZM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.LineString), 'LineString')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.LineStringZ), 'LineStringZ')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.LineStringM), 'LineStringM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.LineStringZM), 'LineStringZM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiLineString), 'MultiLineString')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiLineStringZ), 'MultiLineStringZ')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiLineStringM), 'MultiLineStringM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiLineStringZM), 'MultiLineStringZM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.Polygon), 'Polygon')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.PolygonZ), 'PolygonZ')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.PolygonM), 'PolygonM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.PolygonZM), 'PolygonZM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiPolygon), 'MultiPolygon')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiPolygonZ), 'MultiPolygonZ')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiPolygonM), 'MultiPolygonM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiPolygonZM), 'MultiPolygonZM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.GeometryCollection), 'GeometryCollection')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.GeometryCollectionZ), 'GeometryCollectionZ')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.GeometryCollectionM), 'GeometryCollectionM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.GeometryCollectionZM), 'GeometryCollectionZM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.CircularString), 'CircularString')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.CircularStringZ), 'CircularStringZ')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.CircularStringM), 'CircularStringM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.CircularStringZM), 'CircularStringZM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.CompoundCurve), 'CompoundCurve')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.CompoundCurveZ), 'CompoundCurveZ')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.CompoundCurveM), 'CompoundCurveM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.CompoundCurveZM), 'CompoundCurveZM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.CurvePolygon), 'CurvePolygon')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.CurvePolygonZ), 'CurvePolygonZ')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.CurvePolygonM), 'CurvePolygonM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.CurvePolygonZM), 'CurvePolygonZM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiCurve), 'MultiCurve')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiCurveZ), 'MultiCurveZ')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiCurveM), 'MultiCurveM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiCurveZM), 'MultiCurveZM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiSurface), 'MultiSurface')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiSurfaceZ), 'MultiSurfaceZ')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiSurfaceM), 'MultiSurfaceM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiSurfaceZM), 'MultiSurfaceZM')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.NoGeometry), 'NoGeometry')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.Point25D), 'Point25D')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.LineString25D), 'LineString25D')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.Polygon25D), 'Polygon25D')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiPoint25D), 'MultiPoint25D')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiLineString25D), 'MultiLineString25D')
self.assertEqual(QgsWkbTypes.displayString(QgsWkbTypes.MultiPolygon25D), 'MultiPolygon25D')
self.assertEqual(QgsWkbTypes.displayString(9999999), '')
# test parseType method
self.assertEqual(QgsWkbTypes.parseType('point( 1 2 )'), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.parseType('POINT( 1 2 )'), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.parseType(' point ( 1 2 ) '), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.parseType('point'), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.parseType('LINE STRING( 1 2, 3 4 )'), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.parseType('POINTZ( 1 2 )'), QgsWkbTypes.PointZ)
self.assertEqual(QgsWkbTypes.parseType('POINT z m'), QgsWkbTypes.PointZM)
self.assertEqual(QgsWkbTypes.parseType('bad'), QgsWkbTypes.Unknown)
# test wkbDimensions method
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.Unknown), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.Point), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.PointZ), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.PointM), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.PointZM), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiPoint), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiPointZ), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiPointM), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiPointZM), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.LineString), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.LineStringZ), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.LineStringM), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.LineStringZM), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiLineString), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiLineStringZ), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiLineStringM), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiLineStringZM), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.Polygon), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.PolygonZ), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.PolygonM), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.PolygonZM), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiPolygon), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiPolygonZ), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiPolygonM), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiPolygonZM), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.GeometryCollection), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.GeometryCollectionZ), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.GeometryCollectionM), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.GeometryCollectionZM), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.CircularString), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.CircularStringZ), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.CircularStringM), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.CircularStringZM), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.CompoundCurve), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.CompoundCurveZ), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.CompoundCurveM), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.CompoundCurveZM), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.CurvePolygon), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.CurvePolygonZ), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.CurvePolygonM), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.CurvePolygonZM), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiCurve), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiCurveZ), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiCurveM), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiCurveZM), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiSurface), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiSurfaceZ), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiSurfaceM), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiSurfaceZM), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.NoGeometry), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.Point25D), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.LineString25D), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.Polygon25D), 2)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiPoint25D), 0)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiLineString25D), 1)
self.assertEqual(QgsWkbTypes.wkbDimensions(QgsWkbTypes.MultiPolygon25D), 2)
# test coordDimensions method
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.Unknown), 0)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.Point), 2)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.PointZ), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.PointM), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.PointZM), 4)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiPoint), 2)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiPointZ), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiPointM), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiPointZM), 4)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.LineString), 2)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.LineStringZ), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.LineStringM), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.LineStringZM), 4)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiLineString), 2)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiLineStringZ), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiLineStringM), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiLineStringZM), 4)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.Polygon), 2)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.PolygonZ), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.PolygonM), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.PolygonZM), 4)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiPolygon), 2)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiPolygonZ), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiPolygonM), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiPolygonZM), 4)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.GeometryCollection), 2)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.GeometryCollectionZ), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.GeometryCollectionM), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.GeometryCollectionZM), 4)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.CircularString), 2)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.CircularStringZ), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.CircularStringM), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.CircularStringZM), 4)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.CompoundCurve), 2)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.CompoundCurveZ), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.CompoundCurveM), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.CompoundCurveZM), 4)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.CurvePolygon), 2)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.CurvePolygonZ), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.CurvePolygonM), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.CurvePolygonZM), 4)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiCurve), 2)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiCurveZ), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiCurveM), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiCurveZM), 4)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiSurface), 2)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiSurfaceZ), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiSurfaceM), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiSurfaceZM), 4)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.NoGeometry), 0)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.Point25D), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.LineString25D), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.Polygon25D), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiPoint25D), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiLineString25D), 3)
self.assertEqual(QgsWkbTypes.coordDimensions(QgsWkbTypes.MultiPolygon25D), 3)
# test isSingleType methods
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.Unknown)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.Point)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.LineString)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.Polygon)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiPoint)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiLineString)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiPolygon)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.GeometryCollection)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.CircularString)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.CompoundCurve)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.CurvePolygon)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiCurve)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiSurface)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.NoGeometry)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.PointZ)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.LineStringZ)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.PolygonZ)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiPointZ)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiLineStringZ)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiPolygonZ)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.GeometryCollectionZ)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.CircularStringZ)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.CompoundCurveZ)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.CurvePolygonZ)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiCurveZ)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiSurfaceZ)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.PointM)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.LineStringM)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.PolygonM)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiPointM)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiLineStringM)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiPolygonM)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.GeometryCollectionM)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.CircularStringM)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.CompoundCurveM)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.CurvePolygonM)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiCurveM)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiSurfaceM)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.PointZM)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.LineStringZM)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.PolygonZM)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiPointZM)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiLineStringZM)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiPolygonZM)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.GeometryCollectionZM)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.CircularStringZM)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.CompoundCurveZM)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.CurvePolygonZM)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiCurveZM)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiSurfaceZM)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.Point25D)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.LineString25D)
assert QgsWkbTypes.isSingleType(QgsWkbTypes.Polygon25D)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiPoint25D)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiLineString25D)
assert not QgsWkbTypes.isSingleType(QgsWkbTypes.MultiPolygon25D)
# test isMultiType methods
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.Unknown)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.Point)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.LineString)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.Polygon)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiPoint)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiLineString)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiPolygon)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.GeometryCollection)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.CircularString)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.CompoundCurve)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.CurvePolygon)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiCurve)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiSurface)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.NoGeometry)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.PointZ)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.LineStringZ)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.PolygonZ)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiPointZ)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiLineStringZ)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiPolygonZ)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.GeometryCollectionZ)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.CircularStringZ)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.CompoundCurveZ)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.CurvePolygonZ)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiCurveZ)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiSurfaceZ)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.PointM)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.LineStringM)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.PolygonM)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiPointM)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiLineStringM)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiPolygonM)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.GeometryCollectionM)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.CircularStringM)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.CompoundCurveM)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.CurvePolygonM)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiCurveM)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiSurfaceM)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.PointZM)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.LineStringZM)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.PolygonZM)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiPointZM)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiLineStringZM)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiPolygonZM)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.GeometryCollectionZM)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.CircularStringZM)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.CompoundCurveZM)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.CurvePolygonZM)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiCurveZM)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiSurfaceZM)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.Point25D)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.LineString25D)
assert not QgsWkbTypes.isMultiType(QgsWkbTypes.Polygon25D)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiPoint25D)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiLineString25D)
assert QgsWkbTypes.isMultiType(QgsWkbTypes.MultiPolygon25D)
# test isCurvedType methods
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.Unknown)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.Point)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.LineString)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.Polygon)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiPoint)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiLineString)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiPolygon)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.GeometryCollection)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.CircularString)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.CompoundCurve)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.CurvePolygon)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiCurve)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiSurface)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.NoGeometry)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.PointZ)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.LineStringZ)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.PolygonZ)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiPointZ)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiLineStringZ)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiPolygonZ)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.GeometryCollectionZ)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.CircularStringZ)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.CompoundCurveZ)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.CurvePolygonZ)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiCurveZ)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiSurfaceZ)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.PointM)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.LineStringM)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.PolygonM)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiPointM)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiLineStringM)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiPolygonM)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.GeometryCollectionM)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.CircularStringM)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.CompoundCurveM)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.CurvePolygonM)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiCurveM)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiSurfaceM)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.PointZM)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.LineStringZM)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.PolygonZM)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiPointZM)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiLineStringZM)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiPolygonZM)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.GeometryCollectionZM)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.CircularStringZM)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.CompoundCurveZM)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.CurvePolygonZM)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiCurveZM)
assert QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiSurfaceZM)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.Point25D)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.LineString25D)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.Polygon25D)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiPoint25D)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiLineString25D)
assert not QgsWkbTypes.isCurvedType(QgsWkbTypes.MultiPolygon25D)
# test hasZ methods
assert not QgsWkbTypes.hasZ(QgsWkbTypes.Unknown)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.Point)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.LineString)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.Polygon)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.MultiPoint)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.MultiLineString)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.MultiPolygon)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.GeometryCollection)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.CircularString)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.CompoundCurve)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.CurvePolygon)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.MultiCurve)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.MultiSurface)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.NoGeometry)
assert QgsWkbTypes.hasZ(QgsWkbTypes.PointZ)
assert QgsWkbTypes.hasZ(QgsWkbTypes.LineStringZ)
assert QgsWkbTypes.hasZ(QgsWkbTypes.PolygonZ)
assert QgsWkbTypes.hasZ(QgsWkbTypes.MultiPointZ)
assert QgsWkbTypes.hasZ(QgsWkbTypes.MultiLineStringZ)
assert QgsWkbTypes.hasZ(QgsWkbTypes.MultiPolygonZ)
assert QgsWkbTypes.hasZ(QgsWkbTypes.GeometryCollectionZ)
assert QgsWkbTypes.hasZ(QgsWkbTypes.CircularStringZ)
assert QgsWkbTypes.hasZ(QgsWkbTypes.CompoundCurveZ)
assert QgsWkbTypes.hasZ(QgsWkbTypes.CurvePolygonZ)
assert QgsWkbTypes.hasZ(QgsWkbTypes.MultiCurveZ)
assert QgsWkbTypes.hasZ(QgsWkbTypes.MultiSurfaceZ)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.PointM)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.LineStringM)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.PolygonM)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.MultiPointM)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.MultiLineStringM)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.MultiPolygonM)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.GeometryCollectionM)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.CircularStringM)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.CompoundCurveM)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.CurvePolygonM)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.MultiCurveM)
assert not QgsWkbTypes.hasZ(QgsWkbTypes.MultiSurfaceM)
assert QgsWkbTypes.hasZ(QgsWkbTypes.PointZM)
assert QgsWkbTypes.hasZ(QgsWkbTypes.LineStringZM)
assert QgsWkbTypes.hasZ(QgsWkbTypes.PolygonZM)
assert QgsWkbTypes.hasZ(QgsWkbTypes.MultiPointZM)
assert QgsWkbTypes.hasZ(QgsWkbTypes.MultiLineStringZM)
assert QgsWkbTypes.hasZ(QgsWkbTypes.MultiPolygonZM)
assert QgsWkbTypes.hasZ(QgsWkbTypes.GeometryCollectionZM)
assert QgsWkbTypes.hasZ(QgsWkbTypes.CircularStringZM)
assert QgsWkbTypes.hasZ(QgsWkbTypes.CompoundCurveZM)
assert QgsWkbTypes.hasZ(QgsWkbTypes.CurvePolygonZM)
assert QgsWkbTypes.hasZ(QgsWkbTypes.MultiCurveZM)
assert QgsWkbTypes.hasZ(QgsWkbTypes.MultiSurfaceZM)
assert QgsWkbTypes.hasZ(QgsWkbTypes.Point25D)
assert QgsWkbTypes.hasZ(QgsWkbTypes.LineString25D)
assert QgsWkbTypes.hasZ(QgsWkbTypes.Polygon25D)
assert QgsWkbTypes.hasZ(QgsWkbTypes.MultiPoint25D)
assert QgsWkbTypes.hasZ(QgsWkbTypes.MultiLineString25D)
assert QgsWkbTypes.hasZ(QgsWkbTypes.MultiPolygon25D)
# test hasM methods
assert not QgsWkbTypes.hasM(QgsWkbTypes.Unknown)
assert not QgsWkbTypes.hasM(QgsWkbTypes.Point)
assert not QgsWkbTypes.hasM(QgsWkbTypes.LineString)
assert not QgsWkbTypes.hasM(QgsWkbTypes.Polygon)
assert not QgsWkbTypes.hasM(QgsWkbTypes.MultiPoint)
assert not QgsWkbTypes.hasM(QgsWkbTypes.MultiLineString)
assert not QgsWkbTypes.hasM(QgsWkbTypes.MultiPolygon)
assert not QgsWkbTypes.hasM(QgsWkbTypes.GeometryCollection)
assert not QgsWkbTypes.hasM(QgsWkbTypes.CircularString)
assert not QgsWkbTypes.hasM(QgsWkbTypes.CompoundCurve)
assert not QgsWkbTypes.hasM(QgsWkbTypes.CurvePolygon)
assert not QgsWkbTypes.hasM(QgsWkbTypes.MultiCurve)
assert not QgsWkbTypes.hasM(QgsWkbTypes.MultiSurface)
assert not QgsWkbTypes.hasM(QgsWkbTypes.NoGeometry)
assert not QgsWkbTypes.hasM(QgsWkbTypes.PointZ)
assert not QgsWkbTypes.hasM(QgsWkbTypes.LineStringZ)
assert not QgsWkbTypes.hasM(QgsWkbTypes.PolygonZ)
assert not QgsWkbTypes.hasM(QgsWkbTypes.MultiPointZ)
assert not QgsWkbTypes.hasM(QgsWkbTypes.MultiLineStringZ)
assert not QgsWkbTypes.hasM(QgsWkbTypes.MultiPolygonZ)
assert not QgsWkbTypes.hasM(QgsWkbTypes.GeometryCollectionZ)
assert not QgsWkbTypes.hasM(QgsWkbTypes.CircularStringZ)
assert not QgsWkbTypes.hasM(QgsWkbTypes.CompoundCurveZ)
assert not QgsWkbTypes.hasM(QgsWkbTypes.CurvePolygonZ)
assert not QgsWkbTypes.hasM(QgsWkbTypes.MultiCurveZ)
assert not QgsWkbTypes.hasM(QgsWkbTypes.MultiSurfaceZ)
assert QgsWkbTypes.hasM(QgsWkbTypes.PointM)
assert QgsWkbTypes.hasM(QgsWkbTypes.LineStringM)
assert QgsWkbTypes.hasM(QgsWkbTypes.PolygonM)
assert QgsWkbTypes.hasM(QgsWkbTypes.MultiPointM)
assert QgsWkbTypes.hasM(QgsWkbTypes.MultiLineStringM)
assert QgsWkbTypes.hasM(QgsWkbTypes.MultiPolygonM)
assert QgsWkbTypes.hasM(QgsWkbTypes.GeometryCollectionM)
assert QgsWkbTypes.hasM(QgsWkbTypes.CircularStringM)
assert QgsWkbTypes.hasM(QgsWkbTypes.CompoundCurveM)
assert QgsWkbTypes.hasM(QgsWkbTypes.CurvePolygonM)
assert QgsWkbTypes.hasM(QgsWkbTypes.MultiCurveM)
assert QgsWkbTypes.hasM(QgsWkbTypes.MultiSurfaceM)
assert QgsWkbTypes.hasM(QgsWkbTypes.PointZM)
assert QgsWkbTypes.hasM(QgsWkbTypes.LineStringZM)
assert QgsWkbTypes.hasM(QgsWkbTypes.PolygonZM)
assert QgsWkbTypes.hasM(QgsWkbTypes.MultiPointZM)
assert QgsWkbTypes.hasM(QgsWkbTypes.MultiLineStringZM)
assert QgsWkbTypes.hasM(QgsWkbTypes.MultiPolygonZM)
assert QgsWkbTypes.hasM(QgsWkbTypes.GeometryCollectionZM)
assert QgsWkbTypes.hasM(QgsWkbTypes.CircularStringZM)
assert QgsWkbTypes.hasM(QgsWkbTypes.CompoundCurveZM)
assert QgsWkbTypes.hasM(QgsWkbTypes.CurvePolygonZM)
assert QgsWkbTypes.hasM(QgsWkbTypes.MultiCurveZM)
assert QgsWkbTypes.hasM(QgsWkbTypes.MultiSurfaceZM)
assert not QgsWkbTypes.hasM(QgsWkbTypes.Point25D)
assert not QgsWkbTypes.hasM(QgsWkbTypes.LineString25D)
assert not QgsWkbTypes.hasM(QgsWkbTypes.Polygon25D)
assert not QgsWkbTypes.hasM(QgsWkbTypes.MultiPoint25D)
assert not QgsWkbTypes.hasM(QgsWkbTypes.MultiLineString25D)
assert not QgsWkbTypes.hasM(QgsWkbTypes.MultiPolygon25D)
# test adding z dimension to types
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.Unknown), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.Point), QgsWkbTypes.PointZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.PointZ), QgsWkbTypes.PointZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.PointM), QgsWkbTypes.PointZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.PointZM), QgsWkbTypes.PointZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiPoint), QgsWkbTypes.MultiPointZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiPointZ), QgsWkbTypes.MultiPointZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiPointM), QgsWkbTypes.MultiPointZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiPointZM), QgsWkbTypes.MultiPointZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.LineString), QgsWkbTypes.LineStringZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.LineStringZ), QgsWkbTypes.LineStringZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.LineStringM), QgsWkbTypes.LineStringZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.LineStringZM), QgsWkbTypes.LineStringZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiLineString), QgsWkbTypes.MultiLineStringZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiLineStringZ), QgsWkbTypes.MultiLineStringZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiLineStringM), QgsWkbTypes.MultiLineStringZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiLineStringZM), QgsWkbTypes.MultiLineStringZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.Polygon), QgsWkbTypes.PolygonZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.PolygonZ), QgsWkbTypes.PolygonZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.PolygonM), QgsWkbTypes.PolygonZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.PolygonZM), QgsWkbTypes.PolygonZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiPolygon), QgsWkbTypes.MultiPolygonZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiPolygonZ), QgsWkbTypes.MultiPolygonZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiPolygonM), QgsWkbTypes.MultiPolygonZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiPolygonZM), QgsWkbTypes.MultiPolygonZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.GeometryCollection), QgsWkbTypes.GeometryCollectionZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.GeometryCollectionZ), QgsWkbTypes.GeometryCollectionZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.GeometryCollectionM), QgsWkbTypes.GeometryCollectionZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.GeometryCollectionZM), QgsWkbTypes.GeometryCollectionZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.CircularString), QgsWkbTypes.CircularStringZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.CircularStringZ), QgsWkbTypes.CircularStringZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.CircularStringM), QgsWkbTypes.CircularStringZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.CircularStringZM), QgsWkbTypes.CircularStringZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.CompoundCurve), QgsWkbTypes.CompoundCurveZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.CompoundCurveZ), QgsWkbTypes.CompoundCurveZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.CompoundCurveM), QgsWkbTypes.CompoundCurveZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.CompoundCurveZM), QgsWkbTypes.CompoundCurveZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.CurvePolygon), QgsWkbTypes.CurvePolygonZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.CurvePolygonZ), QgsWkbTypes.CurvePolygonZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.CurvePolygonM), QgsWkbTypes.CurvePolygonZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.CurvePolygonZM), QgsWkbTypes.CurvePolygonZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiCurve), QgsWkbTypes.MultiCurveZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiCurveZ), QgsWkbTypes.MultiCurveZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiCurveM), QgsWkbTypes.MultiCurveZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiCurveZM), QgsWkbTypes.MultiCurveZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiSurface), QgsWkbTypes.MultiSurfaceZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiSurfaceZ), QgsWkbTypes.MultiSurfaceZ)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiSurfaceM), QgsWkbTypes.MultiSurfaceZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiSurfaceZM), QgsWkbTypes.MultiSurfaceZM)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.NoGeometry), QgsWkbTypes.NoGeometry)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.Point25D), QgsWkbTypes.Point25D)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.LineString25D), QgsWkbTypes.LineString25D)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.Polygon25D), QgsWkbTypes.Polygon25D)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiPoint25D), QgsWkbTypes.MultiPoint25D)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiLineString25D), QgsWkbTypes.MultiLineString25D)
self.assertEqual(QgsWkbTypes.addZ(QgsWkbTypes.MultiPolygon25D), QgsWkbTypes.MultiPolygon25D)
# test to25D
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.Unknown), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.Point), QgsWkbTypes.Point25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.PointZ), QgsWkbTypes.Point25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.PointM), QgsWkbTypes.Point25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.PointZM), QgsWkbTypes.Point25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiPoint), QgsWkbTypes.MultiPoint25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiPointZ), QgsWkbTypes.MultiPoint25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiPointM), QgsWkbTypes.MultiPoint25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiPointZM), QgsWkbTypes.MultiPoint25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.LineString), QgsWkbTypes.LineString25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.LineStringZ), QgsWkbTypes.LineString25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.LineStringM), QgsWkbTypes.LineString25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.LineStringZM), QgsWkbTypes.LineString25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiLineString), QgsWkbTypes.MultiLineString25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiLineStringZ), QgsWkbTypes.MultiLineString25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiLineStringM), QgsWkbTypes.MultiLineString25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiLineStringZM), QgsWkbTypes.MultiLineString25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.Polygon), QgsWkbTypes.Polygon25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.PolygonZ), QgsWkbTypes.Polygon25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.PolygonM), QgsWkbTypes.Polygon25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.PolygonZM), QgsWkbTypes.Polygon25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiPolygon), QgsWkbTypes.MultiPolygon25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiPolygonZ), QgsWkbTypes.MultiPolygon25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiPolygonM), QgsWkbTypes.MultiPolygon25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiPolygonZM), QgsWkbTypes.MultiPolygon25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.GeometryCollection), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.GeometryCollectionZ), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.GeometryCollectionM), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.GeometryCollectionZM), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.CircularString), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.CircularStringZ), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.CircularStringM), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.CircularStringZM), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.CompoundCurve), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.CompoundCurveZ), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.CompoundCurveM), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.CompoundCurveZM), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.CurvePolygon), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.CurvePolygonZ), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.CurvePolygonM), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.CurvePolygonZM), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiCurve), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiCurveZ), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiCurveM), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiCurveZM), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiSurface), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiSurfaceZ), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiSurfaceM), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiSurfaceZM), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.NoGeometry), QgsWkbTypes.NoGeometry)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.Point25D), QgsWkbTypes.Point25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.LineString25D), QgsWkbTypes.LineString25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.Polygon25D), QgsWkbTypes.Polygon25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiPoint25D), QgsWkbTypes.MultiPoint25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiLineString25D), QgsWkbTypes.MultiLineString25D)
self.assertEqual(QgsWkbTypes.to25D(QgsWkbTypes.MultiPolygon25D), QgsWkbTypes.MultiPolygon25D)
# test adding m dimension to types
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.Unknown), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.Point), QgsWkbTypes.PointM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.PointZ), QgsWkbTypes.PointZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.PointM), QgsWkbTypes.PointM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.PointZM), QgsWkbTypes.PointZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiPoint), QgsWkbTypes.MultiPointM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiPointZ), QgsWkbTypes.MultiPointZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiPointM), QgsWkbTypes.MultiPointM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiPointZM), QgsWkbTypes.MultiPointZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.LineString), QgsWkbTypes.LineStringM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.LineStringZ), QgsWkbTypes.LineStringZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.LineStringM), QgsWkbTypes.LineStringM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.LineStringZM), QgsWkbTypes.LineStringZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiLineString), QgsWkbTypes.MultiLineStringM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiLineStringZ), QgsWkbTypes.MultiLineStringZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiLineStringM), QgsWkbTypes.MultiLineStringM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiLineStringZM), QgsWkbTypes.MultiLineStringZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.Polygon), QgsWkbTypes.PolygonM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.PolygonZ), QgsWkbTypes.PolygonZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.PolygonM), QgsWkbTypes.PolygonM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.PolygonZM), QgsWkbTypes.PolygonZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiPolygon), QgsWkbTypes.MultiPolygonM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiPolygonZ), QgsWkbTypes.MultiPolygonZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiPolygonM), QgsWkbTypes.MultiPolygonM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiPolygonZM), QgsWkbTypes.MultiPolygonZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.GeometryCollection), QgsWkbTypes.GeometryCollectionM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.GeometryCollectionZ), QgsWkbTypes.GeometryCollectionZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.GeometryCollectionM), QgsWkbTypes.GeometryCollectionM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.GeometryCollectionZM), QgsWkbTypes.GeometryCollectionZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.CircularString), QgsWkbTypes.CircularStringM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.CircularStringZ), QgsWkbTypes.CircularStringZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.CircularStringM), QgsWkbTypes.CircularStringM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.CircularStringZM), QgsWkbTypes.CircularStringZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.CompoundCurve), QgsWkbTypes.CompoundCurveM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.CompoundCurveZ), QgsWkbTypes.CompoundCurveZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.CompoundCurveM), QgsWkbTypes.CompoundCurveM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.CompoundCurveZM), QgsWkbTypes.CompoundCurveZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.CurvePolygon), QgsWkbTypes.CurvePolygonM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.CurvePolygonZ), QgsWkbTypes.CurvePolygonZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.CurvePolygonM), QgsWkbTypes.CurvePolygonM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.CurvePolygonZM), QgsWkbTypes.CurvePolygonZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiCurve), QgsWkbTypes.MultiCurveM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiCurveZ), QgsWkbTypes.MultiCurveZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiCurveM), QgsWkbTypes.MultiCurveM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiCurveZM), QgsWkbTypes.MultiCurveZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiSurface), QgsWkbTypes.MultiSurfaceM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiSurfaceZ), QgsWkbTypes.MultiSurfaceZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiSurfaceM), QgsWkbTypes.MultiSurfaceM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiSurfaceZM), QgsWkbTypes.MultiSurfaceZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.NoGeometry), QgsWkbTypes.NoGeometry)
# we force upgrade 25D types to "Z" before adding the M value
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.Point25D), QgsWkbTypes.PointZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.LineString25D), QgsWkbTypes.LineStringZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.Polygon25D), QgsWkbTypes.PolygonZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiPoint25D), QgsWkbTypes.MultiPointZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiLineString25D), QgsWkbTypes.MultiLineStringZM)
self.assertEqual(QgsWkbTypes.addM(QgsWkbTypes.MultiPolygon25D), QgsWkbTypes.MultiPolygonZM)
# test dropping z dimension from types
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.Unknown), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.Point), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.PointZ), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.PointM), QgsWkbTypes.PointM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.PointZM), QgsWkbTypes.PointM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiPoint), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiPointZ), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiPointM), QgsWkbTypes.MultiPointM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiPointZM), QgsWkbTypes.MultiPointM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.LineString), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.LineStringZ), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.LineStringM), QgsWkbTypes.LineStringM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.LineStringZM), QgsWkbTypes.LineStringM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiLineString), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiLineStringZ), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiLineStringM), QgsWkbTypes.MultiLineStringM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiLineStringZM), QgsWkbTypes.MultiLineStringM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.Polygon), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.PolygonZ), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.PolygonM), QgsWkbTypes.PolygonM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.PolygonZM), QgsWkbTypes.PolygonM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiPolygon), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiPolygonZ), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiPolygonM), QgsWkbTypes.MultiPolygonM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiPolygonZM), QgsWkbTypes.MultiPolygonM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.GeometryCollection), QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.GeometryCollectionZ), QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.GeometryCollectionM), QgsWkbTypes.GeometryCollectionM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.GeometryCollectionZM), QgsWkbTypes.GeometryCollectionM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.CircularString), QgsWkbTypes.CircularString)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.CircularStringZ), QgsWkbTypes.CircularString)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.CircularStringM), QgsWkbTypes.CircularStringM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.CircularStringZM), QgsWkbTypes.CircularStringM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.CompoundCurve), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.CompoundCurveZ), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.CompoundCurveM), QgsWkbTypes.CompoundCurveM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.CompoundCurveZM), QgsWkbTypes.CompoundCurveM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.CurvePolygon), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.CurvePolygonZ), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.CurvePolygonM), QgsWkbTypes.CurvePolygonM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.CurvePolygonZM), QgsWkbTypes.CurvePolygonM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiCurve), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiCurveZ), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiCurveM), QgsWkbTypes.MultiCurveM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiCurveZM), QgsWkbTypes.MultiCurveM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiSurface), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiSurfaceZ), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiSurfaceM), QgsWkbTypes.MultiSurfaceM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiSurfaceZM), QgsWkbTypes.MultiSurfaceM)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.NoGeometry), QgsWkbTypes.NoGeometry)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.Point25D), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.LineString25D), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.Polygon25D), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiPoint25D), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiLineString25D), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.dropZ(QgsWkbTypes.MultiPolygon25D), QgsWkbTypes.MultiPolygon)
# test dropping m dimension from types
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.Unknown), QgsWkbTypes.Unknown)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.Point), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.PointZ), QgsWkbTypes.PointZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.PointM), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.PointZM), QgsWkbTypes.PointZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiPoint), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiPointZ), QgsWkbTypes.MultiPointZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiPointM), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiPointZM), QgsWkbTypes.MultiPointZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.LineString), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.LineStringZ), QgsWkbTypes.LineStringZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.LineStringM), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.LineStringZM), QgsWkbTypes.LineStringZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiLineString), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiLineStringZ), QgsWkbTypes.MultiLineStringZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiLineStringM), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiLineStringZM), QgsWkbTypes.MultiLineStringZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.Polygon), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.PolygonZ), QgsWkbTypes.PolygonZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.PolygonM), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.PolygonZM), QgsWkbTypes.PolygonZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiPolygon), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiPolygonZ), QgsWkbTypes.MultiPolygonZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiPolygonM), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiPolygonZM), QgsWkbTypes.MultiPolygonZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.GeometryCollection), QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.GeometryCollectionZ), QgsWkbTypes.GeometryCollectionZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.GeometryCollectionM), QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.GeometryCollectionZM), QgsWkbTypes.GeometryCollectionZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.CircularString), QgsWkbTypes.CircularString)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.CircularStringZ), QgsWkbTypes.CircularStringZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.CircularStringM), QgsWkbTypes.CircularString)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.CircularStringZM), QgsWkbTypes.CircularStringZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.CompoundCurve), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.CompoundCurveZ), QgsWkbTypes.CompoundCurveZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.CompoundCurveM), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.CompoundCurveZM), QgsWkbTypes.CompoundCurveZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.CurvePolygon), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.CurvePolygonZ), QgsWkbTypes.CurvePolygonZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.CurvePolygonM), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.CurvePolygonZM), QgsWkbTypes.CurvePolygonZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiCurve), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiCurveZ), QgsWkbTypes.MultiCurveZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiCurveM), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiCurveZM), QgsWkbTypes.MultiCurveZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiSurface), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiSurfaceZ), QgsWkbTypes.MultiSurfaceZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiSurfaceM), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiSurfaceZM), QgsWkbTypes.MultiSurfaceZ)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.NoGeometry), QgsWkbTypes.NoGeometry)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.Point25D), QgsWkbTypes.Point25D)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.LineString25D), QgsWkbTypes.LineString25D)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.Polygon25D), QgsWkbTypes.Polygon25D)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiPoint25D), QgsWkbTypes.MultiPoint25D)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiLineString25D), QgsWkbTypes.MultiLineString25D)
self.assertEqual(QgsWkbTypes.dropM(QgsWkbTypes.MultiPolygon25D), QgsWkbTypes.MultiPolygon25D)
# Test QgsWkbTypes.zmType
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.Point, False, False), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.Point, True, False), QgsWkbTypes.PointZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.Point, False, True), QgsWkbTypes.PointM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.Point, True, True), QgsWkbTypes.PointZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PointZ, False, False), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PointZ, True, False), QgsWkbTypes.PointZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PointZ, False, True), QgsWkbTypes.PointM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PointZ, True, True), QgsWkbTypes.PointZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PointM, False, False), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PointM, True, False), QgsWkbTypes.PointZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PointM, False, True), QgsWkbTypes.PointM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PointM, True, True), QgsWkbTypes.PointZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PointZM, False, False), QgsWkbTypes.Point)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PointZM, True, False), QgsWkbTypes.PointZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PointZM, False, True), QgsWkbTypes.PointM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PointZM, True, True), QgsWkbTypes.PointZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineString, False, False), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineString, True, False), QgsWkbTypes.LineStringZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineString, False, True), QgsWkbTypes.LineStringM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineString, True, True), QgsWkbTypes.LineStringZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineStringZ, False, False), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineStringZ, True, False), QgsWkbTypes.LineStringZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineStringZ, False, True), QgsWkbTypes.LineStringM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineStringZ, True, True), QgsWkbTypes.LineStringZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineStringM, False, False), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineStringM, True, False), QgsWkbTypes.LineStringZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineStringM, False, True), QgsWkbTypes.LineStringM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineStringM, True, True), QgsWkbTypes.LineStringZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineStringZM, False, False), QgsWkbTypes.LineString)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineStringZM, True, False), QgsWkbTypes.LineStringZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineStringZM, False, True), QgsWkbTypes.LineStringM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.LineStringZM, True, True), QgsWkbTypes.LineStringZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.Polygon, False, False), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.Polygon, True, False), QgsWkbTypes.PolygonZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.Polygon, False, True), QgsWkbTypes.PolygonM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.Polygon, True, True), QgsWkbTypes.PolygonZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PolygonZ, False, False), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PolygonZ, True, False), QgsWkbTypes.PolygonZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PolygonZ, False, True), QgsWkbTypes.PolygonM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PolygonZ, True, True), QgsWkbTypes.PolygonZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PolygonM, False, False), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PolygonM, True, False), QgsWkbTypes.PolygonZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PolygonM, False, True), QgsWkbTypes.PolygonM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PolygonM, True, True), QgsWkbTypes.PolygonZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PolygonZM, False, False), QgsWkbTypes.Polygon)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PolygonZM, True, False), QgsWkbTypes.PolygonZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PolygonZM, False, True), QgsWkbTypes.PolygonM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.PolygonZM, True, True), QgsWkbTypes.PolygonZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPoint, False, False), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPoint, True, False), QgsWkbTypes.MultiPointZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPoint, False, True), QgsWkbTypes.MultiPointM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPoint, True, True), QgsWkbTypes.MultiPointZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPointZ, False, False), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPointZ, True, False), QgsWkbTypes.MultiPointZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPointZ, False, True), QgsWkbTypes.MultiPointM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPointZ, True, True), QgsWkbTypes.MultiPointZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPointM, False, False), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPointM, True, False), QgsWkbTypes.MultiPointZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPointM, False, True), QgsWkbTypes.MultiPointM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPointM, True, True), QgsWkbTypes.MultiPointZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPointZM, False, False), QgsWkbTypes.MultiPoint)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPointZM, True, False), QgsWkbTypes.MultiPointZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPointZM, False, True), QgsWkbTypes.MultiPointM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPointZM, True, True), QgsWkbTypes.MultiPointZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineString, False, False), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineString, True, False), QgsWkbTypes.MultiLineStringZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineString, False, True), QgsWkbTypes.MultiLineStringM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineString, True, True), QgsWkbTypes.MultiLineStringZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineStringZ, False, False), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineStringZ, True, False), QgsWkbTypes.MultiLineStringZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineStringZ, False, True), QgsWkbTypes.MultiLineStringM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineStringZ, True, True), QgsWkbTypes.MultiLineStringZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineStringM, False, False), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineStringM, True, False), QgsWkbTypes.MultiLineStringZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineStringM, False, True), QgsWkbTypes.MultiLineStringM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineStringM, True, True), QgsWkbTypes.MultiLineStringZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineStringZM, False, False), QgsWkbTypes.MultiLineString)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineStringZM, True, False), QgsWkbTypes.MultiLineStringZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineStringZM, False, True), QgsWkbTypes.MultiLineStringM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiLineStringZM, True, True), QgsWkbTypes.MultiLineStringZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygon, False, False), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygon, True, False), QgsWkbTypes.MultiPolygonZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygon, False, True), QgsWkbTypes.MultiPolygonM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygon, True, True), QgsWkbTypes.MultiPolygonZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygonZ, False, False), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygonZ, True, False), QgsWkbTypes.MultiPolygonZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygonZ, False, True), QgsWkbTypes.MultiPolygonM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygonZ, True, True), QgsWkbTypes.MultiPolygonZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygonM, False, False), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygonM, True, False), QgsWkbTypes.MultiPolygonZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygonM, False, True), QgsWkbTypes.MultiPolygonM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygonM, True, True), QgsWkbTypes.MultiPolygonZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygonZM, False, False), QgsWkbTypes.MultiPolygon)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygonZM, True, False), QgsWkbTypes.MultiPolygonZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygonZM, False, True), QgsWkbTypes.MultiPolygonM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiPolygonZM, True, True), QgsWkbTypes.MultiPolygonZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollection, False, False),
QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollection, True, False),
QgsWkbTypes.GeometryCollectionZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollection, False, True),
QgsWkbTypes.GeometryCollectionM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollection, True, True),
QgsWkbTypes.GeometryCollectionZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollectionZ, False, False),
QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollectionZ, True, False),
QgsWkbTypes.GeometryCollectionZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollectionZ, False, True),
QgsWkbTypes.GeometryCollectionM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollectionZ, True, True),
QgsWkbTypes.GeometryCollectionZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollectionM, False, False),
QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollectionM, True, False),
QgsWkbTypes.GeometryCollectionZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollectionM, False, True),
QgsWkbTypes.GeometryCollectionM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollectionM, True, True),
QgsWkbTypes.GeometryCollectionZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollectionZM, False, False),
QgsWkbTypes.GeometryCollection)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollectionZM, True, False),
QgsWkbTypes.GeometryCollectionZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollectionZM, False, True),
QgsWkbTypes.GeometryCollectionM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.GeometryCollectionZM, True, True),
QgsWkbTypes.GeometryCollectionZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularString, False, False), QgsWkbTypes.CircularString)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularString, True, False), QgsWkbTypes.CircularStringZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularString, False, True), QgsWkbTypes.CircularStringM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularString, True, True), QgsWkbTypes.CircularStringZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularStringZ, False, False), QgsWkbTypes.CircularString)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularStringZ, True, False), QgsWkbTypes.CircularStringZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularStringZ, False, True), QgsWkbTypes.CircularStringM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularStringZ, True, True), QgsWkbTypes.CircularStringZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularStringM, False, False), QgsWkbTypes.CircularString)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularStringM, True, False), QgsWkbTypes.CircularStringZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularStringM, False, True), QgsWkbTypes.CircularStringM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularStringM, True, True), QgsWkbTypes.CircularStringZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularStringZM, False, False), QgsWkbTypes.CircularString)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularStringZM, True, False), QgsWkbTypes.CircularStringZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularStringZM, False, True), QgsWkbTypes.CircularStringM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CircularStringZM, True, True), QgsWkbTypes.CircularStringZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurve, False, False), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurve, True, False), QgsWkbTypes.CompoundCurveZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurve, False, True), QgsWkbTypes.CompoundCurveM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurve, True, True), QgsWkbTypes.CompoundCurveZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurveZ, False, False), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurveZ, True, False), QgsWkbTypes.CompoundCurveZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurveZ, False, True), QgsWkbTypes.CompoundCurveM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurveZ, True, True), QgsWkbTypes.CompoundCurveZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurveM, False, False), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurveM, True, False), QgsWkbTypes.CompoundCurveZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurveM, False, True), QgsWkbTypes.CompoundCurveM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurveM, True, True), QgsWkbTypes.CompoundCurveZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurveZM, False, False), QgsWkbTypes.CompoundCurve)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurveZM, True, False), QgsWkbTypes.CompoundCurveZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurveZM, False, True), QgsWkbTypes.CompoundCurveM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CompoundCurveZM, True, True), QgsWkbTypes.CompoundCurveZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurve, False, False), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurve, True, False), QgsWkbTypes.MultiCurveZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurve, False, True), QgsWkbTypes.MultiCurveM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurve, True, True), QgsWkbTypes.MultiCurveZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurveZ, False, False), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurveZ, True, False), QgsWkbTypes.MultiCurveZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurveZ, False, True), QgsWkbTypes.MultiCurveM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurveZ, True, True), QgsWkbTypes.MultiCurveZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurveM, False, False), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurveM, True, False), QgsWkbTypes.MultiCurveZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurveM, False, True), QgsWkbTypes.MultiCurveM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurveM, True, True), QgsWkbTypes.MultiCurveZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurveZM, False, False), QgsWkbTypes.MultiCurve)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurveZM, True, False), QgsWkbTypes.MultiCurveZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurveZM, False, True), QgsWkbTypes.MultiCurveM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiCurveZM, True, True), QgsWkbTypes.MultiCurveZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygon, False, False), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygon, True, False), QgsWkbTypes.CurvePolygonZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygon, False, True), QgsWkbTypes.CurvePolygonM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygon, True, True), QgsWkbTypes.CurvePolygonZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygonZ, False, False), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygonZ, True, False), QgsWkbTypes.CurvePolygonZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygonZ, False, True), QgsWkbTypes.CurvePolygonM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygonZ, True, True), QgsWkbTypes.CurvePolygonZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygonM, False, False), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygonM, True, False), QgsWkbTypes.CurvePolygonZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygonM, False, True), QgsWkbTypes.CurvePolygonM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygonM, True, True), QgsWkbTypes.CurvePolygonZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygonZM, False, False), QgsWkbTypes.CurvePolygon)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygonZM, True, False), QgsWkbTypes.CurvePolygonZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygonZM, False, True), QgsWkbTypes.CurvePolygonM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.CurvePolygonZM, True, True), QgsWkbTypes.CurvePolygonZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurface, False, False), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurface, True, False), QgsWkbTypes.MultiSurfaceZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurface, False, True), QgsWkbTypes.MultiSurfaceM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurface, True, True), QgsWkbTypes.MultiSurfaceZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurfaceZ, False, False), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurfaceZ, True, False), QgsWkbTypes.MultiSurfaceZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurfaceZ, False, True), QgsWkbTypes.MultiSurfaceM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurfaceZ, True, True), QgsWkbTypes.MultiSurfaceZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurfaceM, False, False), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurfaceM, True, False), QgsWkbTypes.MultiSurfaceZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurfaceM, False, True), QgsWkbTypes.MultiSurfaceM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurfaceM, True, True), QgsWkbTypes.MultiSurfaceZM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurfaceZM, False, False), QgsWkbTypes.MultiSurface)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurfaceZM, True, False), QgsWkbTypes.MultiSurfaceZ)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurfaceZM, False, True), QgsWkbTypes.MultiSurfaceM)
self.assertEqual(QgsWkbTypes.zmType(QgsWkbTypes.MultiSurfaceZM, True, True), QgsWkbTypes.MultiSurfaceZM)
def testGeometryDisplayString(self):
self.assertEqual(QgsWkbTypes.geometryDisplayString(QgsWkbTypes.PointGeometry), 'Point')
self.assertEqual(QgsWkbTypes.geometryDisplayString(QgsWkbTypes.LineGeometry), 'Line')
self.assertEqual(QgsWkbTypes.geometryDisplayString(QgsWkbTypes.PolygonGeometry), 'Polygon')
self.assertEqual(QgsWkbTypes.geometryDisplayString(QgsWkbTypes.UnknownGeometry), 'Unknown geometry')
self.assertEqual(QgsWkbTypes.geometryDisplayString(QgsWkbTypes.NullGeometry), 'No geometry')
self.assertEqual(QgsWkbTypes.geometryDisplayString(999999), 'Invalid type')
def testDeleteVertexCircularString(self):
wkt = "CircularString (0 0,1 1,2 0)"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(0)
self.assertEqual(geom.asWkt(), QgsCircularString().asWkt())
wkt = "CircularString (0 0,1 1,2 0,3 -1,4 0)"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(0)
expected_wkt = "CircularString (2 0, 3 -1, 4 0)"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CircularString (0 0,1 1,2 0,3 -1,4 0)"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(1)
expected_wkt = "CircularString (0 0, 3 -1, 4 0)"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CircularString (0 0,1 1,2 0,3 -1,4 0)"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(2)
expected_wkt = "CircularString (0 0, 1 1, 4 0)"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CircularString (0 0,1 1,2 0,3 -1,4 0)"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(3)
expected_wkt = "CircularString (0 0, 1 1, 4 0)"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CircularString (0 0,1 1,2 0,3 -1,4 0)"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(4)
expected_wkt = "CircularString (0 0,1 1,2 0)"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CircularString (0 0,1 1,2 0,3 -1,4 0)"
geom = QgsGeometry.fromWkt(wkt)
assert not geom.deleteVertex(-1)
assert not geom.deleteVertex(5)
def testDeleteVertexCompoundCurve(self):
wkt = "CompoundCurve ((0 0,1 1))"
geom = QgsGeometry.fromWkt(wkt)
assert not geom.deleteVertex(-1)
assert not geom.deleteVertex(2)
assert geom.deleteVertex(0)
self.assertEqual(geom.asWkt(), QgsCompoundCurve().asWkt())
wkt = "CompoundCurve ((0 0,1 1))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(1)
self.assertEqual(geom.asWkt(), QgsCompoundCurve().asWkt())
wkt = "CompoundCurve ((0 0,1 1),(1 1,2 2))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(0)
expected_wkt = "CompoundCurve ((1 1,2 2))"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CompoundCurve ((0 0,1 1),(1 1,2 2))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(1)
expected_wkt = "CompoundCurve ((0 0,2 2))"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CompoundCurve ((0 0,1 1),(1 1,2 2))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(2)
expected_wkt = "CompoundCurve ((0 0,1 1))"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CompoundCurve ((0 0,1 1),CircularString(1 1,2 0,1 -1))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(1)
expected_wkt = "CompoundCurve ((0 0,1 -1))"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CompoundCurve (CircularString(0 0,1 1,2 0),CircularString(2 0,3 -1,4 0))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(2)
expected_wkt = "CompoundCurve ((0 0, 4 0))"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CompoundCurve (CircularString(0 0,1 1,2 0,1.5 -0.5,1 -1),(1 -1,0 0))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(4)
expected_wkt = "CompoundCurve (CircularString (0 0, 1 1, 2 0),(2 0, 0 0))"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CompoundCurve ((-1 0,0 0),CircularString(0 0,1 1,2 0,1.5 -0.5,1 -1))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(1)
expected_wkt = "CompoundCurve ((-1 0, 2 0),CircularString (2 0, 1.5 -0.5, 1 -1))"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CompoundCurve (CircularString(-1 -1,-1.5 -0.5,-2 0,-1 1,0 0),CircularString(0 0,1 1,2 0,1.5 -0.5,1 -1))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(4)
expected_wkt = "CompoundCurve (CircularString (-1 -1, -1.5 -0.5, -2 0),(-2 0, 2 0),CircularString (2 0, 1.5 -0.5, 1 -1))"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
def testDeleteVertexCurvePolygon(self):
wkt = "CurvePolygon (CompoundCurve (CircularString(0 0,1 1,2 0),(2 0,0 0)))"
geom = QgsGeometry.fromWkt(wkt)
assert not geom.deleteVertex(-1)
assert not geom.deleteVertex(4)
assert geom.deleteVertex(0)
self.assertEqual(geom.asWkt(), QgsCurvePolygon().asWkt())
wkt = "CurvePolygon (CompoundCurve (CircularString(0 0,1 1,2 0),(2 0,0 0)))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(1)
self.assertEqual(geom.asWkt(), QgsCurvePolygon().asWkt())
wkt = "CurvePolygon (CompoundCurve (CircularString(0 0,1 1,2 0),(2 0,0 0)))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(2)
self.assertEqual(geom.asWkt(), QgsCurvePolygon().asWkt())
wkt = "CurvePolygon (CompoundCurve (CircularString(0 0,1 1,2 0),(2 0,0 0)))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(3)
self.assertEqual(geom.asWkt(), QgsCurvePolygon().asWkt())
wkt = "CurvePolygon (CompoundCurve (CircularString(0 0,1 1,2 0,1.5 -0.5,1 -1),(1 -1,0 0)))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(0)
expected_wkt = "CurvePolygon (CompoundCurve (CircularString (2 0, 1.5 -0.5, 1 -1),(1 -1, 2 0)))"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CurvePolygon (CompoundCurve (CircularString(0 0,1 1,2 0,1.5 -0.5,1 -1),(1 -1,0 0)))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(1)
expected_wkt = "CurvePolygon (CompoundCurve (CircularString (0 0, 1.5 -0.5, 1 -1),(1 -1, 0 0)))"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CurvePolygon (CompoundCurve (CircularString(0 0,1 1,2 0,1.5 -0.5,1 -1),(1 -1,0 0)))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(2)
expected_wkt = "CurvePolygon (CompoundCurve (CircularString (0 0, 1 1, 1 -1),(1 -1, 0 0)))"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CurvePolygon (CompoundCurve (CircularString(0 0,1 1,2 0,1.5 -0.5,1 -1),(1 -1,0 0)))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(3)
expected_wkt = "CurvePolygon (CompoundCurve (CircularString (0 0, 1 1, 1 -1),(1 -1, 0 0)))"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
wkt = "CurvePolygon (CompoundCurve (CircularString(0 0,1 1,2 0,1.5 -0.5,1 -1),(1 -1,0 0)))"
geom = QgsGeometry.fromWkt(wkt)
assert geom.deleteVertex(4)
expected_wkt = "CurvePolygon (CompoundCurve (CircularString (0 0, 1 1, 2 0),(2 0, 0 0)))"
self.assertEqual(geom.asWkt(), QgsGeometry.fromWkt(expected_wkt).asWkt())
def testConvertVertex(self):
# WKT BEFORE -> WKT AFTER A CONVERT ON POINT AT 10,10
test_setup = {
# Curve
'LINESTRING(0 0, 10 0, 10 10, 0 10, 0 0)': 'COMPOUNDCURVE((0 0, 10 0), CIRCULARSTRING(10 0, 10 10, 0 10), (0 10, 0 0))',
'COMPOUNDCURVE(CIRCULARSTRING(0 0, 10 0, 10 10, 0 10, 0 0))': 'COMPOUNDCURVE(CIRCULARSTRING(0 0, 10 0, 10 10, 0 10, 0 0))',
'COMPOUNDCURVE((0 0, 10 0), CIRCULARSTRING(10 0, 10 10, 0 10), (0 10, 0 0))': 'COMPOUNDCURVE((0 0, 10 0, 10 10, 0 10, 0 0))',
# Multicurve
'MULTICURVE(LINESTRING(0 0, 10 0, 10 10, 0 10, 0 0), LINESTRING(5 15, 10 20, 0 20, 5 15))': 'MULTICURVE(COMPOUNDCURVE((0 0, 10 0), CIRCULARSTRING(10 0, 10 10, 0 10), (0 10, 0 0)), LINESTRING(5 15, 10 20, 0 20, 5 15))',
'MULTICURVE(COMPOUNDCURVE(CIRCULARSTRING(0 0, 10 0, 10 10, 0 10, 0 0)), LINESTRING(5 15, 10 20, 0 20, 5 15))': 'MULTICURVE(COMPOUNDCURVE(CIRCULARSTRING(0 0, 10 0, 10 10, 0 10, 0 0)), LINESTRING(5 15, 10 20, 0 20, 5 15))',
'MULTICURVE(COMPOUNDCURVE((0 0, 10 0), CIRCULARSTRING(10 0, 10 10, 0 10), (0 10, 0 0)), LINESTRING(5 15, 10 20, 0 20, 5 15))': 'MULTICURVE(COMPOUNDCURVE((0 0, 10 0, 10 10, 0 10, 0 0)), LINESTRING(5 15, 10 20, 0 20, 5 15))',
# Polygon
'CURVEPOLYGON(LINESTRING(0 0, 10 0, 10 10, 0 10, 0 0), LINESTRING(3 3, 7 3, 7 7, 3 7, 3 3))': 'CURVEPOLYGON(COMPOUNDCURVE((0 0, 10 0), CIRCULARSTRING(10 0, 10 10, 0 10), (0 10, 0 0)), LINESTRING(3 3, 7 3, 7 7, 3 7, 3 3))',
'CURVEPOLYGON(COMPOUNDCURVE(CIRCULARSTRING(0 0, 10 0, 10 10, 0 10, 0 0)), COMPOUNDCURVE(CIRCULARSTRING(3 3, 7 3, 7 7, 3 7, 3 3)))': 'CURVEPOLYGON(COMPOUNDCURVE(CIRCULARSTRING(0 0, 10 0, 10 10, 0 10, 0 0)), COMPOUNDCURVE(CIRCULARSTRING(3 3, 7 3, 7 7, 3 7, 3 3)))',
'CURVEPOLYGON(COMPOUNDCURVE((0 0, 10 0), CIRCULARSTRING(10 0, 10 10, 0 10), (0 10, 0 0)), COMPOUNDCURVE((3 3, 7 3), CIRCULARSTRING(7 3, 7 7, 3 7), (3 7, 3 3)))': 'CURVEPOLYGON(COMPOUNDCURVE((0 0, 10 0, 10 10, 0 10, 0 0)), COMPOUNDCURVE((3 3, 7 3), CIRCULARSTRING(7 3, 7 7, 3 7), (3 7, 3 3)))',
# Multipolygon
'MULTISURFACE(CURVEPOLYGON(LINESTRING(0 0, 10 0, 10 10, 0 10, 0 0), LINESTRING(3 3, 7 3, 7 7, 3 7, 3 3)), CURVEPOLYGON(LINESTRING(5 15, 10 20, 0 20, 5 15)))': 'MULTISURFACE(CURVEPOLYGON(COMPOUNDCURVE((0 0, 10 0), CIRCULARSTRING(10 0, 10 10, 0 10), (0 10, 0 0)), LINESTRING(3 3, 7 3, 7 7, 3 7, 3 3)), CURVEPOLYGON(LINESTRING(5 15, 10 20, 0 20, 5 15)))',
'MULTISURFACE(CURVEPOLYGON(COMPOUNDCURVE(CIRCULARSTRING(0 0, 10 0, 10 10, 0 10, 0 0)), COMPOUNDCURVE(CIRCULARSTRING(3 3, 7 3, 7 7, 3 7, 3 3))), CURVEPOLYGON(LINESTRING(5 15, 10 20, 0 20, 5 15)))': 'MULTISURFACE(CURVEPOLYGON(COMPOUNDCURVE(CIRCULARSTRING(0 0, 10 0, 10 10, 0 10, 0 0)), COMPOUNDCURVE(CIRCULARSTRING(3 3, 7 3, 7 7, 3 7, 3 3))), CURVEPOLYGON(LINESTRING(5 15, 10 20, 0 20, 5 15)))',
'MULTISURFACE(CURVEPOLYGON(COMPOUNDCURVE((0 0, 10 0), CIRCULARSTRING(10 0, 10 10, 0 10), (0 10, 0 0)), COMPOUNDCURVE((3 3, 7 3), CIRCULARSTRING(7 3, 7 7, 3 7), (3 7, 3 3))), CURVEPOLYGON(LINESTRING(5 15, 10 20, 0 20, 5 15)))': 'MULTISURFACE(CURVEPOLYGON(COMPOUNDCURVE((0 0, 10 0, 10 10, 0 10, 0 0)), COMPOUNDCURVE((3 3, 7 3), CIRCULARSTRING(7 3, 7 7, 3 7), (3 7, 3 3))), CURVEPOLYGON(LINESTRING(5 15, 10 20, 0 20, 5 15)))',
}
for wkt_before, wkt_expected in test_setup.items():
geom = QgsGeometry.fromWkt(wkt_before)
geom.toggleCircularAtVertex(geom.closestVertex(QgsPointXY(10, 10))[1])
self.assertTrue(QgsGeometry.equals(geom, QgsGeometry.fromWkt(wkt_expected)), f'toggleCircularAtVertex() did not create expected geometry.\nconverted wkt : {geom.asWkt()}\nexpected wkt : {wkt_expected}\ninput wkt : {wkt_before}).')
def testSingleSidedBuffer(self):
wkt = "LineString( 0 0, 10 0)"
geom = QgsGeometry.fromWkt(wkt)
out = geom.singleSidedBuffer(1, 8, QgsGeometry.SideLeft)
result = out.asWkt()
expected_wkt = "Polygon ((10 0, 0 0, 0 1, 10 1, 10 0))"
self.assertTrue(compareWkt(result, expected_wkt, 0.00001),
"Merge lines: mismatch Expected:\n{}\nGot:\n{}\n".format(expected_wkt, result))
wkt = "LineString( 0 0, 10 0)"
geom = QgsGeometry.fromWkt(wkt)
out = geom.singleSidedBuffer(1, 8, QgsGeometry.SideRight)
result = out.asWkt()
expected_wkt = "Polygon ((0 0, 10 0, 10 -1, 0 -1, 0 0))"
self.assertTrue(compareWkt(result, expected_wkt, 0.00001),
"Merge lines: mismatch Expected:\n{}\nGot:\n{}\n".format(expected_wkt, result))
wkt = "LineString( 0 0, 10 0, 10 10)"
geom = QgsGeometry.fromWkt(wkt)
out = geom.singleSidedBuffer(1, 8, QgsGeometry.SideRight, QgsGeometry.JoinStyleMiter)
result = out.asWkt()
expected_wkt = "Polygon ((0 0, 10 0, 10 10, 11 10, 11 -1, 0 -1, 0 0))"
self.assertTrue(compareWkt(result, expected_wkt, 0.00001),
"Merge lines: mismatch Expected:\n{}\nGot:\n{}\n".format(expected_wkt, result))
wkt = "LineString( 0 0, 10 0, 10 10)"
geom = QgsGeometry.fromWkt(wkt)
out = geom.singleSidedBuffer(1, 8, QgsGeometry.SideRight, QgsGeometry.JoinStyleBevel)
result = out.asWkt()
expected_wkt = "Polygon ((0 0, 10 0, 10 10, 11 10, 11 0, 10 -1, 0 -1, 0 0))"
self.assertTrue(compareWkt(result, expected_wkt, 0.00001),
"Merge lines: mismatch Expected:\n{}\nGot:\n{}\n".format(expected_wkt, result))
def testMisc(self):
# Test that we cannot add a CurvePolygon in a MultiPolygon
multipolygon = QgsMultiPolygon()
cp = QgsCurvePolygon()
cp.fromWkt("CurvePolygon ((0 0,0 1,1 1,0 0))")
assert not multipolygon.addGeometry(cp)
# Test that importing an invalid WKB (a MultiPolygon with a CurvePolygon) fails
geom = QgsGeometry.fromWkt('MultiSurface(((0 0,0 1,1 1,0 0)), CurvePolygon ((0 0,0 1,1 1,0 0)))')
wkb = geom.asWkb()
wkb = bytearray(wkb)
if wkb[1] == QgsWkbTypes.MultiSurface:
wkb[1] = QgsWkbTypes.MultiPolygon
elif wkb[1 + 4] == QgsWkbTypes.MultiSurface:
wkb[1 + 4] = QgsWkbTypes.MultiPolygon
else:
self.assertTrue(False)
geom = QgsGeometry()
geom.fromWkb(wkb)
self.assertEqual(geom.asWkt(), QgsMultiPolygon().asWkt())
# Test that fromWkt() on a GeometryCollection works with all possible geometries
wkt = "GeometryCollection( "
wkt += "Point(0 1)"
wkt += ","
wkt += "LineString(0 0,0 1)"
wkt += ","
wkt += "Polygon ((0 0,1 1,1 0,0 0))"
wkt += ","
wkt += "CurvePolygon ((0 0,1 1,1 0,0 0))"
wkt += ","
wkt += "CircularString (0 0,1 1,2 0)"
wkt += ","
wkt += "CompoundCurve ((0 0,0 1))"
wkt += ","
wkt += "MultiPoint ((0 0))"
wkt += ","
wkt += "MultiLineString((0 0,0 1))"
wkt += ","
wkt += "MultiCurve((0 0,0 1))"
wkt += ","
wkt += "MultiPolygon (((0 0,1 1,1 0,0 0)))"
wkt += ","
wkt += "MultiSurface (((0 0,1 1,1 0,0 0)))"
wkt += ","
wkt += "GeometryCollection (Point(0 0))"
wkt += ")"
geom = QgsGeometry.fromWkt(wkt)
assert geom is not None
wkb1 = geom.asWkb()
geom = QgsGeometry()
geom.fromWkb(wkb1)
wkb2 = geom.asWkb()
self.assertEqual(wkb1, wkb2)
def testMergeLines(self):
""" test merging linestrings """
# not a (multi)linestring
geom = QgsGeometry.fromWkt('Point(1 2)')
result = geom.mergeLines()
self.assertTrue(result.isNull())
# linestring should be returned intact
geom = QgsGeometry.fromWkt('LineString(0 0, 10 10)')
result = geom.mergeLines().asWkt()
exp = 'LineString(0 0, 10 10)'
self.assertTrue(compareWkt(result, exp, 0.00001),
"Merge lines: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
# multilinestring
geom = QgsGeometry.fromWkt('MultiLineString((0 0, 10 10),(10 10, 20 20))')
result = geom.mergeLines().asWkt()
exp = 'LineString(0 0, 10 10, 20 20)'
self.assertTrue(compareWkt(result, exp, 0.00001),
"Merge lines: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
geom = QgsGeometry.fromWkt('MultiLineString((0 0, 10 10),(12 2, 14 4),(10 10, 20 20))')
result = geom.mergeLines().asWkt()
exp = 'MultiLineString((0 0, 10 10, 20 20),(12 2, 14 4))'
self.assertTrue(compareWkt(result, exp, 0.00001),
"Merge lines: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
geom = QgsGeometry.fromWkt('MultiLineString((0 0, 10 10),(12 2, 14 4))')
result = geom.mergeLines().asWkt()
exp = 'MultiLineString((0 0, 10 10),(12 2, 14 4))'
self.assertTrue(compareWkt(result, exp, 0.00001),
"Merge lines: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testCurveSinuosity(self):
"""
Test curve straightDistance2d() and sinuosity()
"""
linestring = QgsGeometry.fromWkt('LineString EMPTY')
self.assertTrue(math.isnan(linestring.constGet().straightDistance2d()))
self.assertTrue(math.isnan(linestring.constGet().sinuosity()))
linestring = QgsGeometry.fromWkt('LineString(0 0, 10 0)')
self.assertEqual(linestring.constGet().straightDistance2d(), 10.0)
self.assertEqual(linestring.constGet().sinuosity(), 1.0)
linestring = QgsGeometry.fromWkt('LineString(0 0, 10 10, 5 0)')
self.assertAlmostEqual(linestring.constGet().straightDistance2d(), 5.0, 4)
self.assertAlmostEqual(linestring.constGet().sinuosity(), 5.06449510, 4)
linestring = QgsGeometry.fromWkt('LineString(0 0, 10 0, 10 10, 0 10, 0 0)')
self.assertEqual(linestring.constGet().straightDistance2d(), 0.0)
self.assertTrue(math.isnan(linestring.constGet().sinuosity()))
curve = QgsGeometry.fromWkt('CircularString (20 30, 50 30, 50 90)')
self.assertAlmostEqual(curve.constGet().straightDistance2d(), 67.08203932, 4)
self.assertAlmostEqual(curve.constGet().sinuosity(), 1.57079632, 4)
curve = QgsGeometry.fromWkt('CircularString (20 30, 50 30, 20 30)')
self.assertAlmostEqual(curve.constGet().straightDistance2d(), 0.0, 4)
self.assertTrue(math.isnan(curve.constGet().sinuosity()))
def testLineLocatePoint(self):
""" test QgsGeometry.lineLocatePoint() """
# not a linestring
point = QgsGeometry.fromWkt('Point(1 2)')
self.assertEqual(point.lineLocatePoint(point), -1)
# not a point
linestring = QgsGeometry.fromWkt('LineString(0 0, 10 0)')
self.assertEqual(linestring.lineLocatePoint(linestring), -1)
# valid
self.assertEqual(linestring.lineLocatePoint(point), 1)
point = QgsGeometry.fromWkt('Point(9 -2)')
self.assertEqual(linestring.lineLocatePoint(point), 9)
# circular string
geom = QgsGeometry.fromWkt('CircularString (1 5, 6 2, 7 3)')
point = QgsGeometry.fromWkt('Point(9 -2)')
self.assertAlmostEqual(geom.lineLocatePoint(point), 7.377, places=3)
def testInterpolateAngle(self):
""" test QgsGeometry.interpolateAngle() """
empty = QgsGeometry()
# just test no crash
self.assertEqual(empty.interpolateAngle(5), 0)
# not a linestring
point = QgsGeometry.fromWkt('Point(1 2)')
# no meaning, just test no crash!
self.assertEqual(point.interpolateAngle(5), 0)
# linestring
linestring = QgsGeometry.fromWkt('LineString(0 0, 10 0, 20 10, 20 20, 10 20)')
self.assertAlmostEqual(linestring.interpolateAngle(0), math.radians(90), places=3)
self.assertAlmostEqual(linestring.interpolateAngle(5), math.radians(90), places=3)
self.assertAlmostEqual(linestring.interpolateAngle(10), math.radians(67.5), places=3)
self.assertAlmostEqual(linestring.interpolateAngle(15), math.radians(45), places=3)
self.assertAlmostEqual(linestring.interpolateAngle(25), math.radians(0), places=3)
self.assertAlmostEqual(linestring.interpolateAngle(35), math.radians(270), places=3)
# test first and last points in a linestring - angle should be angle of
# first/last segment
linestring = QgsGeometry.fromWkt('LineString(20 0, 10 0, 10 -10)')
self.assertAlmostEqual(linestring.interpolateAngle(0), math.radians(270), places=3)
self.assertAlmostEqual(linestring.interpolateAngle(20), math.radians(180), places=3)
# polygon
polygon = QgsGeometry.fromWkt('Polygon((0 0, 10 0, 20 10, 20 20, 10 20, 0 0))')
self.assertAlmostEqual(polygon.interpolateAngle(5), math.radians(90), places=3)
self.assertAlmostEqual(polygon.interpolateAngle(10), math.radians(67.5), places=3)
self.assertAlmostEqual(polygon.interpolateAngle(15), math.radians(45), places=3)
self.assertAlmostEqual(polygon.interpolateAngle(25), math.radians(0), places=3)
self.assertAlmostEqual(polygon.interpolateAngle(35), math.radians(270), places=3)
# test first/last vertex in polygon
polygon = QgsGeometry.fromWkt('Polygon((0 0, 10 0, 10 10, 0 10, 0 0))')
self.assertAlmostEqual(polygon.interpolateAngle(0), math.radians(135), places=3)
self.assertAlmostEqual(polygon.interpolateAngle(40), math.radians(135), places=3)
# circular string
geom = QgsGeometry.fromWkt('CircularString (1 5, 6 2, 7 3)')
self.assertAlmostEqual(geom.interpolateAngle(5), 1.6919, places=3)
def testInterpolate(self):
""" test QgsGeometry.interpolate() """
empty = QgsGeometry()
# just test no crash
self.assertFalse(empty.interpolate(5))
# not a linestring
point = QgsGeometry.fromWkt('Point(1 2)') # NOQA
# no meaning, just test no crash!
self.assertFalse(empty.interpolate(5))
# linestring
linestring = QgsGeometry.fromWkt('LineString(0 0, 10 0, 10 10)')
exp = 'Point(5 0)'
result = linestring.interpolate(5).asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"Interpolate: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
self.assertTrue(linestring.interpolate(25).isNull())
# multilinestring
linestring = QgsGeometry.fromWkt('MultiLineString((0 0, 10 0, 10 10),(20 0, 30 0, 30 10))')
exp = 'Point(5 0)'
result = linestring.interpolate(5).asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"Interpolate: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
exp = 'Point(10 5)'
result = linestring.interpolate(15).asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"Interpolate: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
exp = 'Point(10 10)'
result = linestring.interpolate(20).asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"Interpolate: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
exp = 'Point(25 0)'
result = linestring.interpolate(25).asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"Interpolate: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
exp = 'Point(30 0)'
result = linestring.interpolate(30).asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"Interpolate: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
exp = 'Point(30 5)'
result = linestring.interpolate(35).asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"Interpolate: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
self.assertTrue(linestring.interpolate(50).isNull())
# polygon
polygon = QgsGeometry.fromWkt('Polygon((0 0, 10 0, 10 10, 20 20, 10 20, 0 0))') # NOQA
exp = 'Point(10 5)'
result = polygon.interpolate(15).asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"Interpolate: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
self.assertTrue(polygon.interpolate(68).isNull())
# polygon with ring
polygon = QgsGeometry.fromWkt(
'Polygon((0 0, 10 0, 10 10, 20 20, 10 20, 0 0),(5 5, 6 5, 6 6, 5 6, 5 5))') # NOQA
exp = 'Point (6 5.5)'
result = polygon.interpolate(68).asWkt()
self.assertTrue(compareWkt(result, exp, 0.1),
"Interpolate: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testAngleAtVertex(self):
""" test QgsGeometry.angleAtVertex """
empty = QgsGeometry()
# just test no crash
self.assertEqual(empty.angleAtVertex(0), 0)
# not a linestring
point = QgsGeometry.fromWkt('Point(1 2)')
# no meaning, just test no crash!
self.assertEqual(point.angleAtVertex(0), 0)
# linestring
linestring = QgsGeometry.fromWkt('LineString(0 0, 10 0, 20 10, 20 20, 10 20)')
self.assertAlmostEqual(linestring.angleAtVertex(1), math.radians(67.5), places=3)
self.assertAlmostEqual(linestring.angleAtVertex(2), math.radians(22.5), places=3)
self.assertAlmostEqual(linestring.angleAtVertex(3), math.radians(315.0), places=3)
self.assertAlmostEqual(linestring.angleAtVertex(5), 0, places=3)
self.assertAlmostEqual(linestring.angleAtVertex(-1), 0, places=3)
# test first and last points in a linestring - angle should be angle of
# first/last segment
linestring = QgsGeometry.fromWkt('LineString(20 0, 10 0, 10 -10)')
self.assertAlmostEqual(linestring.angleAtVertex(0), math.radians(270), places=3)
self.assertAlmostEqual(linestring.angleAtVertex(2), math.radians(180), places=3)
# closed linestring - angle at first/last vertex should be average angle
linestring = QgsGeometry.fromWkt(
'LineString (-1007697 1334641, -1007697 1334643, -1007695 1334643, -1007695 1334641, -1007696 1334641, -1007697 1334641)')
self.assertAlmostEqual(linestring.angleAtVertex(0), math.radians(315), places=3)
self.assertAlmostEqual(linestring.angleAtVertex(5), math.radians(315), places=3)
# polygon
polygon = QgsGeometry.fromWkt('Polygon((0 0, 10 0, 10 10, 0 10, 0 0))')
self.assertAlmostEqual(polygon.angleAtVertex(0), math.radians(135.0), places=3)
self.assertAlmostEqual(polygon.angleAtVertex(1), math.radians(45.0), places=3)
self.assertAlmostEqual(polygon.angleAtVertex(2), math.radians(315.0), places=3)
self.assertAlmostEqual(polygon.angleAtVertex(3), math.radians(225.0), places=3)
self.assertAlmostEqual(polygon.angleAtVertex(4), math.radians(135.0), places=3)
def testExtendLine(self):
""" test QgsGeometry.extendLine """
empty = QgsGeometry()
self.assertFalse(empty.extendLine(1, 2))
# not a linestring
point = QgsGeometry.fromWkt('Point(1 2)')
self.assertFalse(point.extendLine(1, 2))
# linestring
linestring = QgsGeometry.fromWkt('LineString(0 0, 1 0, 1 1)')
extended = linestring.extendLine(1, 2)
exp = 'LineString(-1 0, 1 0, 1 3)'
result = extended.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"Extend line: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
# multilinestring
multilinestring = QgsGeometry.fromWkt('MultiLineString((0 0, 1 0, 1 1),(11 11, 11 10, 10 10))')
extended = multilinestring.extendLine(1, 2)
exp = 'MultiLineString((-1 0, 1 0, 1 3),(11 12, 11 10, 8 10))'
result = extended.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"Extend line: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testRemoveRings(self):
empty = QgsGeometry()
self.assertFalse(empty.removeInteriorRings())
# not a polygon
point = QgsGeometry.fromWkt('Point(1 2)')
self.assertFalse(point.removeInteriorRings())
# polygon
polygon = QgsGeometry.fromWkt('Polygon((0 0, 1 0, 1 1, 0 0),(0.1 0.1, 0.2 0.1, 0.2 0.2, 0.1 0.1))')
removed = polygon.removeInteriorRings()
exp = 'Polygon((0 0, 1 0, 1 1, 0 0))'
result = removed.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"Extend line: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
# multipolygon
multipolygon = QgsGeometry.fromWkt('MultiPolygon(((0 0, 1 0, 1 1, 0 0),(0.1 0.1, 0.2 0.1, 0.2 0.2, 0.1 0.1)),'
'((10 0, 11 0, 11 1, 10 0),(10.1 10.1, 10.2 0.1, 10.2 0.2, 10.1 0.1)))')
removed = multipolygon.removeInteriorRings()
exp = 'MultiPolygon(((0 0, 1 0, 1 1, 0 0)),((10 0, 11 0, 11 1, 10 0)))'
result = removed.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"Extend line: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testMinimumOrientedBoundingBox(self):
empty = QgsGeometry()
bbox, area, angle, width, height = empty.orientedMinimumBoundingBox()
self.assertFalse(bbox)
# not a useful geometry
point = QgsGeometry.fromWkt('Point(1 2)')
bbox, area, angle, width, height = point.orientedMinimumBoundingBox()
self.assertFalse(bbox)
# polygon
polygon = QgsGeometry.fromWkt('Polygon((-0.1 -1.3, 2.1 1, 3 2.8, 6.7 0.2, 3 -1.8, 0.3 -2.7, -0.1 -1.3))')
bbox, area, angle, width, height = polygon.orientedMinimumBoundingBox()
exp = 'Polygon ((-0.628 -1.9983, 2.9769 -4.724, 6.7 0.2, 3.095 2.9257, -0.628 -1.9983))'
result = bbox.asWkt(4)
self.assertTrue(compareWkt(result, exp, 0.00001),
"Oriented MBBR: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
self.assertAlmostEqual(area, 27.89886071158214, places=3)
self.assertAlmostEqual(angle, 37.09283729704157, places=3)
self.assertAlmostEqual(width, 4.519421040409892, places=3)
self.assertAlmostEqual(height, 6.173105019896937, places=3)
def testOrthogonalize(self):
empty = QgsGeometry()
o = empty.orthogonalize()
self.assertFalse(o)
# not a useful geometry
point = QgsGeometry.fromWkt('Point(1 2)')
o = point.orthogonalize()
self.assertFalse(o)
# polygon
polygon = QgsGeometry.fromWkt('Polygon((-0.699 0.892, -0.703 0.405, -0.022 0.361, 0.014 0.851, -0.699 0.892))')
o = polygon.orthogonalize()
exp = 'Polygon ((-0.69899999999999995 0.89200000000000002, -0.72568713635737736 0.38414056283699533, -0.00900222326098143 0.34648000752227009, 0.01768491457044956 0.85433944198378253, -0.69899999999999995 0.89200000000000002))'
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"orthogonalize: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
# polygon with ring
polygon = QgsGeometry.fromWkt(
'Polygon ((-0.698 0.892, -0.702 0.405, -0.022 0.360, 0.014 0.850, -0.698 0.892),(-0.619 0.777, -0.619 0.574, -0.515 0.567, -0.517 0.516, -0.411 0.499, -0.379 0.767, -0.619 0.777),(-0.322 0.506, -0.185 0.735, -0.046 0.428, -0.322 0.506))')
o = polygon.orthogonalize()
exp = 'Polygon ((-0.69799999999999995 0.89200000000000002, -0.72515703079591087 0.38373993222914216, -0.00901577368860811 0.34547552423418099, 0.01814125858957143 0.85373558928902782, -0.69799999999999995 0.89200000000000002),(-0.61899999999999999 0.77700000000000002, -0.63403125159063511 0.56020458713735533, -0.53071476068518508 0.55304126003523246, -0.5343108192220235 0.5011754225601015, -0.40493624158682306 0.49220537936424585, -0.3863089084840608 0.76086661681561074, -0.61899999999999999 0.77700000000000002),(-0.32200000000000001 0.50600000000000001, -0.185 0.73499999999999999, -0.046 0.42799999999999999, -0.32200000000000001 0.50600000000000001))'
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"orthogonalize: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
# multipolygon
polygon = QgsGeometry.fromWkt(
'MultiPolygon(((-0.550 -1.553, -0.182 -0.954, -0.182 -0.954, 0.186 -1.538, -0.550 -1.553)),'
'((0.506 -1.376, 0.433 -1.081, 0.765 -0.900, 0.923 -1.132, 0.923 -1.391, 0.506 -1.376)))')
o = polygon.orthogonalize()
exp = 'MultiPolygon (((-0.55000000000000004 -1.55299999999999994, -0.182 -0.95399999999999996, -0.182 -0.95399999999999996, 0.186 -1.53800000000000003, -0.55000000000000004 -1.55299999999999994)),((0.50600000000000001 -1.37599999999999989, 0.34888970623957499 -1.04704644438350125, 0.78332709454235683 -0.83955640656085295, 0.92300000000000004 -1.1319999999999999, 0.91737248858460974 -1.38514497083566535, 0.50600000000000001 -1.37599999999999989)))'
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"orthogonalize: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
# line
line = QgsGeometry.fromWkt(
'LineString (-1.07445631048298162 -0.91619958829825165, 0.04022568180912156 -0.95572731852137571, 0.04741254184968957 -0.61794489661467789, 0.68704308546024517 -0.66106605685808595)')
o = line.orthogonalize()
exp = 'LineString (-1.07445631048298162 -0.91619958829825165, 0.04812855116470245 -0.96433184892270418, 0.06228000950284909 -0.63427853851139493, 0.68704308546024517 -0.66106605685808595)'
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"orthogonalize: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testPolygonize(self):
o = QgsGeometry.polygonize([])
self.assertFalse(o)
empty = QgsGeometry()
o = QgsGeometry.polygonize([empty])
self.assertFalse(o)
line = QgsGeometry.fromWkt('LineString EMPTY')
o = QgsGeometry.polygonize([line])
self.assertFalse(o)
l1 = QgsGeometry.fromWkt("LINESTRING (100 180, 20 20, 160 20, 100 180)")
l2 = QgsGeometry.fromWkt("LINESTRING (100 180, 80 60, 120 60, 100 180)")
o = QgsGeometry.polygonize([l1, l2])
exp = "GeometryCollection(POLYGON ((100 180, 160 20, 20 20, 100 180), (100 180, 80 60, 120 60, 100 180)),POLYGON ((100 180, 120 60, 80 60, 100 180)))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"polygonize: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
lines = [QgsGeometry.fromWkt('LineString(0 0, 1 1)'),
QgsGeometry.fromWkt('LineString(0 0, 0 1)'),
QgsGeometry.fromWkt('LineString(0 1, 1 1)'),
QgsGeometry.fromWkt('LineString(1 1, 1 0)'),
QgsGeometry.fromWkt('LineString(1 0, 0 0)'),
QgsGeometry.fromWkt('LineString(5 5, 6 6)'),
QgsGeometry.fromWkt('Point(0, 0)')]
o = QgsGeometry.polygonize(lines)
exp = "GeometryCollection (Polygon ((0 0, 1 1, 1 0, 0 0)),Polygon ((1 1, 0 0, 0 1, 1 1)))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"polygonize: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testDelaunayTriangulation(self):
empty = QgsGeometry()
o = empty.delaunayTriangulation()
self.assertFalse(o)
line = QgsGeometry.fromWkt('LineString EMPTY')
o = line.delaunayTriangulation()
self.assertFalse(o)
input = QgsGeometry.fromWkt("MULTIPOINT ((10 10), (10 20), (20 20))")
o = input.delaunayTriangulation()
exp = "GEOMETRYCOLLECTION (POLYGON ((10 20, 10 10, 20 20, 10 20)))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
o = input.delaunayTriangulation(0, True)
exp = "MultiLineString ((10 20, 20 20),(10 10, 10 20),(10 10, 20 20))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt(
"MULTIPOINT ((50 40), (140 70), (80 100), (130 140), (30 150), (70 180), (190 110), (120 20))")
o = input.delaunayTriangulation()
exp = "GEOMETRYCOLLECTION (POLYGON ((30 150, 50 40, 80 100, 30 150)), POLYGON ((30 150, 80 100, 70 180, 30 150)), POLYGON ((70 180, 80 100, 130 140, 70 180)), POLYGON ((70 180, 130 140, 190 110, 70 180)), POLYGON ((190 110, 130 140, 140 70, 190 110)), POLYGON ((190 110, 140 70, 120 20, 190 110)), POLYGON ((120 20, 140 70, 80 100, 120 20)), POLYGON ((120 20, 80 100, 50 40, 120 20)), POLYGON ((80 100, 140 70, 130 140, 80 100)))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
o = input.delaunayTriangulation(0, True)
exp = "MultiLineString ((70 180, 190 110),(30 150, 70 180),(30 150, 50 40),(50 40, 120 20),(120 20, 190 110),(120 20, 140 70),(140 70, 190 110),(130 140, 140 70),(130 140, 190 110),(70 180, 130 140),(80 100, 130 140),(70 180, 80 100),(30 150, 80 100),(50 40, 80 100),(80 100, 120 20),(80 100, 140 70))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt(
"MULTIPOINT ((10 10), (10 20), (20 20), (20 10), (20 0), (10 0), (0 0), (0 10), (0 20))")
o = input.delaunayTriangulation()
exp = "GEOMETRYCOLLECTION (POLYGON ((0 20, 0 10, 10 10, 0 20)), POLYGON ((0 20, 10 10, 10 20, 0 20)), POLYGON ((10 20, 10 10, 20 10, 10 20)), POLYGON ((10 20, 20 10, 20 20, 10 20)), POLYGON ((10 0, 20 0, 10 10, 10 0)), POLYGON ((10 0, 10 10, 0 10, 10 0)), POLYGON ((10 0, 0 10, 0 0, 10 0)), POLYGON ((10 10, 20 0, 20 10, 10 10)))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
o = input.delaunayTriangulation(0, True)
exp = "MultiLineString ((10 20, 20 20),(0 20, 10 20),(0 10, 0 20),(0 0, 0 10),(0 0, 10 0),(10 0, 20 0),(20 0, 20 10),(20 10, 20 20),(10 20, 20 10),(10 10, 20 10),(10 10, 10 20),(0 20, 10 10),(0 10, 10 10),(10 0, 10 10),(0 10, 10 0),(10 10, 20 0))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt(
"POLYGON ((42 30, 41.96 29.61, 41.85 29.23, 41.66 28.89, 41.41 28.59, 41.11 28.34, 40.77 28.15, 40.39 28.04, 40 28, 39.61 28.04, 39.23 28.15, 38.89 28.34, 38.59 28.59, 38.34 28.89, 38.15 29.23, 38.04 29.61, 38 30, 38.04 30.39, 38.15 30.77, 38.34 31.11, 38.59 31.41, 38.89 31.66, 39.23 31.85, 39.61 31.96, 40 32, 40.39 31.96, 40.77 31.85, 41.11 31.66, 41.41 31.41, 41.66 31.11, 41.85 30.77, 41.96 30.39, 42 30))")
o = input.delaunayTriangulation(0, True)
# depending on GEOS version, the result will be one of these two. Either is correct.
# older GEOS
exp = "MULTILINESTRING ((41.66 31.11, 41.85 30.77), (41.41 31.41, 41.66 31.11), (41.11 31.66, 41.41 31.41), (40.77 31.85, 41.11 31.66), (40.39 31.96, 40.77 31.85), (40 32, 40.39 31.96), (39.61 31.96, 40 32), (39.23 31.85, 39.61 31.96), (38.89 31.66, 39.23 31.85), (38.59 31.41, 38.89 31.66), (38.34 31.11, 38.59 31.41), (38.15 30.77, 38.34 31.11), (38.04 30.39, 38.15 30.77), (38 30, 38.04 30.39), (38 30, 38.04 29.61), (38.04 29.61, 38.15 29.23), (38.15 29.23, 38.34 28.89), (38.34 28.89, 38.59 28.59), (38.59 28.59, 38.89 28.34), (38.89 28.34, 39.23 28.15), (39.23 28.15, 39.61 28.04), (39.61 28.04, 40 28), (40 28, 40.39 28.04), (40.39 28.04, 40.77 28.15), (40.77 28.15, 41.11 28.34), (41.11 28.34, 41.41 28.59), (41.41 28.59, 41.66 28.89), (41.66 28.89, 41.85 29.23), (41.85 29.23, 41.96 29.61), (41.96 29.61, 42 30), (41.96 30.39, 42 30), (41.85 30.77, 41.96 30.39), (41.66 31.11, 41.96 30.39), (41.41 31.41, 41.96 30.39), (41.41 28.59, 41.96 30.39), (41.41 28.59, 41.41 31.41), (38.59 28.59, 41.41 28.59), (38.59 28.59, 41.41 31.41), (38.59 28.59, 38.59 31.41), (38.59 31.41, 41.41 31.41), (38.59 31.41, 39.61 31.96), (39.61 31.96, 41.41 31.41), (39.61 31.96, 40.39 31.96), (40.39 31.96, 41.41 31.41), (40.39 31.96, 41.11 31.66), (38.04 30.39, 38.59 28.59), (38.04 30.39, 38.59 31.41), (38.04 30.39, 38.34 31.11), (38.04 29.61, 38.59 28.59), (38.04 29.61, 38.04 30.39), (39.61 28.04, 41.41 28.59), (38.59 28.59, 39.61 28.04), (38.89 28.34, 39.61 28.04), (40.39 28.04, 41.41 28.59), (39.61 28.04, 40.39 28.04), (41.96 29.61, 41.96 30.39), (41.41 28.59, 41.96 29.61), (41.66 28.89, 41.96 29.61), (40.39 28.04, 41.11 28.34), (38.04 29.61, 38.34 28.89), (38.89 31.66, 39.61 31.96))"
# newer GEOS
exp2 = "MultiLineString ((41.66 31.11, 41.85 30.77),(41.41 31.41, 41.66 31.11),(41.11 31.66, 41.41 31.41),(40.77 31.85, 41.11 31.66),(40.39 31.96, 40.77 31.85),(40 32, 40.39 31.96),(39.61 31.96, 40 32),(39.23 31.85, 39.61 31.96),(38.89 31.66, 39.23 31.85),(38.59 31.41, 38.89 31.66),(38.34 31.11, 38.59 31.41),(38.15 30.77, 38.34 31.11),(38.04 30.39, 38.15 30.77),(38 30, 38.04 30.39),(38 30, 38.04 29.61),(38.04 29.61, 38.15 29.23),(38.15 29.23, 38.34 28.89),(38.34 28.89, 38.59 28.59),(38.59 28.59, 38.89 28.34),(38.89 28.34, 39.23 28.15),(39.23 28.15, 39.61 28.04),(39.61 28.04, 40 28),(40 28, 40.39 28.04),(40.39 28.04, 40.77 28.15),(40.77 28.15, 41.11 28.34),(41.11 28.34, 41.41 28.59),(41.41 28.59, 41.66 28.89),(41.66 28.89, 41.85 29.23),(41.85 29.23, 41.96 29.61),(41.96 29.61, 42 30),(41.96 30.39, 42 30),(41.85 30.77, 41.96 30.39),(41.66 31.11, 41.96 30.39),(41.41 31.41, 41.96 30.39),(41.96 29.61, 41.96 30.39),(41.41 31.41, 41.96 29.61),(41.41 28.59, 41.96 29.61),(41.41 28.59, 41.41 31.41),(38.59 31.41, 41.41 28.59),(38.59 31.41, 41.41 31.41),(38.59 31.41, 40.39 31.96),(40.39 31.96, 41.41 31.41),(40.39 31.96, 41.11 31.66),(38.59 31.41, 39.61 31.96),(39.61 31.96, 40.39 31.96),(38.59 28.59, 41.41 28.59),(38.59 28.59, 38.59 31.41),(38.04 29.61, 38.59 28.59),(38.04 29.61, 38.59 31.41),(38.04 29.61, 38.04 30.39),(38.04 30.39, 38.59 31.41),(38.04 30.39, 38.34 31.11),(40.39 28.04, 41.41 28.59),(38.59 28.59, 40.39 28.04),(39.61 28.04, 40.39 28.04),(38.59 28.59, 39.61 28.04),(38.89 28.34, 39.61 28.04),(41.66 28.89, 41.96 29.61),(40.39 28.04, 41.11 28.34),(38.04 29.61, 38.34 28.89),(38.89 31.66, 39.61 31.96))"
result = o.asWkt(2)
if compareWkt(result, exp, 0.00001):
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
else:
self.assertTrue(compareWkt(result, exp2, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp2, result))
input = QgsGeometry.fromWkt(
"POLYGON ((0 0, 0 200, 180 200, 180 0, 0 0), (20 180, 160 180, 160 20, 152.625 146.75, 20 180), (30 160, 150 30, 70 90, 30 160))")
o = input.delaunayTriangulation(0, True)
exp = "MultiLineString ((0 200, 180 200),(0 0, 0 200),(0 0, 180 0),(180 0, 180 200),(152.625 146.75, 180 0),(152.625 146.75, 180 200),(152.625 146.75, 160 180),(160 180, 180 200),(0 200, 160 180),(20 180, 160 180),(0 200, 20 180),(20 180, 30 160),(0 200, 30 160),(0 0, 30 160),(30 160, 70 90),(0 0, 70 90),(70 90, 150 30),(0 0, 150 30),(150 30, 160 20),(0 0, 160 20),(160 20, 180 0),(152.625 146.75, 160 20),(150 30, 152.625 146.75),(70 90, 152.625 146.75),(30 160, 152.625 146.75),(30 160, 160 180))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt(
"MULTIPOINT ((10 10 1), (10 20 2), (20 20 3), (20 10 1.5), (20 0 2.5), (10 0 3.5), (0 0 0), (0 10 .5), (0 20 .25))")
o = input.delaunayTriangulation()
exp = "GeometryCollection (PolygonZ ((0 20 0.25, 0 10 0.5, 10 10 1, 0 20 0.25)),PolygonZ ((0 20 0.25, 10 10 1, 10 20 2, 0 20 0.25)),PolygonZ ((10 20 2, 10 10 1, 20 10 1.5, 10 20 2)),PolygonZ ((10 20 2, 20 10 1.5, 20 20 3, 10 20 2)),PolygonZ ((10 0 3.5, 20 0 2.5, 10 10 1, 10 0 3.5)),PolygonZ ((10 0 3.5, 10 10 1, 0 10 0.5, 10 0 3.5)),PolygonZ ((10 0 3.5, 0 10 0.5, 0 0 0, 10 0 3.5)),PolygonZ ((10 10 1, 20 0 2.5, 20 10 1.5, 10 10 1)))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
o = input.delaunayTriangulation(0, True)
exp = "MultiLineStringZ ((10 20 2, 20 20 3),(0 20 0.25, 10 20 2),(0 10 0.5, 0 20 0.25),(0 0 0, 0 10 0.5),(0 0 0, 10 0 3.5),(10 0 3.5, 20 0 2.5),(20 0 2.5, 20 10 1.5),(20 10 1.5, 20 20 3),(10 20 2, 20 10 1.5),(10 10 1, 20 10 1.5),(10 10 1, 10 20 2),(0 20 0.25, 10 10 1),(0 10 0.5, 10 10 1),(10 0 3.5, 10 10 1),(0 10 0.5, 10 0 3.5),(10 10 1, 20 0 2.5))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt(
"MULTIPOINT((-118.3964065 56.0557),(-118.396406 56.0475),(-118.396407 56.04),(-118.3968 56))")
o = input.delaunayTriangulation(0.001, True)
exp = "MULTILINESTRING ((-118.3964065 56.0557, -118.396406 56.0475), (-118.396407 56.04, -118.396406 56.0475), (-118.3968 56, -118.396407 56.04))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testVoronoi(self):
empty = QgsGeometry()
o = empty.voronoiDiagram()
self.assertFalse(o)
line = QgsGeometry.fromWkt('LineString EMPTY')
o = line.voronoiDiagram()
self.assertFalse(o)
input = QgsGeometry.fromWkt("MULTIPOINT ((150 200))")
o = input.voronoiDiagram()
self.assertTrue(o.isEmpty())
input = QgsGeometry.fromWkt("MULTIPOINT ((150 200), (180 270), (275 163))")
o = input.voronoiDiagram()
if self.geos39:
exp = "GeometryCollection (Polygon ((25 38, 25 295, 221.20588235294118817 210.91176470588234793, 170.02400000000000091 38, 25 38)),Polygon ((400 38, 170.02400000000000091 38, 221.20588235294118817 210.91176470588234793, 400 369.65420560747656964, 400 38)),Polygon ((25 395, 400 395, 400 369.65420560747656964, 221.20588235294118817 210.91176470588234793, 25 295, 25 395)))"
else:
exp = "GeometryCollection (Polygon ((170.02400000000000091 38, 25 38, 25 295, 221.20588235294115975 210.91176470588234793, 170.02400000000000091 38)),Polygon ((400 369.65420560747662648, 400 38, 170.02400000000000091 38, 221.20588235294115975 210.91176470588234793, 400 369.65420560747662648)),Polygon ((25 295, 25 395, 400 395, 400 369.65420560747662648, 221.20588235294115975 210.91176470588234793, 25 295)))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt("MULTIPOINT ((280 300), (420 330), (380 230), (320 160))")
o = input.voronoiDiagram()
if self.geos39:
exp = "GeometryCollection (Polygon ((110 500, 310.35714285714283278 500, 353.515625 298.59375, 306.875 231.96428571428572241, 110 175.71428571428572241, 110 500)),Polygon ((590 -10, 589.16666666666662877 -10, 306.875 231.96428571428572241, 353.515625 298.59375, 590 204, 590 -10)),Polygon ((110 -10, 110 175.71428571428572241, 306.875 231.96428571428572241, 589.16666666666662877 -10, 110 -10)),Polygon ((590 500, 590 204, 353.515625 298.59375, 310.35714285714283278 500, 590 500)))"
else:
exp = "GeometryCollection (Polygon ((110 175.71428571428572241, 110 500, 310.35714285714283278 500, 353.515625 298.59375, 306.875 231.96428571428572241, 110 175.71428571428572241)),Polygon ((590 204, 590 -10, 589.16666666666662877 -10, 306.875 231.96428571428572241, 353.515625 298.59375, 590 204)),Polygon ((589.16666666666662877 -10, 110 -10, 110 175.71428571428572241, 306.875 231.96428571428572241, 589.16666666666662877 -10)),Polygon ((310.35714285714283278 500, 590 500, 590 204, 353.515625 298.59375, 310.35714285714283278 500)))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt("MULTIPOINT ((320 170), (366 246), (530 230), (530 300), (455 277), (490 160))")
o = input.voronoiDiagram()
if self.geos39:
exp = "GeometryCollection (Polygon ((110 -50, 110 349.02631578947364233, 405.31091180866962986 170.28550074738416242, 392.35294117647055145 -50, 110 -50)),Polygon ((740 -50, 392.35294117647055145 -50, 405.31091180866962986 170.28550074738416242, 429.91476778570188344 205.76082797008174907, 470.12061711079945781 217.78821879382888937, 740 63.57142857142859071, 740 -50)),Polygon ((110 510, 323.94382022471910432 510, 429.91476778570188344 205.76082797008174907, 405.31091180866962986 170.28550074738416242, 110 349.02631578947364233, 110 510)),Polygon ((424.57333333333326664 510, 499.70666666666664923 265, 470.12061711079945781 217.78821879382888937, 429.91476778570188344 205.76082797008174907, 323.94382022471910432 510, 424.57333333333326664 510)),Polygon ((740 63.57142857142859071, 470.12061711079945781 217.78821879382888937, 499.70666666666664923 265, 740 265, 740 63.57142857142859071)),Polygon ((740 510, 740 265, 499.70666666666664923 265, 424.57333333333326664 510, 740 510)))"
else:
exp = "GeometryCollection (Polygon ((392.35294117647055145 -50, 110 -50, 110 349.02631578947364233, 405.31091180866962986 170.28550074738416242, 392.35294117647055145 -50)),Polygon ((740 63.57142857142859071, 740 -50, 392.35294117647055145 -50, 405.31091180866962986 170.28550074738416242, 429.91476778570188344 205.76082797008174907, 470.12061711079945781 217.78821879382888937, 740 63.57142857142859071)),Polygon ((110 349.02631578947364233, 110 510, 323.94382022471910432 510, 429.91476778570188344 205.76082797008174907, 405.31091180866962986 170.28550074738416242, 110 349.02631578947364233)),Polygon ((323.94382022471910432 510, 424.57333333333326664 510, 499.70666666666664923 265, 470.12061711079945781 217.78821879382888937, 429.91476778570188344 205.76082797008174907, 323.94382022471910432 510)),Polygon ((740 265, 740 63.57142857142859071, 470.12061711079945781 217.78821879382888937, 499.70666666666664923 265, 740 265)),Polygon ((424.57333333333326664 510, 740 510, 740 265, 499.70666666666664923 265, 424.57333333333326664 510)))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt(
"MULTIPOINT ((280 200), (406 285), (580 280), (550 190), (370 190), (360 90), (480 110), (440 160), (450 180), (480 180), (460 160), (360 210), (360 220), (370 210), (375 227))")
o = input.voronoiDiagram()
if self.geos39:
exp = "GeometryCollection (Polygon ((-20 585, 111.94841269841269593 585, 293.54906542056073704 315.803738317756995, 318.75 215, 323.2352941176470722 179.1176470588235361, 319.39560439560437999 144.560439560439562, -20 -102.27272727272726627, -20 585)),Polygon ((365 200, 365 215, 369.40909090909093493 219.40909090909090651, 414.21192052980131848 206.23178807947019209, 411.875 200, 365 200)),Polygon ((365 215, 365 200, 323.2352941176470722 179.1176470588235361, 318.75 215, 365 215)),Polygon ((-20 -210, -20 -102.27272727272726627, 319.39560439560437999 144.560439560439562, 388.97260273972602818 137.60273972602740855, 419.55882352941176805 102.64705882352940591, 471.66666666666674246 -210, -20 -210)),Polygon ((411.875 200, 410.29411764705884025 187.35294117647057988, 388.97260273972602818 137.60273972602740855, 319.39560439560437999 144.560439560439562, 323.2352941176470722 179.1176470588235361, 365 200, 411.875 200)),Polygon ((410.29411764705884025 187.35294117647057988, 411.875 200, 414.21192052980131848 206.23178807947019209, 431.62536593766145643 234.0192009643533595, 465 248.00476190476189231, 465 175, 450 167.5, 410.29411764705884025 187.35294117647057988)),Polygon ((293.54906542056073704 315.803738317756995, 339.65007656967839011 283.17840735068909908, 369.40909090909093493 219.40909090909090651, 365 215, 318.75 215, 293.54906542056073704 315.803738317756995)),Polygon ((501.69252873563220874 585, 492.56703910614527331 267.43296089385472669, 465 248.00476190476189231, 431.62536593766145643 234.0192009643533595, 339.65007656967839011 283.17840735068909908, 293.54906542056073704 315.803738317756995, 111.94841269841269593 585, 501.69252873563220874 585)),Polygon ((369.40909090909093493 219.40909090909090651, 339.65007656967839011 283.17840735068909908, 431.62536593766145643 234.0192009643533595, 414.21192052980131848 206.23178807947019209, 369.40909090909093493 219.40909090909090651)),Polygon ((388.97260273972602818 137.60273972602740855, 410.29411764705884025 187.35294117647057988, 450 167.5, 450 127, 419.55882352941176805 102.64705882352940591, 388.97260273972602818 137.60273972602740855)),Polygon ((465 175, 465 248.00476190476189231, 492.56703910614527331 267.43296089385472669, 505 255, 520.71428571428566556 145, 495 145, 465 175)),Polygon ((880 -210, 471.66666666666674246 -210, 419.55882352941176805 102.64705882352940591, 450 127, 495 145, 520.71428571428566556 145, 880 -169.375, 880 -210)),Polygon ((465 175, 495 145, 450 127, 450 167.5, 465 175)),Polygon ((880 585, 880 130, 505 255, 492.56703910614527331 267.43296089385472669, 501.69252873563220874 585, 880 585)),Polygon ((880 -169.375, 520.71428571428566556 145, 505 255, 880 130, 880 -169.375)))"
else:
exp = "GeometryCollection (Polygon ((-20 -102.27272727272726627, -20 585, 111.94841269841269593 585, 293.54906542056073704 315.803738317756995, 318.75 215, 323.2352941176470722 179.1176470588235361, 319.39560439560437999 144.560439560439562, -20 -102.27272727272726627)),Polygon ((365 200, 365 215, 369.40909090909093493 219.40909090909090651, 414.21192052980131848 206.23178807947019209, 411.875 200, 365 200)),Polygon ((365 215, 365 200, 323.2352941176470722 179.1176470588235361, 318.75 215, 365 215)),Polygon ((471.66666666666674246 -210, -20 -210, -20 -102.27272727272726627, 319.39560439560437999 144.560439560439562, 388.97260273972602818 137.60273972602738013, 419.55882352941176805 102.64705882352942012, 471.66666666666674246 -210)),Polygon ((411.875 200, 410.29411764705884025 187.35294117647057988, 388.97260273972602818 137.60273972602738013, 319.39560439560437999 144.560439560439562, 323.2352941176470722 179.1176470588235361, 365 200, 411.875 200)),Polygon ((410.29411764705884025 187.35294117647057988, 411.875 200, 414.21192052980131848 206.23178807947019209, 431.62536593766145643 234.0192009643533595, 465 248.00476190476189231, 465 175, 450 167.5, 410.29411764705884025 187.35294117647057988)),Polygon ((293.54906542056073704 315.803738317756995, 339.65007656967839011 283.17840735068909908, 369.40909090909093493 219.40909090909090651, 365 215, 318.75 215, 293.54906542056073704 315.803738317756995)),Polygon ((111.94841269841269593 585, 501.69252873563215189 585, 492.56703910614521646 267.43296089385472669, 465 248.00476190476189231, 431.62536593766145643 234.0192009643533595, 339.65007656967839011 283.17840735068909908, 293.54906542056073704 315.803738317756995, 111.94841269841269593 585)),Polygon ((369.40909090909093493 219.40909090909090651, 339.65007656967839011 283.17840735068909908, 431.62536593766145643 234.0192009643533595, 414.21192052980131848 206.23178807947019209, 369.40909090909093493 219.40909090909090651)),Polygon ((388.97260273972602818 137.60273972602738013, 410.29411764705884025 187.35294117647057988, 450 167.5, 450 127, 419.55882352941176805 102.64705882352942012, 388.97260273972602818 137.60273972602738013)),Polygon ((465 175, 465 248.00476190476189231, 492.56703910614521646 267.43296089385472669, 505 255, 520.71428571428566556 145, 495 145, 465 175)),Polygon ((880 -169.375, 880 -210, 471.66666666666674246 -210, 419.55882352941176805 102.64705882352942012, 450 127, 495 145, 520.71428571428566556 145, 880 -169.375)),Polygon ((465 175, 495 145, 450 127, 450 167.5, 465 175)),Polygon ((501.69252873563215189 585, 880 585, 880 130.00000000000005684, 505 255, 492.56703910614521646 267.43296089385472669, 501.69252873563215189 585)),Polygon ((880 130.00000000000005684, 880 -169.375, 520.71428571428566556 145, 505 255, 880 130.00000000000005684)))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt(
"MULTIPOINT ((100 200), (105 202), (110 200), (140 230), (210 240), (220 190), (170 170), (170 260), (213 245), (220 190))")
o = input.voronoiDiagram(QgsGeometry(), 6)
if self.geos39:
exp = "GeometryCollection (Polygon ((-20 50, -20 380, -3.75 380, 105 235, 105 115, 77.1428571428571388 50, -20 50)),Polygon ((77.1428571428571388 50, 105 115, 145 195, 178.33333333333334281 211.66666666666665719, 183.51851851851850483 208.70370370370369528, 246.99999999999997158 50, 77.1428571428571388 50)),Polygon ((20.00000000000000711 380, 176.66666666666665719 223.33333333333334281, 178.33333333333334281 211.66666666666665719, 145 195, 105 235, -3.75 380, 20.00000000000000711 380)),Polygon ((105 115, 105 235, 145 195, 105 115)),Polygon ((255 380, 176.66666666666665719 223.33333333333334281, 20.00000000000000711 380, 255 380)),Polygon ((340 380, 340 240, 183.51851851851850483 208.70370370370369528, 178.33333333333334281 211.66666666666665719, 176.66666666666665719 223.33333333333334281, 255 380, 340 380)),Polygon ((340 50, 246.99999999999997158 50, 183.51851851851850483 208.70370370370369528, 340 240, 340 50)))"
else:
exp = "GeometryCollection (Polygon ((77.1428571428571388 50, -20 50, -20 380, -3.75 380, 105 235, 105 115, 77.1428571428571388 50)),Polygon ((247 50, 77.1428571428571388 50, 105 115, 145 195, 178.33333333333334281 211.66666666666665719, 183.51851851851853326 208.70370370370369528, 247 50)),Polygon ((-3.75 380, 20.00000000000000711 380, 176.66666666666665719 223.33333333333334281, 178.33333333333334281 211.66666666666665719, 145 195, 105 235, -3.75 380)),Polygon ((105 115, 105 235, 145 195, 105 115)),Polygon ((20.00000000000000711 380, 255 380, 176.66666666666665719 223.33333333333334281, 20.00000000000000711 380)),Polygon ((255 380, 340 380, 340 240, 183.51851851851853326 208.70370370370369528, 178.33333333333334281 211.66666666666665719, 176.66666666666665719 223.33333333333334281, 255 380)),Polygon ((340 240, 340 50, 247 50, 183.51851851851853326 208.70370370370369528, 340 240)))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt(
"MULTIPOINT ((170 270), (177 275), (190 230), (230 250), (210 290), (240 280), (240 250))")
o = input.voronoiDiagram(QgsGeometry(), 10)
if self.geos39:
exp = "GeometryCollection (Polygon ((100 360, 150 360, 200 260, 100 210, 100 360)),Polygon ((250 360, 220 270, 200 260, 150 360, 250 360)),Polygon ((100 160, 100 210, 200 260, 235 190, 247 160, 100 160)),Polygon ((220 270, 235 265, 235 190, 200 260, 220 270)),Polygon ((310 360, 310 265, 235 265, 220 270, 250 360, 310 360)),Polygon ((310 160, 247 160, 235 190, 235 265, 310 265, 310 160)))"
else:
exp = "GeometryCollection (Polygon ((100 210, 100 360, 150 360, 200 260, 100 210)),Polygon ((150 360, 250 360, 220 270, 200 260, 150 360)),Polygon ((247 160, 100 160, 100 210, 200 260, 235 190, 247 160)),Polygon ((220 270, 235 265, 235 190, 200 260, 220 270)),Polygon ((250 360, 310 360, 310 265, 235 265, 220 270, 250 360)),Polygon ((310 265, 310 160, 247 160, 235 190, 235 265, 310 265)))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt(
"MULTIPOINT ((155 271), (150 360), (260 360), (271 265), (280 260), (270 370), (154 354), (150 260))")
o = input.voronoiDiagram(QgsGeometry(), 100)
if self.geos39:
exp = "GeometryCollection (Polygon ((20 130, 20 310, 205 310, 215 299, 215 130, 20 130)),Polygon ((410 500, 410 338, 215 299, 205 310, 205 500, 410 500)),Polygon ((20 500, 205 500, 205 310, 20 310, 20 500)),Polygon ((410 130, 215 130, 215 299, 410 338, 410 130)))"
else:
exp = "GeometryCollection (Polygon ((215 130, 20 130, 20 310, 205 310, 215 299, 215 130)),Polygon ((205 500, 410 500, 410 338, 215 299, 205 310, 205 500)),Polygon ((20 310, 20 500, 205 500, 205 310, 20 310)),Polygon ((410 338, 410 130, 215 130, 215 299, 410 338)))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"delaunay: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testDensifyByCount(self):
empty = QgsGeometry()
o = empty.densifyByCount(4)
self.assertFalse(o)
# point
input = QgsGeometry.fromWkt("PointZ( 1 2 3 )")
o = input.densifyByCount(100)
exp = "PointZ( 1 2 3 )"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt(
"MULTIPOINT ((155 271), (150 360), (260 360), (271 265), (280 260), (270 370), (154 354), (150 260))")
o = input.densifyByCount(100)
exp = "MULTIPOINT ((155 271), (150 360), (260 360), (271 265), (280 260), (270 370), (154 354), (150 260))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
# line
input = QgsGeometry.fromWkt("LineString( 0 0, 10 0, 10 10 )")
o = input.densifyByCount(0)
exp = "LineString( 0 0, 10 0, 10 10 )"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
o = input.densifyByCount(1)
exp = "LineString( 0 0, 5 0, 10 0, 10 5, 10 10 )"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
o = input.densifyByCount(3)
exp = "LineString( 0 0, 2.5 0, 5 0, 7.5 0, 10 0, 10 2.5, 10 5, 10 7.5, 10 10 )"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt("LineStringZ( 0 0 1, 10 0 2, 10 10 0)")
o = input.densifyByCount(1)
exp = "LineStringZ( 0 0 1, 5 0 1.5, 10 0 2, 10 5 1, 10 10 0 )"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt("LineStringM( 0 0 0, 10 0 2, 10 10 0)")
o = input.densifyByCount(1)
exp = "LineStringM( 0 0 0, 5 0 1, 10 0 2, 10 5 1, 10 10 0 )"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt("LineStringZM( 0 0 1 10, 10 0 2 8, 10 10 0 4)")
o = input.densifyByCount(1)
exp = "LineStringZM( 0 0 1 10, 5 0 1.5 9, 10 0 2 8, 10 5 1 6, 10 10 0 4 )"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
# polygon
input = QgsGeometry.fromWkt("Polygon(( 0 0, 10 0, 10 10, 0 0 ))")
o = input.densifyByCount(0)
exp = "Polygon(( 0 0, 10 0, 10 10, 0 0 ))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt("PolygonZ(( 0 0 1, 10 0 2, 10 10 0, 0 0 1 ))")
o = input.densifyByCount(1)
exp = "PolygonZ(( 0 0 1, 5 0 1.5, 10 0 2, 10 5 1, 10 10 0, 5 5 0.5, 0 0 1 ))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt("PolygonZM(( 0 0 1 4, 10 0 2 6, 10 10 0 8, 0 0 1 4 ))")
o = input.densifyByCount(1)
exp = "PolygonZM(( 0 0 1 4, 5 0 1.5 5, 10 0 2 6, 10 5 1 7, 10 10 0 8, 5 5 0.5 6, 0 0 1 4 ))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
# (not strictly valid, but shouldn't matter!
input = QgsGeometry.fromWkt(
"PolygonZM(( 0 0 1 4, 10 0 2 6, 10 10 0 8, 0 0 1 4 ), ( 0 0 1 4, 10 0 2 6, 10 10 0 8, 0 0 1 4 ) )")
o = input.densifyByCount(1)
exp = "PolygonZM(( 0 0 1 4, 5 0 1.5 5, 10 0 2 6, 10 5 1 7, 10 10 0 8, 5 5 0.5 6, 0 0 1 4 ),( 0 0 1 4, 5 0 1.5 5, 10 0 2 6, 10 5 1 7, 10 10 0 8, 5 5 0.5 6, 0 0 1 4 ))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
# multi line
input = QgsGeometry.fromWkt(
"MultiLineString(( 0 0, 5 0, 10 0, 10 5, 10 10), (20 0, 25 0, 30 0, 30 5, 30 10 ) )")
o = input.densifyByCount(1)
exp = "MultiLineString(( 0 0, 2.5 0, 5 0, 7.5 0, 10 0, 10 2.5, 10 5, 10 7.5, 10 10 ),( 20 0, 22.5 0, 25 0, 27.5 0, 30 0, 30 2.5, 30 5, 30 7.5, 30 10 ))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
# multipolygon
input = QgsGeometry.fromWkt(
"MultiPolygonZ((( 0 0 1, 10 0 2, 10 10 0, 0 0 1)),(( 0 0 1, 10 0 2, 10 10 0, 0 0 1 )))")
o = input.densifyByCount(1)
exp = "MultiPolygonZ((( 0 0 1, 5 0 1.5, 10 0 2, 10 5 1, 10 10 0, 5 5 0.5, 0 0 1 )),(( 0 0 1, 5 0 1.5, 10 0 2, 10 5 1, 10 10 0, 5 5 0.5, 0 0 1 )))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testDensifyByDistance(self):
empty = QgsGeometry()
o = empty.densifyByDistance(4)
self.assertFalse(o)
# point
input = QgsGeometry.fromWkt("PointZ( 1 2 3 )")
o = input.densifyByDistance(0.1)
exp = "PointZ( 1 2 3 )"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt(
"MULTIPOINT ((155 271), (150 360), (260 360), (271 265), (280 260), (270 370), (154 354), (150 260))")
o = input.densifyByDistance(0.1)
exp = "MULTIPOINT ((155 271), (150 360), (260 360), (271 265), (280 260), (270 370), (154 354), (150 260))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
# line
input = QgsGeometry.fromWkt("LineString( 0 0, 10 0, 10 10 )")
o = input.densifyByDistance(100)
exp = "LineString( 0 0, 10 0, 10 10 )"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
o = input.densifyByDistance(3)
exp = "LineString (0 0, 2.5 0, 5 0, 7.5 0, 10 0, 10 2.5, 10 5, 10 7.5, 10 10)"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt("LineStringZ( 0 0 1, 10 0 2, 10 10 0)")
o = input.densifyByDistance(6)
exp = "LineStringZ (0 0 1, 5 0 1.5, 10 0 2, 10 5 1, 10 10 0)"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt("LineStringM( 0 0 0, 10 0 2, 10 10 0)")
o = input.densifyByDistance(3)
exp = "LineStringM (0 0 0, 2.5 0 0.5, 5 0 1, 7.5 0 1.5, 10 0 2, 10 2.5 1.5, 10 5 1, 10 7.5 0.5, 10 10 0)"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt("LineStringZM( 0 0 1 10, 10 0 2 8, 10 10 0 4)")
o = input.densifyByDistance(6)
exp = "LineStringZM (0 0 1 10, 5 0 1.5 9, 10 0 2 8, 10 5 1 6, 10 10 0 4)"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
# polygon
input = QgsGeometry.fromWkt("Polygon(( 0 0, 20 0, 20 20, 0 0 ))")
o = input.densifyByDistance(110)
exp = "Polygon(( 0 0, 20 0, 20 20, 0 0 ))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
input = QgsGeometry.fromWkt("PolygonZ(( 0 0 1, 20 0 2, 20 20 0, 0 0 1 ))")
o = input.densifyByDistance(6)
exp = "PolygonZ ((0 0 1, 5 0 1.25, 10 0 1.5, 15 0 1.75, 20 0 2, 20 5 1.5, 20 10 1, 20 15 0.5, 20 20 0, 16 16 0.2, 12 12 0.4, 8 8 0.6, 4 4 0.8, 0 0 1))"
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"densify by count: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testCentroid(self):
tests = [["POINT(10 0)", "POINT(10 0)"],
["POINT(10 10)", "POINT(10 10)"],
["MULTIPOINT((10 10), (20 20) )", "POINT(15 15)"],
[" MULTIPOINT((10 10), (20 20), (10 20), (20 10))", "POINT(15 15)"],
["LINESTRING(10 10, 20 20)", "POINT(15 15)"],
["LINESTRING(0 0, 10 0)", "POINT(5 0 )"],
["LINESTRING (10 10, 10 10)", "POINT (10 10)"], # zero length line
["MULTILINESTRING ((10 10, 10 10), (20 20, 20 20))", "POINT (15 15)"], # zero length multiline
["LINESTRING (60 180, 120 100, 180 180)", "POINT (120 140)"],
["LINESTRING (80 0, 80 120, 120 120, 120 0)", "POINT (100 68.57142857142857)"],
["MULTILINESTRING ((0 0, 0 100), (100 0, 100 100))", "POINT (50 50)"],
[" MULTILINESTRING ((0 0, 0 200, 200 200, 200 0, 0 0),(60 180, 20 180, 20 140, 60 140, 60 180))",
"POINT (90 110)"],
[
"MULTILINESTRING ((20 20, 60 60),(20 -20, 60 -60),(-20 -20, -60 -60),(-20 20, -60 60),(-80 0, 0 80, 80 0, 0 -80, -80 0),(-40 20, -40 -20),(-20 40, 20 40),(40 20, 40 -20),(20 -40, -20 -40))",
"POINT (0 0)"],
["POLYGON((0 0, 10 0, 10 10, 0 10, 0 0))", "POINT (5 5)"],
["POLYGON ((40 160, 160 160, 160 40, 40 40, 40 160))", "POINT (100 100)"],
["POLYGON ((0 200, 200 200, 200 0, 0 0, 0 200), (20 180, 80 180, 80 20, 20 20, 20 180))",
"POINT (115.78947368421052 100)"],
["POLYGON ((0 0, 0 200, 200 200, 200 0, 0 0),(60 180, 20 180, 20 140, 60 140, 60 180))",
"POINT (102.5 97.5)"],
[
"POLYGON ((0 0, 0 200, 200 200, 200 0, 0 0),(60 180, 20 180, 20 140, 60 140, 60 180),(180 60, 140 60, 140 20, 180 20, 180 60))",
"POINT (100 100)"],
[
"MULTIPOLYGON (((0 40, 0 140, 140 140, 140 120, 20 120, 20 40, 0 40)),((0 0, 0 20, 120 20, 120 100, 140 100, 140 0, 0 0)))",
"POINT (70 70)"],
[
"GEOMETRYCOLLECTION (POLYGON ((0 200, 20 180, 20 140, 60 140, 200 0, 0 0, 0 200)),POLYGON ((200 200, 0 200, 20 180, 60 180, 60 140, 200 0, 200 200)))",
"POINT (102.5 97.5)"],
[
"GEOMETRYCOLLECTION (LINESTRING (80 0, 80 120, 120 120, 120 0),MULTIPOINT ((20 60), (40 80), (60 60)))",
"POINT (100 68.57142857142857)"],
["GEOMETRYCOLLECTION (POLYGON ((0 40, 40 40, 40 0, 0 0, 0 40)),LINESTRING (80 0, 80 80, 120 40))",
"POINT (20 20)"],
[
"GEOMETRYCOLLECTION (POLYGON ((0 40, 40 40, 40 0, 0 0, 0 40)),LINESTRING (80 0, 80 80, 120 40),MULTIPOINT ((20 60), (40 80), (60 60)))",
"POINT (20 20)"],
["GEOMETRYCOLLECTION (POLYGON ((10 10, 10 10, 10 10, 10 10)),LINESTRING (20 20, 30 30))",
"POINT (25 25)"],
["GEOMETRYCOLLECTION (POLYGON ((10 10, 10 10, 10 10, 10 10)),LINESTRING (20 20, 20 20))",
"POINT (15 15)"],
[
"GEOMETRYCOLLECTION (POLYGON ((10 10, 10 10, 10 10, 10 10)),LINESTRING (20 20, 20 20),MULTIPOINT ((20 10), (10 20)) )",
"POINT (15 15)"],
# ["GEOMETRYCOLLECTION (POLYGON ((10 10, 10 10, 10 10, 10 10)),LINESTRING (20 20, 20 20),POINT EMPTY )","POINT (15 15)"],
# ["GEOMETRYCOLLECTION (POLYGON ((10 10, 10 10, 10 10, 10 10)),LINESTRING EMPTY,POINT EMPTY )","POINT (10 10)"],
[
"GEOMETRYCOLLECTION (POLYGON ((20 100, 20 -20, 60 -20, 60 100, 20 100)),POLYGON ((-20 60, 100 60, 100 20, -20 20, -20 60)))",
"POINT (40 40)"],
["POLYGON ((40 160, 160 160, 160 160, 40 160, 40 160))", "POINT (100 160)"],
["POLYGON ((10 10, 100 100, 100 100, 10 10))", "POINT (55 55)"],
# ["POLYGON EMPTY","POINT EMPTY"],
# ["MULTIPOLYGON(EMPTY,((0 0,1 0,1 1,0 1, 0 0)))","POINT (0.5 0.5)"],
[
"POLYGON((56.528666666700 25.2101666667,56.529000000000 25.2105000000,56.528833333300 25.2103333333,56.528666666700 25.2101666667))",
"POINT (56.52883333335 25.21033333335)"],
[
"POLYGON((56.528666666700 25.2101666667,56.529000000000 25.2105000000,56.528833333300 25.2103333333,56.528666666700 25.2101666667))",
"POINT (56.528833 25.210333)"]
]
for t in tests:
input = QgsGeometry.fromWkt(t[0])
o = input.centroid()
exp = t[1]
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"centroid: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
# QGIS native algorithms are bad!
if False:
result = QgsGeometry(input.get().centroid()).asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"centroid: mismatch using QgsAbstractGeometry methods Input {} \n Expected:\n{}\nGot:\n{}\n".format(
t[0], exp, result))
def testCompare(self):
lp = [QgsPointXY(1, 1), QgsPointXY(2, 2), QgsPointXY(1, 2), QgsPointXY(1, 1)]
lp2 = [QgsPointXY(1, 1.0000001), QgsPointXY(2, 2), QgsPointXY(1, 2), QgsPointXY(1, 1)]
self.assertTrue(QgsGeometry.compare(lp, lp)) # line-line
self.assertTrue(QgsGeometry.compare([lp], [lp])) # pylygon-polygon
self.assertTrue(QgsGeometry.compare([[lp]], [[lp]])) # multipyolygon-multipolygon
# handling empty values
self.assertFalse(QgsGeometry.compare(None, None))
self.assertFalse(QgsGeometry.compare(lp, [])) # line-line
self.assertFalse(QgsGeometry.compare([lp], [[]])) # pylygon-polygon
self.assertFalse(QgsGeometry.compare([[lp]], [[[]]])) # multipolygon-multipolygon
# tolerance
self.assertFalse(QgsGeometry.compare(lp, lp2))
self.assertTrue(QgsGeometry.compare(lp, lp2, 1e-6))
def testPoint(self):
point = QgsPoint(1, 2)
self.assertEqual(point.wkbType(), QgsWkbTypes.Point)
self.assertEqual(point.x(), 1)
self.assertEqual(point.y(), 2)
point = QgsPoint(1, 2, wkbType=QgsWkbTypes.Point)
self.assertEqual(point.wkbType(), QgsWkbTypes.Point)
self.assertEqual(point.x(), 1)
self.assertEqual(point.y(), 2)
point_z = QgsPoint(1, 2, 3)
self.assertEqual(point_z.wkbType(), QgsWkbTypes.PointZ)
self.assertEqual(point_z.x(), 1)
self.assertEqual(point_z.y(), 2)
self.assertEqual(point_z.z(), 3)
point_z = QgsPoint(1, 2, 3, 4, wkbType=QgsWkbTypes.PointZ)
self.assertEqual(point_z.wkbType(), QgsWkbTypes.PointZ)
self.assertEqual(point_z.x(), 1)
self.assertEqual(point_z.y(), 2)
self.assertEqual(point_z.z(), 3)
point_m = QgsPoint(1, 2, m=3)
self.assertEqual(point_m.wkbType(), QgsWkbTypes.PointM)
self.assertEqual(point_m.x(), 1)
self.assertEqual(point_m.y(), 2)
self.assertEqual(point_m.m(), 3)
point_zm = QgsPoint(1, 2, 3, 4)
self.assertEqual(point_zm.wkbType(), QgsWkbTypes.PointZM)
self.assertEqual(point_zm.x(), 1)
self.assertEqual(point_zm.y(), 2)
self.assertEqual(point_zm.z(), 3)
self.assertEqual(point_zm.m(), 4)
def testSubdivide(self):
tests = [["LINESTRING (1 1,1 9,9 9,9 1)", 8, "MULTILINESTRING ((1 1,1 9,9 9,9 1))"],
["Point (1 1)", 8, "MultiPoint ((1 1))"],
["GeometryCollection ()", 8, "GeometryCollection EMPTY"],
["LINESTRING (1 1,1 2,1 3,1 4,1 5,1 6,1 7,1 8,1 9)", 8,
"MultiLineString ((1 1, 1 2, 1 3, 1 4, 1 5),(1 5, 1 6, 1 7, 1 8, 1 9))"],
["LINESTRING(0 0, 100 100, 150 150)", 8, 'MultiLineString ((0 0, 100 100, 150 150))'],
[
'POLYGON((132 10,119 23,85 35,68 29,66 28,49 42,32 56,22 64,32 110,40 119,36 150,57 158,75 171,92 182,114 184,132 186,146 178,176 184,179 162,184 141,190 122,190 100,185 79,186 56,186 52,178 34,168 18,147 13,132 10))',
10, None],
["LINESTRING (1 1,1 2,1 3,1 4,1 5,1 6,1 7,1 8,1 9)", 1,
"MultiLineString ((1 1, 1 2, 1 3, 1 4, 1 5),(1 5, 1 6, 1 7, 1 8, 1 9))"],
["LINESTRING (1 1,1 2,1 3,1 4,1 5,1 6,1 7,1 8,1 9)", 16,
"MultiLineString ((1 1, 1 2, 1 3, 1 4, 1 5, 1 6, 1 7, 1 8, 1 9))"],
[
"POLYGON ((0 0, 0 200, 200 200, 200 0, 0 0),(60 180, 20 180, 20 140, 60 140, 60 180),(180 60, 140 60, 140 20, 180 20, 180 60))",
8,
"MultiPolygon (((0 0, 0 100, 100 100, 100 0, 0 0)),((100 0, 100 50, 140 50, 140 20, 150 20, 150 0, 100 0)),((150 0, 150 20, 180 20, 180 50, 200 50, 200 0, 150 0)),((100 50, 100 100, 150 100, 150 60, 140 60, 140 50, 100 50)),((150 60, 150 100, 200 100, 200 50, 180 50, 180 60, 150 60)),((0 100, 0 150, 20 150, 20 140, 50 140, 50 100, 0 100)),((50 100, 50 140, 60 140, 60 150, 100 150, 100 100, 50 100)),((0 150, 0 200, 50 200, 50 180, 20 180, 20 150, 0 150)),((50 180, 50 200, 100 200, 100 150, 60 150, 60 180, 50 180)),((100 100, 100 200, 200 200, 200 100, 100 100)))"],
[
"POLYGON((132 10,119 23,85 35,68 29,66 28,49 42,32 56,22 64,32 110,40 119,36 150, 57 158,75 171,92 182,114 184,132 186,146 178,176 184,179 162,184 141,190 122,190 100,185 79,186 56,186 52,178 34,168 18,147 13,132 10))",
10, None]
]
for t in tests:
input = QgsGeometry.fromWkt(t[0])
o = input.subdivide(t[1])
# make sure area is unchanged
self.assertAlmostEqual(input.area(), o.area(), 5)
max_points = 999999
for p in range(o.constGet().numGeometries()):
part = o.constGet().geometryN(p)
self.assertLessEqual(part.nCoordinates(), max(t[1], 8))
if t[2]:
exp = t[2]
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"clipped: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testClipped(self):
tests = [["LINESTRING (1 1,1 9,9 9,9 1)", QgsRectangle(0, 0, 10, 10), "LINESTRING (1 1,1 9,9 9,9 1)"],
["LINESTRING (-1 -9,-1 11,9 11)", QgsRectangle(0, 0, 10, 10),
"GEOMETRYCOLLECTION EMPTY"],
["LINESTRING (-1 5,5 5,9 9)", QgsRectangle(0, 0, 10, 10), "LINESTRING (0 5,5 5,9 9)"],
["LINESTRING (5 5,8 5,12 5)", QgsRectangle(0, 0, 10, 10), "LINESTRING (5 5,8 5,10 5)"],
["LINESTRING (5 -1,5 5,1 2,-3 2,1 6)", QgsRectangle(0, 0, 10, 10),
"MULTILINESTRING ((5 0,5 5,1 2,0 2),(0 5,1 6))"],
["LINESTRING (0 3,0 5,0 7)", QgsRectangle(0, 0, 10, 10),
"GEOMETRYCOLLECTION EMPTY"],
["LINESTRING (0 3,0 5,-1 7)", QgsRectangle(0, 0, 10, 10),
"GEOMETRYCOLLECTION EMPTY"],
["LINESTRING (0 3,0 5,2 7)", QgsRectangle(0, 0, 10, 10), "LINESTRING (0 5,2 7)"],
["LINESTRING (2 1,0 0,1 2)", QgsRectangle(0, 0, 10, 10), "LINESTRING (2 1,0 0,1 2)"],
["LINESTRING (3 3,0 3,0 5,2 7)", QgsRectangle(0, 0, 10, 10), "MULTILINESTRING ((3 3,0 3),(0 5,2 7))"],
["LINESTRING (5 5,10 5,20 5)", QgsRectangle(0, 0, 10, 10), "LINESTRING (5 5,10 5)"],
["LINESTRING (3 3,0 6,3 9)", QgsRectangle(0, 0, 10, 10), "LINESTRING (3 3,0 6,3 9)"],
["POLYGON ((5 5,5 6,6 6,6 5,5 5))", QgsRectangle(0, 0, 10, 10), "POLYGON ((5 5,5 6,6 6,6 5,5 5))"],
["POLYGON ((15 15,15 16,16 16,16 15,15 15))", QgsRectangle(0, 0, 10, 10),
"GEOMETRYCOLLECTION EMPTY"],
["POLYGON ((-1 -1,-1 11,11 11,11 -1,-1 -1))", QgsRectangle(0, 0, 10, 10),
"Polygon ((0 0, 0 10, 10 10, 10 0, 0 0))"],
["POLYGON ((-1 -1,-1 5,5 5,5 -1,-1 -1))", QgsRectangle(0, 0, 10, 10),
"Polygon ((0 0, 0 5, 5 5, 5 0, 0 0))"],
["POLYGON ((-2 -2,-2 5,5 5,5 -2,-2 -2), (3 3,4 4,4 2,3 3))", QgsRectangle(0, 0, 10, 10),
"Polygon ((0 0, 0 5, 5 5, 5 0, 0 0),(3 3, 4 4, 4 2, 3 3))"]
]
for t in tests:
input = QgsGeometry.fromWkt(t[0])
o = input.clipped(t[1])
exp = t[2]
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.00001),
"clipped: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testCreateWedgeBuffer(self):
tests = [[QgsPoint(1, 11), 0, 45, 2, 0,
'CurvePolygon (CompoundCurve (CircularString (0.23463313526982044 12.84775906502257392, 1 13, 1.76536686473017967 12.84775906502257392),(1.76536686473017967 12.84775906502257392, 1 11),(1 11, 0.23463313526982044 12.84775906502257392)))'],
[QgsPoint(1, 11), 90, 45, 2, 0,
'CurvePolygon (CompoundCurve (CircularString (2.84775906502257348 11.76536686473017923, 3 11, 2.84775906502257348 10.23463313526982077),(2.84775906502257348 10.23463313526982077, 1 11),(1 11, 2.84775906502257348 11.76536686473017923)))'],
[QgsPoint(1, 11), 180, 90, 2, 0,
'CurvePolygon (CompoundCurve (CircularString (2.41421356237309492 9.58578643762690419, 1.00000000000000022 9, -0.41421356237309492 9.58578643762690419),(-0.41421356237309492 9.58578643762690419, 1 11),(1 11, 2.41421356237309492 9.58578643762690419)))'],
[QgsPoint(1, 11), 0, 200, 2, 0,
'CurvePolygon (CompoundCurve (CircularString (-0.96961550602441604 10.65270364466613984, 0.99999999999999956 13, 2.96961550602441626 10.65270364466613984),(2.96961550602441626 10.65270364466613984, 1 11),(1 11, -0.96961550602441604 10.65270364466613984)))'],
[QgsPoint(1, 11), 0, 45, 2, 1,
'CurvePolygon (CompoundCurve (CircularString (0.23463313526982044 12.84775906502257392, 1 13, 1.76536686473017967 12.84775906502257392),(1.76536686473017967 12.84775906502257392, 1.38268343236508984 11.92387953251128607),CircularString (1.38268343236508984 11.92387953251128607, 0.99999999999999978 12, 0.61731656763491016 11.92387953251128607),(0.61731656763491016 11.92387953251128607, 0.23463313526982044 12.84775906502257392)))'],
[QgsPoint(1, 11), 0, 200, 2, 1,
'CurvePolygon (CompoundCurve (CircularString (-0.96961550602441604 10.65270364466613984, 0.99999999999999956 13, 2.96961550602441626 10.65270364466613984),(2.96961550602441626 10.65270364466613984, 1.98480775301220813 10.82635182233306992),CircularString (1.98480775301220813 10.82635182233306992, 0.99999999999999978 12, 0.01519224698779198 10.82635182233306992),(0.01519224698779198 10.82635182233306992, -0.96961550602441604 10.65270364466613984)))'],
[QgsPoint(1, 11, 3), 0, 45, 2, 0,
'CurvePolygonZ (CompoundCurveZ (CircularStringZ (0.23463313526982044 12.84775906502257392 3, 1 13 3, 1.76536686473017967 12.84775906502257392 3),(1.76536686473017967 12.84775906502257392 3, 1 11 3),(1 11 3, 0.23463313526982044 12.84775906502257392 3)))'],
[QgsPoint(1, 11, m=3), 0, 45, 2, 0,
'CurvePolygonM (CompoundCurveM (CircularStringM (0.23463313526982044 12.84775906502257392 3, 1 13 3, 1.76536686473017967 12.84775906502257392 3),(1.76536686473017967 12.84775906502257392 3, 1 11 3),(1 11 3, 0.23463313526982044 12.84775906502257392 3)))'],
[QgsPoint(1, 11), 0, 360, 2, 0,
'CurvePolygon (CompoundCurve (CircularString (1 13, 3 11, 1 9, -1 11, 1 13)))'],
[QgsPoint(1, 11), 0, -1000, 2, 0,
'CurvePolygon (CompoundCurve (CircularString (1 13, 3 11, 1 9, -1 11, 1 13)))'],
[QgsPoint(1, 11), 0, 360, 2, 1,
'CurvePolygon (CompoundCurve (CircularString (1 13, 3 11, 1 9, -1 11, 1 13)),CompoundCurve (CircularString (1 12, 2 11, 1 10, 0 11, 1 12)))']
]
for t in tests:
input = t[0]
azimuth = t[1]
width = t[2]
outer = t[3]
inner = t[4]
o = QgsGeometry.createWedgeBuffer(input, azimuth, width, outer, inner)
exp = t[5]
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.01),
"wedge buffer: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testTaperedBuffer(self):
tests = [['LineString (6 2, 9 2, 9 3, 11 5)', 1, 2, 3,
'MultiPolygon (((5.5 2, 5.56698729810778037 2.24999999999999956, 5.75 2.43301270189221919, 6 2.5, 8.23175255221825708 2.66341629715358597, 8.20710678118654791 3, 8.31333433001913669 3.39644660940672605, 10.13397459621556074 5.49999999999999911, 10.5 5.86602540378443837, 11 6, 11.5 5.86602540378443837, 11.86602540378443926 5.5, 12 5, 11.86602540378443926 4.5, 11.5 4.13397459621556163, 9.76603613070954424 2.63321666219915951, 9.71966991411008863 1.99999999999999978, 9.62325242795870217 1.64016504294495569, 9.35983495705504431 1.37674757204129761, 9 1.28033008588991049, 6 1.5, 5.75 1.56698729810778059, 5.56698729810778037 1.75, 5.5 2)))'
if self.geos39 else
'MultiPolygon (((6 1.5, 5.75 1.56698729810778059, 5.56698729810778037 1.75, 5.5 2, 5.56698729810778037 2.24999999999999956, 5.75 2.43301270189221919, 6 2.5, 8.23175255221825708 2.66341629715358597, 8.20710678118654791 3, 8.31333433001913669 3.39644660940672605, 10.13397459621556074 5.49999999999999911, 10.5 5.86602540378443837, 11 6, 11.5 5.86602540378443837, 11.86602540378443926 5.5, 12 5, 11.86602540378443926 4.5, 11.5 4.13397459621556163, 9.76603613070954424 2.63321666219915951, 9.71966991411008863 1.99999999999999978, 9.62325242795870217 1.64016504294495569, 9.35983495705504431 1.37674757204129761, 9 1.28033008588991049, 6 1.5)))'],
['LineString (6 2, 9 2, 9 3, 11 5)', 1, 1, 3,
'MultiPolygon (((5.5 2, 5.56698729810778037 2.24999999999999956, 5.75 2.43301270189221919, 6 2.5, 8.5 2.5, 8.5 3, 8.56698729810778126 3.24999999999999956, 8.75 3.43301270189221919, 10.75 5.43301270189221963, 11 5.5, 11.25 5.43301270189221874, 11.43301270189221874 5.25, 11.5 5, 11.43301270189221874 4.75, 11.25 4.56698729810778037, 9.5 2.81698729810778081, 9.5 2, 9.43301270189221874 1.75000000000000022, 9.25 1.56698729810778081, 9 1.5, 6 1.5, 5.75 1.56698729810778059, 5.56698729810778037 1.75, 5.5 2)))'
if self.geos39 else
'MultiPolygon (((6 1.5, 5.75 1.56698729810778059, 5.56698729810778037 1.75, 5.5 2, 5.56698729810778037 2.24999999999999956, 5.75 2.43301270189221919, 6 2.5, 8.5 2.5, 8.5 3, 8.56698729810778126 3.24999999999999956, 8.75 3.43301270189221919, 10.75 5.43301270189221963, 11 5.5, 11.25 5.43301270189221874, 11.43301270189221874 5.25, 11.5 5, 11.43301270189221874 4.75, 11.25 4.56698729810778037, 9.5 2.81698729810778081, 9.5 2, 9.43301270189221874 1.75000000000000022, 9.25 1.56698729810778081, 9 1.5, 6 1.5)))'],
['LineString (6 2, 9 2, 9 3, 11 5)', 2, 1, 3,
'MultiPolygon (((5 2, 5.13397459621556074 2.49999999999999956, 5.5 2.86602540378443837, 6 3, 8.28066508549441238 2.83300216551852069, 8.29289321881345209 3, 8.38762756430420531 3.35355339059327351, 8.64644660940672694 3.61237243569579425, 10.75 5.43301270189221963, 11 5.5, 11.25 5.43301270189221874, 11.43301270189221874 5.25, 11.5 5, 11.43301270189221874 4.75, 9.72358625835961909 2.77494218213953703, 9.78033008588991137 1.99999999999999978, 9.67578567771795583 1.60983495705504498, 9.39016504294495569 1.32421432228204461, 9 1.21966991411008951, 6 1, 5.5 1.13397459621556118, 5.13397459621556163 1.49999999999999978, 5 2)))'
if self.geos39 else
'MultiPolygon (((6 1, 5.5 1.13397459621556118, 5.13397459621556163 1.49999999999999978, 5 2, 5.13397459621556074 2.49999999999999956, 5.5 2.86602540378443837, 6 3, 8.28066508549441238 2.83300216551852069, 8.29289321881345209 3, 8.38762756430420531 3.35355339059327351, 8.64644660940672694 3.61237243569579425, 10.75 5.43301270189221963, 11 5.5, 11.25 5.43301270189221874, 11.43301270189221874 5.25, 11.5 5, 11.43301270189221874 4.75, 9.72358625835961909 2.77494218213953703, 9.78033008588991137 1.99999999999999978, 9.67578567771795583 1.60983495705504498, 9.39016504294495569 1.32421432228204461, 9 1.21966991411008951, 6 1)))'
],
[
'MultiLineString ((2 0, 2 2, 3 2, 3 3),(2.94433781190019195 4.04721689059500989, 5.45950095969289784 4.11976967370441471),(3 3, 5.5804222648752404 2.94683301343570214))',
1, 2, 3,
'MultiPolygon (((2 -0.5, 1.75 -0.43301270189221935, 1.56698729810778081 -0.25000000000000011, 1.5 0.00000000000000006, 1.25 2, 1.35048094716167078 2.37499999999999956, 1.62499999999999978 2.649519052838329, 2 2.75, 2.03076923076923066 2.75384615384615383, 2 3, 2.13397459621556118 3.49999999999999956, 2.5 3.86602540378443837, 3.00000000000000044 4, 3.50000000000000044 3.86602540378443837, 3.86602540378443837 3.5, 4 3, 3.875 1.99999999999999978, 3.75777222831138413 1.56250000000000044, 3.4375 1.24222777168861631, 3 1.125, 2.64615384615384608 1.1692307692307693, 2.5 -0.00000000000000012, 2.43301270189221963 -0.24999999999999983, 2.25 -0.4330127018922193, 2 -0.5)),((2.69433781190019195 3.6142041887027907, 2.51132511000797276 3.79721689059500989, 2.44433781190019195 4.04721689059500989, 2.51132511000797232 4.29721689059500989, 2.69433781190019195 4.48022959248722952, 2.94433781190019195 4.54721689059500989, 5.45950095969289784 5.11976967370441471, 5.95950095969289784 4.98579507748885309, 6.32552636347733621 4.61976967370441471, 6.45950095969289784 4.11976967370441471, 6.3255263634773371 3.61976967370441516, 5.95950095969289784 3.25374426991997634, 5.45950095969289784 3.11976967370441471, 2.94433781190019195 3.54721689059500989, 2.69433781190019195 3.6142041887027907)),((5.5804222648752404 3.94683301343570214, 6.0804222648752404 3.81285841722014052, 6.44644766865967878 3.44683301343570214, 6.5804222648752404 2.94683301343570214, 6.44644766865967966 2.44683301343570259, 6.0804222648752404 2.08080760965126377, 5.5804222648752404 1.94683301343570214, 3 2.5, 2.75 2.56698729810778081, 2.56698729810778081 2.75, 2.5 3, 2.56698729810778037 3.24999999999999956, 2.75 3.43301270189221919, 3 3.5, 5.5804222648752404 3.94683301343570214)))'
if self.geos39 else
'MultiPolygon (((2.5 -0.00000000000000012, 2.43301270189221963 -0.24999999999999983, 2.25 -0.4330127018922193, 2 -0.5, 1.75 -0.43301270189221935, 1.56698729810778081 -0.25000000000000011, 1.5 0.00000000000000006, 1.25 2, 1.35048094716167078 2.37499999999999956, 1.62499999999999978 2.649519052838329, 2 2.75, 2.03076923076923066 2.75384615384615383, 2 3, 2.13397459621556118 3.49999999999999956, 2.5 3.86602540378443837, 3.00000000000000044 4, 3.50000000000000044 3.86602540378443837, 3.86602540378443837 3.5, 4 3, 3.875 1.99999999999999978, 3.75777222831138413 1.56250000000000044, 3.4375 1.24222777168861631, 3 1.125, 2.64615384615384608 1.1692307692307693, 2.5 -0.00000000000000012)),((2.94433781190019195 3.54721689059500989, 2.69433781190019195 3.6142041887027907, 2.51132511000797276 3.79721689059500989, 2.44433781190019195 4.04721689059500989, 2.51132511000797232 4.29721689059500989, 2.69433781190019195 4.48022959248722952, 2.94433781190019195 4.54721689059500989, 5.45950095969289784 5.11976967370441471, 5.95950095969289784 4.98579507748885309, 6.32552636347733621 4.61976967370441471, 6.45950095969289784 4.11976967370441471, 6.3255263634773371 3.61976967370441516, 5.95950095969289784 3.25374426991997634, 5.45950095969289784 3.11976967370441471, 2.94433781190019195 3.54721689059500989)),((5.5804222648752404 3.94683301343570214, 6.0804222648752404 3.81285841722014052, 6.44644766865967878 3.44683301343570214, 6.5804222648752404 2.94683301343570214, 6.44644766865967966 2.44683301343570259, 6.0804222648752404 2.08080760965126377, 5.5804222648752404 1.94683301343570214, 3 2.5, 2.75 2.56698729810778081, 2.56698729810778081 2.75, 2.5 3, 2.56698729810778037 3.24999999999999956, 2.75 3.43301270189221919, 3 3.5, 5.5804222648752404 3.94683301343570214)))'],
['LineString (6 2, 9 2, 9 3, 11 5)', 2, 7, 3,
'MultiPolygon (((5.13397459621556163 1.49999999999999978, 5 2, 5.13397459621556074 2.49999999999999956, 5.5 2.86602540378443837, 6.61565808125483201 3.29902749321661304, 6.86570975577233966 4.23223304703362935, 7.96891108675446347 6.74999999999999822, 9.25 8.03108891324553475, 11 8.5, 12.75000000000000178 8.03108891324553475, 14.03108891324553475 6.75, 14.5 4.99999999999999911, 14.03108891324553653 3.25000000000000133, 12.75 1.9689110867544648, 10.86920158655618174 1.1448080812814232, 10.81722403411685463 0.95082521472477743, 10.04917478527522334 0.18277596588314599, 9 -0.09834957055044669, 7.95082521472477666 0.18277596588314587, 5.5 1.13397459621556118, 5.13397459621556163 1.49999999999999978)))'
if self.geos39 else
'MultiPolygon (((10.86920158655618174 1.1448080812814232, 10.81722403411685463 0.95082521472477743, 10.04917478527522334 0.18277596588314599, 9 -0.09834957055044669, 7.95082521472477666 0.18277596588314587, 5.5 1.13397459621556118, 5.13397459621556163 1.49999999999999978, 5 2, 5.13397459621556074 2.49999999999999956, 5.5 2.86602540378443837, 6.61565808125483201 3.29902749321661304, 6.86570975577233966 4.23223304703362935, 7.96891108675446347 6.74999999999999822, 9.25 8.03108891324553475, 11 8.5, 12.75000000000000178 8.03108891324553475, 14.03108891324553475 6.75, 14.5 4.99999999999999911, 14.03108891324553653 3.25000000000000133, 12.75 1.9689110867544648, 10.86920158655618174 1.1448080812814232)))'],
]
for t in tests:
input = QgsGeometry.fromWkt(t[0])
start = t[1]
end = t[2]
segments = t[3]
o = QgsGeometry.taperedBuffer(input, start, end, segments)
exp = t[4]
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.01),
"tapered buffer: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testVariableWidthBufferByM(self):
tests = [['LineString (6 2, 9 2, 9 3, 11 5)', 3, 'GeometryCollection EMPTY'],
['LineStringM (6 2 1, 9 2 1.5, 9 3 0.5, 11 5 2)', 3,
'MultiPolygon (((5.5 2, 5.56698729810778037 2.24999999999999956, 5.75 2.43301270189221919, 6 2.5, 8.54510095773215994 2.71209174647768014, 8.78349364905388974 3.125, 10.13397459621556074 5.49999999999999911, 10.5 5.86602540378443837, 11 6, 11.5 5.86602540378443837, 11.86602540378443926 5.5, 12 5, 11.86602540378443926 4.5, 11.5 4.13397459621556163, 9.34232758349701164 2.90707123255090094, 9.649519052838329 2.375, 9.75 1.99999999999999978, 9.649519052838329 1.62500000000000022, 9.375 1.350480947161671, 9 1.25, 6 1.5, 5.75 1.56698729810778059, 5.56698729810778037 1.75, 5.5 2)))'
if self.geos39 else
'MultiPolygon (((6 1.5, 5.75 1.56698729810778059, 5.56698729810778037 1.75, 5.5 2, 5.56698729810778037 2.24999999999999956, 5.75 2.43301270189221919, 6 2.5, 8.54510095773215994 2.71209174647768014, 8.78349364905388974 3.125, 10.13397459621556074 5.49999999999999911, 10.5 5.86602540378443837, 11 6, 11.5 5.86602540378443837, 11.86602540378443926 5.5, 12 5, 11.86602540378443926 4.5, 11.5 4.13397459621556163, 9.34232758349701164 2.90707123255090094, 9.649519052838329 2.375, 9.75 1.99999999999999978, 9.649519052838329 1.62500000000000022, 9.375 1.350480947161671, 9 1.25, 6 1.5)))'],
['MultiLineStringM ((6 2 1, 9 2 1.5, 9 3 0.5, 11 5 2),(1 2 0.5, 3 2 0.2))', 3,
'MultiPolygon (((5.5 2, 5.56698729810778037 2.24999999999999956, 5.75 2.43301270189221919, 6 2.5, 8.54510095773215994 2.71209174647768014, 8.78349364905388974 3.125, 10.13397459621556074 5.49999999999999911, 10.5 5.86602540378443837, 11 6, 11.5 5.86602540378443837, 11.86602540378443926 5.5, 12 5, 11.86602540378443926 4.5, 11.5 4.13397459621556163, 9.34232758349701164 2.90707123255090094, 9.649519052838329 2.375, 9.75 1.99999999999999978, 9.649519052838329 1.62500000000000022, 9.375 1.350480947161671, 9 1.25, 6 1.5, 5.75 1.56698729810778059, 5.56698729810778037 1.75, 5.5 2)),((0.875 1.78349364905389041, 0.78349364905389041 1.875, 0.75 2, 0.7834936490538903 2.125, 0.875 2.21650635094610982, 1 2.25, 3 2.10000000000000009, 3.04999999999999982 2.08660254037844384, 3.08660254037844384 2.04999999999999982, 3.10000000000000009 2, 3.08660254037844384 1.94999999999999996, 3.04999999999999982 1.91339745962155616, 3 1.89999999999999991, 1 1.75, 0.875 1.78349364905389041)))'
if self.geos39 else
'MultiPolygon (((6 1.5, 5.75 1.56698729810778059, 5.56698729810778037 1.75, 5.5 2, 5.56698729810778037 2.24999999999999956, 5.75 2.43301270189221919, 6 2.5, 8.54510095773215994 2.71209174647768014, 8.78349364905388974 3.125, 10.13397459621556074 5.49999999999999911, 10.5 5.86602540378443837, 11 6, 11.5 5.86602540378443837, 11.86602540378443926 5.5, 12 5, 11.86602540378443926 4.5, 11.5 4.13397459621556163, 9.34232758349701164 2.90707123255090094, 9.649519052838329 2.375, 9.75 1.99999999999999978, 9.649519052838329 1.62500000000000022, 9.375 1.350480947161671, 9 1.25, 6 1.5)),((1 1.75, 0.875 1.78349364905389041, 0.78349364905389041 1.875, 0.75 2, 0.7834936490538903 2.125, 0.875 2.21650635094610982, 1 2.25, 3 2.10000000000000009, 3.04999999999999982 2.08660254037844384, 3.08660254037844384 2.04999999999999982, 3.10000000000000009 2, 3.08660254037844384 1.94999999999999996, 3.04999999999999982 1.91339745962155616, 3 1.89999999999999991, 1 1.75)))']
]
for t in tests:
input = QgsGeometry.fromWkt(t[0])
segments = t[1]
o = QgsGeometry.variableWidthBufferByM(input, segments)
exp = t[2]
result = o.asWkt()
self.assertTrue(compareWkt(result, exp, 0.01),
"tapered buffer: mismatch Expected:\n{}\nGot:\n{}\n".format(exp, result))
def testHausdorff(self):
tests = [["POLYGON((0 0, 0 2, 1 2, 2 2, 2 0, 0 0))",
"POLYGON((0.5 0.5, 0.5 2.5, 1.5 2.5, 2.5 2.5, 2.5 0.5, 0.5 0.5))", 0.707106781186548],
["LINESTRING (0 0, 2 1)", "LINESTRING (0 0, 2 0)", 1],
["LINESTRING (0 0, 2 0)", "LINESTRING (0 1, 1 2, 2 1)", 2],
["LINESTRING (0 0, 2 0)", "MULTIPOINT (0 1, 1 0, 2 1)", 1],
["LINESTRING (130 0, 0 0, 0 150)", "LINESTRING (10 10, 10 150, 130 10)", 14.142135623730951]
]
for t in tests:
g1 = QgsGeometry.fromWkt(t[0])
g2 = QgsGeometry.fromWkt(t[1])
o = g1.hausdorffDistance(g2)
exp = t[2]
self.assertAlmostEqual(o, exp, 5,
"mismatch for {} to {}, expected:\n{}\nGot:\n{}\n".format(t[0], t[1], exp, o))
def testHausdorffDensify(self):
tests = [
["LINESTRING (130 0, 0 0, 0 150)", "LINESTRING (10 10, 10 150, 130 10)", 0.5, 70.0]
]
for t in tests:
g1 = QgsGeometry.fromWkt(t[0])
g2 = QgsGeometry.fromWkt(t[1])
densify = t[2]
o = g1.hausdorffDistanceDensify(g2, densify)
exp = t[3]
self.assertAlmostEqual(o, exp, 5,
"mismatch for {} to {}, expected:\n{}\nGot:\n{}\n".format(t[0], t[1], exp, o))
def testConvertToCurves(self):
tests = [
["LINESTRING Z (3 3 3,2.4142135623731 1.58578643762691 3,1 1 3,-0.414213562373092 1.5857864376269 3,-1 2.99999999999999 3,-0.414213562373101 4.41421356237309 3,0.999999999999991 5 3,2.41421356237309 4.4142135623731 3,3 3 3)",
"CompoundCurveZ (CircularStringZ (3 3 3, -1 2.99999999999998979 3, 3 3 3))", 0.00000001, 0.0000001],
["LINESTRING(0 0,10 0,10 10,0 10,0 0)", "CompoundCurve((0 0,10 0,10 10,0 10,0 0))", 0.00000001, 0.00000001],
["LINESTRING(0 0,10 0,10 10,0 10)", "CompoundCurve((0 0,10 0,10 10,0 10))", 0.00000001, 0.00000001],
["LINESTRING(10 10,0 10,0 0,10 0)", "CompoundCurve((10 10,0 10,0 0,10 0))", 0.0000001, 0.00000001],
["LINESTRING(0 0, 1 1)", "CompoundCurve((0 0, 1 1))", 0.00000001, 0.00000001],
["GEOMETRYCOLLECTION(LINESTRING(10 10,10 11),LINESTRING(10 11,11 11),LINESTRING(11 11,10 10))",
"MultiCurve (CompoundCurve ((10 10, 10 11)),CompoundCurve ((10 11, 11 11)),CompoundCurve ((11 11, 10 10)))", 0.000001, 0.000001],
["GEOMETRYCOLLECTION(LINESTRING(4 4,4 8),CIRCULARSTRING(4 8,6 10,8 8),LINESTRING(8 8,8 4))",
"MultiCurve (CompoundCurve ((4 4, 4 8)),CompoundCurve (CircularString (4 8, 6 10, 8 8)),CompoundCurve ((8 8, 8 4)))", 0.0000001, 0.0000001],
["LINESTRING(-13151357.927248 3913656.64539871,-13151419.0845266 3913664.12016378,-13151441.323537 3913666.61175286,-13151456.8908442 3913666.61175286,-13151476.9059536 3913666.61175286,-13151496.921063 3913666.61175287,-13151521.3839744 3913666.61175287,-13151591.4368571 3913665.36595828)",
"CompoundCurve ((-13151357.92724799923598766 3913656.64539870992302895, -13151419.08452660031616688 3913664.12016378017142415, -13151441.32353699952363968 3913666.61175285978242755, -13151456.8908441998064518 3913666.61175285978242755, -13151476.90595359914004803 3913666.61175285978242755, -13151496.92106300033628941 3913666.61175287002697587, -13151521.38397439941763878 3913666.61175287002697587, -13151591.43685710057616234 3913665.36595827993005514))", 0.000001, 0.0000001],
["Point( 1 2 )", "Point( 1 2 )", 0.00001, 0.00001],
["MultiPoint( 1 2, 3 4 )", "MultiPoint( (1 2 ), (3 4 ))", 0.00001, 0.00001],
# A polygon converts to curve
["POLYGON((3 3,2.4142135623731 1.58578643762691,1 1,-0.414213562373092 1.5857864376269,-1 2.99999999999999,-0.414213562373101 4.41421356237309,0.999999999999991 5,2.41421356237309 4.4142135623731,3 3))", "CURVEPOLYGON(COMPOUNDCURVE(CircularString(3 3, -1 2.99999999999998979, 3 3)))", 0.00000001, 0.00000001],
# The same polygon, even if already CURVEPOLYGON, still converts to curve
["CURVEPOLYGON((3 3,2.4142135623731 1.58578643762691,1 1,-0.414213562373092 1.5857864376269,-1 2.99999999999999,-0.414213562373101 4.41421356237309,0.999999999999991 5,2.41421356237309 4.4142135623731,3 3))", "CURVEPOLYGON(COMPOUNDCURVE(CircularString(3 3, -1 2.99999999999998979, 3 3)))", 0.00000001, 0.00000001],
]
for t in tests:
g1 = QgsGeometry.fromWkt(t[0])
distance_tolerance = t[2]
angle_tolerance = t[3]
o = g1.convertToCurves(distance_tolerance, angle_tolerance)
self.assertTrue(compareWkt(o.asWkt(), t[1], 0.00001),
"clipped: mismatch Expected:\n{}\nGot:\n{}\n".format(t[1], o.asWkt()))
def testBoundingBoxIntersects(self):
tests = [
["LINESTRING (0 0, 100 100)", "LINESTRING (90 0, 100 0)", True],
["LINESTRING (0 0, 100 100)", "LINESTRING (101 0, 102 0)", False],
["POINT(20 1)", "LINESTRING( 0 0, 100 100 )", True],
["POINT(20 1)", "POINT(21 1)", False],
["POINT(20 1)", "POINT(20 1)", True]
]
for t in tests:
g1 = QgsGeometry.fromWkt(t[0])
g2 = QgsGeometry.fromWkt(t[1])
res = g1.boundingBoxIntersects(g2)
self.assertEqual(res, t[2],
"mismatch for {} to {}, expected:\n{}\nGot:\n{}\n".format(g1.asWkt(), g2.asWkt(), t[2],
res))
def testBoundingBoxIntersectsRectangle(self):
tests = [
["LINESTRING (0 0, 100 100)", QgsRectangle(90, 0, 100, 10), True],
["LINESTRING (0 0, 100 100)", QgsRectangle(101, 0, 102, 10), False],
["POINT(20 1)", QgsRectangle(0, 0, 100, 100), True],
["POINT(20 1)", QgsRectangle(21, 1, 21, 1), False],
["POINT(20 1)", QgsRectangle(20, 1, 20, 1), True]
]
for t in tests:
g1 = QgsGeometry.fromWkt(t[0])
res = g1.boundingBoxIntersects(t[1])
self.assertEqual(res, t[2],
"mismatch for {} to {}, expected:\n{}\nGot:\n{}\n".format(g1.asWkt(), t[1].toString(),
t[2], res))
def testOffsetCurve(self):
tests = [
["LINESTRING (0 0, 0 100, 100 100)", 1, "LineString (-1 0, -1 101, 100 101)"],
["LINESTRING (0 0, 0 100, 100 100)", -1, "LineString (1 0, 1 99, 100 99)"],
["LINESTRING (100 100, 0 100, 0 0)", 1, "LineString (100 99, 1 99, 1 0)"],
["LINESTRING (100 100, 0 100, 0 0)", -1, "LineString (100 101, -1 101, -1 0)"],
# linestring which becomes multilinestring -- the actual offset curve calculated by GEOS looks bad, but we shouldn't crash here
[
"LINESTRING (259329.820 5928370.79, 259324.337 5928371.758, 259319.678 5928372.33, 259317.064 5928372.498 )",
100,
"MultiLineString ((259313.3 5928272.5, 259312.5 5928272.6),(259312.4 5928272.3, 259309.5 5928272.8, 259307.5 5928273.1))"],
["MULTILINESTRING ((0 0, 0 100, 100 100),(100 100, 0 100, 0 0))", 1,
"MultiLineString ((-1 0, -1 101, 100 101),(100 99, 1 99, 1 0))"]
]
for t in tests:
g1 = QgsGeometry.fromWkt(t[0])
res = g1.offsetCurve(t[1], 2, QgsGeometry.JoinStyleMiter, 5)
self.assertEqual(res.asWkt(1), t[2],
"mismatch for {} to {}, expected:\n{}\nGot:\n{}\n".format(t[0], t[1],
t[2], res.asWkt(1)))
def testForceRHR(self):
tests = [
["", ""],
["Point (100 100)", "Point (100 100)"],
["LINESTRING (0 0, 0 100, 100 100)", "LineString (0 0, 0 100, 100 100)"],
["LINESTRING (100 100, 0 100, 0 0)", "LineString (100 100, 0 100, 0 0)"],
["POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1))", "Polygon ((-1 -1, 0 2, 4 2, 4 0, -1 -1))"],
[
"MULTIPOLYGON(Polygon((-1 -1, 4 0, 4 2, 0 2, -1 -1)),Polygon((100 100, 200 100, 200 200, 100 200, 100 100)))",
"MultiPolygon (((-1 -1, 0 2, 4 2, 4 0, -1 -1)),((100 100, 100 200, 200 200, 200 100, 100 100)))"],
[
"GeometryCollection(Polygon((-1 -1, 4 0, 4 2, 0 2, -1 -1)),Polygon((100 100, 200 100, 200 200, 100 200, 100 100)))",
"GeometryCollection (Polygon ((-1 -1, 0 2, 4 2, 4 0, -1 -1)),Polygon ((100 100, 100 200, 200 200, 200 100, 100 100)))"]
]
for t in tests:
g1 = QgsGeometry.fromWkt(t[0])
res = g1.forceRHR()
self.assertEqual(res.asWkt(1), t[1],
"mismatch for {}, expected:\n{}\nGot:\n{}\n".format(t[0], t[1], res.asWkt(1)))
def testLineStringFromBezier(self):
tests = [
[QgsPoint(1, 1), QgsPoint(10, 1), QgsPoint(10, 10), QgsPoint(20, 10), 5,
'LineString (1 1, 5.5 1.9, 8.7 4.2, 11.6 6.8, 15 9.1, 20 10)'],
[QgsPoint(1, 1), QgsPoint(10, 1), QgsPoint(10, 10), QgsPoint(1, 1), 10,
'LineString (1 1, 3.4 1.2, 5.3 1.9, 6.7 2.7, 7.5 3.6, 7.8 4.4, 7.5 4.9, 6.7 5, 5.3 4.5, 3.4 3.2, 1 1)'],
[QgsPoint(1, 1), QgsPoint(10, 1), QgsPoint(10, 10), QgsPoint(20, 10), 10,
'LineString (1 1, 3.4 1.3, 5.5 1.9, 7.2 2.9, 8.7 4.2, 10.1 5.5, 11.6 6.8, 13.2 8.1, 15 9.1, 17.3 9.7, 20 10)'],
[QgsPoint(1, 1), QgsPoint(10, 1), QgsPoint(10, 10), QgsPoint(20, 10), 1,
'LineString (1 1, 20 10)'],
[QgsPoint(1, 1), QgsPoint(10, 1), QgsPoint(10, 10), QgsPoint(20, 10), 0,
'LineString EMPTY'],
[QgsPoint(1, 1, 2), QgsPoint(10, 1), QgsPoint(10, 10), QgsPoint(20, 10), 5,
'LineString (1 1, 5.5 1.9, 8.7 4.2, 11.6 6.8, 15 9.1, 20 10)'],
[QgsPoint(1, 1), QgsPoint(10, 1, 2), QgsPoint(10, 10), QgsPoint(20, 10), 5,
'LineString (1 1, 5.5 1.9, 8.7 4.2, 11.6 6.8, 15 9.1, 20 10)'],
[QgsPoint(1, 1, 2), QgsPoint(10, 1), QgsPoint(10, 10, 2), QgsPoint(20, 10), 5,
'LineString (1 1, 5.5 1.9, 8.7 4.2, 11.6 6.8, 15 9.1, 20 10)'],
[QgsPoint(1, 1, 2), QgsPoint(10, 1), QgsPoint(10, 10), QgsPoint(20, 10, 2), 5,
'LineString (1 1, 5.5 1.9, 8.7 4.2, 11.6 6.8, 15 9.1, 20 10)'],
[QgsPoint(1, 1, 1), QgsPoint(10, 1, 2), QgsPoint(10, 10, 3), QgsPoint(20, 10, 4), 5,
'LineStringZ (1 1 1, 5.5 1.9 1.6, 8.7 4.2 2.2, 11.6 6.8 2.8, 15 9.1 3.4, 20 10 4)'],
[QgsPoint(1, 1, 1, 10), QgsPoint(10, 1, 2, 9), QgsPoint(10, 10, 3, 2), QgsPoint(20, 10, 4, 1), 5,
'LineStringZM (1 1 1 10, 5.5 1.9 1.6 8.8, 8.7 4.2 2.2 6.7, 11.6 6.8 2.8 4.3, 15 9.1 3.4 2.2, 20 10 4 1)']
]
for t in tests:
res = QgsLineString.fromBezierCurve(t[0], t[1], t[2], t[3], t[4])
self.assertEqual(res.asWkt(1), t[5],
"mismatch for {}, expected:\n{}\nGot:\n{}\n".format(t[0], t[5], res.asWkt(1)))
def testIsGeosValid(self):
tests = [
["", False, False, ''],
["Point (100 100)", True, True, ''],
["MultiPoint (100 100, 100 200)", True, True, ''],
["LINESTRING (0 0, 0 100, 100 100)", True, True, ''],
["POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1))", True, True, ''],
[
"MULTIPOLYGON(Polygon((-1 -1, 4 0, 4 2, 0 2, -1 -1)),Polygon((100 100, 200 100, 200 200, 100 200, 100 100)))",
True, True, ''],
[
'MultiPolygon (((159865.14786298031685874 6768656.31838363595306873, 159858.97975336571107619 6769211.44824895076453686, 160486.07089751763851382 6769211.44824895076453686, 160481.95882444124436006 6768658.37442017439752817, 160163.27316101978067309 6768658.37442017439752817, 160222.89822062765597366 6769116.87056819349527359, 160132.43261294672265649 6769120.98264127038419247, 160163.27316101978067309 6768658.37442017439752817, 159865.14786298031685874 6768656.31838363595306873)))',
False, True, 'Ring self-intersection'],
['Polygon((0 3, 3 0, 3 3, 0 0, 0 3))', False, False, 'Self-intersection'],
]
for t in tests:
# run each check 2 times to allow for testing of cached value
g1 = QgsGeometry.fromWkt(t[0])
for i in range(2):
res = g1.isGeosValid()
self.assertEqual(res, t[1],
"mismatch for {}, expected:\n{}\nGot:\n{}\n".format(t[0], t[1], res))
if not res:
self.assertEqual(g1.lastError(), t[3], t[0])
for i in range(2):
res = g1.isGeosValid(QgsGeometry.FlagAllowSelfTouchingHoles)
self.assertEqual(res, t[2],
"mismatch for {}, expected:\n{}\nGot:\n{}\n".format(t[0], t[2], res))
def testValidateGeometry(self):
tests = [
["", [], [], []],
["Point (100 100)", [], [], []],
["MultiPoint (100 100, 100 200)", [], [], []],
["LINESTRING (0 0, 0 100, 100 100)", [], [], []],
["POLYGON((-1 -1, 4 0, 4 2, 0 2, -1 -1))", [], [], []],
[
"MULTIPOLYGON(Polygon((-1 -1, 4 0, 4 2, 0 2, -1 -1)),Polygon((100 100, 200 100, 200 200, 100 200, 100 100)))",
[], [], []],
['POLYGON ((200 400, 400 400, 400 200, 300 200, 350 250, 250 250, 300 200, 200 200, 200 400))',
[QgsGeometry.Error('Ring self-intersection', QgsPointXY(300, 200))], [], []],
[
'MultiPolygon (((159865.14786298031685874 6768656.31838363595306873, 159858.97975336571107619 6769211.44824895076453686, 160486.07089751763851382 6769211.44824895076453686, 160481.95882444124436006 6768658.37442017439752817, 160163.27316101978067309 6768658.37442017439752817, 160222.89822062765597366 6769116.87056819349527359, 160132.43261294672265649 6769120.98264127038419247, 160163.27316101978067309 6768658.37442017439752817, 159865.14786298031685874 6768656.31838363595306873)))',
[QgsGeometry.Error('Ring self-intersection',
QgsPointXY(160163.27316101978067309, 6768658.37442017439752817))], [], []],
['Polygon((0 3, 3 0, 3 3, 0 0, 0 3))', [QgsGeometry.Error('Self-intersection', QgsPointXY(1.5, 1.5))],
[QgsGeometry.Error('Self-intersection', QgsPointXY(1.5, 1.5))],
[QgsGeometry.Error('segments 0 and 2 of line 0 intersect at 1.5, 1.5', QgsPointXY(1.5, 1.5))]],
]
for t in tests:
g1 = QgsGeometry.fromWkt(t[0])
res = g1.validateGeometry(QgsGeometry.ValidatorGeos)
self.assertEqual(res, t[1],
"mismatch for {}, expected:\n{}\nGot:\n{}\n".format(t[0], t[1],
res[0].where() if res else ''))
res = g1.validateGeometry(QgsGeometry.ValidatorGeos, QgsGeometry.FlagAllowSelfTouchingHoles)
self.assertEqual(res, t[2],
"mismatch for {}, expected:\n{}\nGot:\n{}\n".format(t[0], t[2],
res[0].where() if res else ''))
res = g1.validateGeometry(QgsGeometry.ValidatorQgisInternal)
self.assertEqual(res, t[3],
"mismatch for {}, expected:\n{}\nGot:\n{}\n".format(t[0], t[3],
res[0].where() if res else ''))
def testCollectDuplicateNodes(self):
g = QgsGeometry.fromWkt("LineString (1 1, 1 1, 1 1, 1 2, 1 3, 1 3, 1 3, 1 4, 1 5, 1 6, 1 6)")
res = g.constGet().collectDuplicateNodes()
self.assertCountEqual(res, [QgsVertexId(-1, -1, 1), QgsVertexId(-1, -1, 2), QgsVertexId(-1, -1, 5), QgsVertexId(-1, -1, 6), QgsVertexId(-1, -1, 10)])
g = QgsGeometry.fromWkt("LineString (1 1, 1 2, 1 3, 1 4, 1 5, 1 6)")
res = g.constGet().collectDuplicateNodes()
self.assertFalse(res)
g = QgsGeometry.fromWkt("LineStringZ (1 1 1, 1 1 2, 1 1 3, 1 2 1, 1 3 1, 1 3 1, 1 3 2, 1 4 1, 1 5 1, 1 6 1, 1 6 2)")
res = g.constGet().collectDuplicateNodes()
self.assertCountEqual(res, [QgsVertexId(-1, -1, 1), QgsVertexId(-1, -1, 2), QgsVertexId(-1, -1, 5), QgsVertexId(-1, -1, 6), QgsVertexId(-1, -1, 10)])
# consider z values
res = g.constGet().collectDuplicateNodes(useZValues=True)
self.assertEqual(res, [QgsVertexId(-1, -1, 5)])
# tolerance
g = QgsGeometry.fromWkt("LineString (1 1, 1 1.1, 1 2, 1 3, 1 3, 1 4, 1 5)")
res = g.constGet().collectDuplicateNodes()
self.assertCountEqual(res, [QgsVertexId(-1, -1, 4)])
res = g.constGet().collectDuplicateNodes(epsilon=0.5)
self.assertCountEqual(res, [QgsVertexId(-1, -1, 1), QgsVertexId(-1, -1, 4)])
def testRandomPoints(self):
"""
Test QgsGeometry.randomPointsInPolygon.
This just test the Python operation of this function -- more tests in testqgsgeometry.cpp
"""
# no random points inside null geometry
g = QgsGeometry()
with self.assertRaises(ValueError):
res = g.randomPointsInPolygon(100)
# no random points inside linestring
g = QgsGeometry.fromWkt('LineString(4 5, 6 6)')
with self.assertRaises(TypeError):
res = g.randomPointsInPolygon(100)
# good!
g = QgsGeometry.fromWkt('Polygon(( 5 15, 10 15, 10 20, 5 20, 5 15 ), (6 16, 8 16, 8 18, 6 16 ))')
res = g.randomPointsInPolygon(100)
self.assertEqual(len(res), 100)
g = QgsGeometry.fromWkt(
'MultiPolygon((( 5 15, 10 15, 10 20, 5 20, 5 15 ), (6 16, 8 16, 8 18, 6 16 )), (( 105 115, 110 115, 110 120, 105 120, 105 115 ), (106 116, 108 116, 108 118, 106 116 )))')
res = g.randomPointsInPolygon(100)
self.assertEqual(len(res), 100)
res2 = g.randomPointsInPolygon(100)
self.assertNotEqual(res, res2)
# with seed
res = g.randomPointsInPolygon(100, seed=123123)
res2 = g.randomPointsInPolygon(100, seed=123123)
self.assertEqual(res, res2)
def testLineStringFromQPolygonF(self):
line = QgsLineString.fromQPolygonF(QPolygonF())
self.assertEqual(line.asWkt(0), 'LineString EMPTY')
line = QgsLineString.fromQPolygonF(QPolygonF([QPointF(1, 2), QPointF(3, 4)]))
self.assertEqual(line.asWkt(1), 'LineString (1 2, 3 4)')
line = QgsLineString.fromQPolygonF(
QPolygonF([QPointF(1.5, 2.5), QPointF(3, 4), QPointF(3, 6.5), QPointF(1.5, 2.5)]))
self.assertEqual(line.asWkt(1), 'LineString (1.5 2.5, 3 4, 3 6.5, 1.5 2.5)')
def testCoerce(self):
"""Test coerce function"""
def coerce_to_wkt(wkt, type):
geom = QgsGeometry.fromWkt(wkt)
return [g.asWkt(2) for g in geom.coerceToType(type)]
self.assertEqual(coerce_to_wkt('Point (1 1)', QgsWkbTypes.Point), ['Point (1 1)'])
self.assertEqual(coerce_to_wkt('LineString (1 1, 2 2, 3 3)', QgsWkbTypes.LineString),
['LineString (1 1, 2 2, 3 3)'])
self.assertEqual(coerce_to_wkt('Polygon((1 1, 2 2, 1 2, 1 1))', QgsWkbTypes.Polygon),
['Polygon ((1 1, 2 2, 1 2, 1 1))'])
self.assertEqual(coerce_to_wkt('LineString (1 1, 2 2, 3 3)', QgsWkbTypes.Point),
['Point (1 1)', 'Point (2 2)', 'Point (3 3)'])
self.assertEqual(coerce_to_wkt('LineString (1 1, 2 2, 3 3)', QgsWkbTypes.Polygon),
['Polygon ((1 1, 2 2, 3 3, 1 1))'])
self.assertEqual(coerce_to_wkt('Polygon((1 1, 2 2, 1 2, 1 1))', QgsWkbTypes.Point),
['Point (1 1)', 'Point (2 2)', 'Point (1 2)'])
self.assertEqual(coerce_to_wkt('Polygon((1 1, 2 2, 1 2, 1 1))', QgsWkbTypes.LineString),
['LineString (1 1, 2 2, 1 2, 1 1)'])
self.assertEqual(coerce_to_wkt('Point z (1 1 3)', QgsWkbTypes.Point), ['Point (1 1)'])
self.assertEqual(coerce_to_wkt('Point z (1 1 3)', QgsWkbTypes.PointZ), ['PointZ (1 1 3)'])
# Adding Z back
self.assertEqual(coerce_to_wkt('Point (1 1)', QgsWkbTypes.PointZ), ['PointZ (1 1 0)'])
# Adding M back
self.assertEqual(coerce_to_wkt('Point (1 1)', QgsWkbTypes.PointM), ['PointM (1 1 0)'])
self.assertEqual(coerce_to_wkt('Point m (1 1 3)', QgsWkbTypes.Point), ['Point (1 1)'])
self.assertEqual(coerce_to_wkt('Point(1 3)', QgsWkbTypes.MultiPoint), ['MultiPoint ((1 3))'])
self.assertEqual(coerce_to_wkt('MultiPoint((1 3), (2 2))', QgsWkbTypes.MultiPoint),
['MultiPoint ((1 3),(2 2))'])
self.assertEqual(coerce_to_wkt('Polygon((1 1, 2 2, 3 3, 1 1))', QgsWkbTypes.Polygon),
['Polygon ((1 1, 2 2, 3 3, 1 1))'])
self.assertEqual(coerce_to_wkt('Polygon z ((1 1 1, 2 2 2, 3 3 3, 1 1 1))', QgsWkbTypes.Polygon),
['Polygon ((1 1, 2 2, 3 3, 1 1))'])
self.assertEqual(coerce_to_wkt('Polygon z ((1 1 1, 2 2 2, 3 3 3, 1 1 1))', QgsWkbTypes.PolygonZ),
['PolygonZ ((1 1 1, 2 2 2, 3 3 3, 1 1 1))'])
# Adding Z back
self.assertEqual(coerce_to_wkt('Polygon ((1 1, 2 2, 3 3, 1 1))', QgsWkbTypes.PolygonZ),
['PolygonZ ((1 1 0, 2 2 0, 3 3 0, 1 1 0))'])
# Adding M back
self.assertEqual(coerce_to_wkt('Polygon ((1 1, 2 2, 3 3, 1 1))', QgsWkbTypes.PolygonM),
['PolygonM ((1 1 0, 2 2 0, 3 3 0, 1 1 0))'])
self.assertEqual(coerce_to_wkt('Polygon m ((1 1 1, 2 2 2, 3 3 3, 1 1 1))', QgsWkbTypes.Polygon),
['Polygon ((1 1, 2 2, 3 3, 1 1))'])
self.assertEqual(coerce_to_wkt('Polygon m ((1 1 1, 2 2 2, 3 3 3, 1 1 1))', QgsWkbTypes.PolygonM),
['PolygonM ((1 1 1, 2 2 2, 3 3 3, 1 1 1))'])
self.assertEqual(coerce_to_wkt('Polygon((1 1, 2 2, 3 3, 1 1))', QgsWkbTypes.MultiPolygon),
['MultiPolygon (((1 1, 2 2, 3 3, 1 1)))'])
self.assertEqual(
coerce_to_wkt('MultiPolygon(((1 1, 2 2, 3 3, 1 1)), ((1 1, 2 2, 3 3, 1 1)))', QgsWkbTypes.MultiPolygon),
['MultiPolygon (((1 1, 2 2, 3 3, 1 1)),((1 1, 2 2, 3 3, 1 1)))'])
self.assertEqual(coerce_to_wkt('LineString(1 1, 2 2, 3 3, 1 1)', QgsWkbTypes.LineString),
['LineString (1 1, 2 2, 3 3, 1 1)'])
self.assertEqual(coerce_to_wkt('LineString z (1 1 1, 2 2 2, 3 3 3, 1 1 1)', QgsWkbTypes.LineString),
['LineString (1 1, 2 2, 3 3, 1 1)'])
self.assertEqual(coerce_to_wkt('LineString z (1 1 1, 2 2 2, 3 3 3, 1 1 1)', QgsWkbTypes.LineStringZ),
['LineStringZ (1 1 1, 2 2 2, 3 3 3, 1 1 1)'])
self.assertEqual(coerce_to_wkt('LineString m (1 1 1, 2 2 2, 3 3 3, 1 1 1)', QgsWkbTypes.LineString),
['LineString (1 1, 2 2, 3 3, 1 1)'])
self.assertEqual(coerce_to_wkt('LineString m (1 1 1, 2 2 2, 3 3 3, 1 1 1)', QgsWkbTypes.LineStringM),
['LineStringM (1 1 1, 2 2 2, 3 3 3, 1 1 1)'])
# Adding Z back
self.assertEqual(coerce_to_wkt('LineString (1 1, 2 2, 3 3, 1 1)', QgsWkbTypes.LineStringZ),
['LineStringZ (1 1 0, 2 2 0, 3 3 0, 1 1 0)'])
# Adding M back
self.assertEqual(coerce_to_wkt('LineString (1 1, 2 2, 3 3, 1 1)', QgsWkbTypes.LineStringM),
['LineStringM (1 1 0, 2 2 0, 3 3 0, 1 1 0)'])
self.assertEqual(coerce_to_wkt('LineString(1 1, 2 2, 3 3, 1 1)', QgsWkbTypes.MultiLineString),
['MultiLineString ((1 1, 2 2, 3 3, 1 1))'])
self.assertEqual(coerce_to_wkt('MultiLineString((1 1, 2 2, 3 3, 1 1), (1 1, 2 2, 3 3, 1 1))',
QgsWkbTypes.MultiLineString),
['MultiLineString ((1 1, 2 2, 3 3, 1 1),(1 1, 2 2, 3 3, 1 1))'])
# Test Multi -> Single
self.assertEqual(coerce_to_wkt('MultiLineString((1 1, 2 2, 3 3, 1 1), (10 1, 20 2, 30 3, 10 1))',
QgsWkbTypes.LineString),
['LineString (1 1, 2 2, 3 3, 1 1)', 'LineString (10 1, 20 2, 30 3, 10 1)'])
# line -> points
self.assertEqual(coerce_to_wkt('LineString (1 1, 2 2, 3 3)', QgsWkbTypes.Point),
['Point (1 1)', 'Point (2 2)', 'Point (3 3)'])
self.assertEqual(coerce_to_wkt('LineString (1 1, 2 2, 3 3)', QgsWkbTypes.MultiPoint),
['MultiPoint ((1 1),(2 2),(3 3))'])
self.assertEqual(coerce_to_wkt('MultiLineString ((1 1, 2 2),(4 4, 3 3))', QgsWkbTypes.Point),
['Point (1 1)', 'Point (2 2)', 'Point (4 4)', 'Point (3 3)'])
self.assertEqual(coerce_to_wkt('MultiLineString ((1 1, 2 2),(4 4, 3 3))', QgsWkbTypes.MultiPoint),
['MultiPoint ((1 1),(2 2),(4 4),(3 3))'])
# line -> polygon
self.assertEqual(coerce_to_wkt('LineString (1 1, 1 2, 2 2)', QgsWkbTypes.Polygon),
['Polygon ((1 1, 1 2, 2 2, 1 1))'])
self.assertEqual(coerce_to_wkt('LineString (1 1, 1 2, 2 2)', QgsWkbTypes.MultiPolygon),
['MultiPolygon (((1 1, 1 2, 2 2, 1 1)))'])
self.assertEqual(coerce_to_wkt('MultiLineString ((1 1, 1 2, 2 2, 1 1),(3 3, 4 3, 4 4))', QgsWkbTypes.Polygon),
['Polygon ((1 1, 1 2, 2 2, 1 1))', 'Polygon ((3 3, 4 3, 4 4, 3 3))'])
self.assertEqual(coerce_to_wkt('MultiLineString ((1 1, 1 2, 2 2, 1 1),(3 3, 4 3, 4 4))',
QgsWkbTypes.MultiPolygon),
['MultiPolygon (((1 1, 1 2, 2 2, 1 1)),((3 3, 4 3, 4 4, 3 3)))'])
self.assertEqual(coerce_to_wkt('CircularString (1 1, 1 2, 2 2, 2 0, 1 1)', QgsWkbTypes.CurvePolygon),
['CurvePolygon (CircularString (1 1, 1 2, 2 2, 2 0, 1 1))'])
self.assertEqual(coerce_to_wkt('CircularString (1 1, 1 2, 2 2, 2 0, 1 1)', QgsWkbTypes.LineString)[0][:100],
'LineString (1 1, 0.99 1.01, 0.98 1.02, 0.97 1.03, 0.97 1.04, 0.96 1.05, 0.95 1.06, 0.94 1.06, 0.94 1')
self.assertEqual(coerce_to_wkt('CircularString (1 1, 1 2, 2 2, 2 0, 1 1)', QgsWkbTypes.Polygon)[0][:100],
'Polygon ((1 1, 0.99 1.01, 0.98 1.02, 0.97 1.03, 0.97 1.04, 0.96 1.05, 0.95 1.06, 0.94 1.06, 0.94 1.0')
# polygon -> points
self.assertEqual(coerce_to_wkt('Polygon ((1 1, 1 2, 2 2, 1 1))', QgsWkbTypes.Point),
['Point (1 1)', 'Point (1 2)', 'Point (2 2)'])
self.assertEqual(coerce_to_wkt('Polygon ((1 1, 1 2, 2 2, 1 1))', QgsWkbTypes.MultiPoint),
['MultiPoint ((1 1),(1 2),(2 2))'])
self.assertEqual(
coerce_to_wkt('MultiPolygon (((1 1, 1 2, 2 2, 1 1)),((3 3, 4 3, 4 4, 3 3)))', QgsWkbTypes.Point),
['Point (1 1)', 'Point (1 2)', 'Point (2 2)', 'Point (3 3)', 'Point (4 3)', 'Point (4 4)'])
self.assertEqual(coerce_to_wkt('MultiPolygon (((1 1, 1 2, 2 2, 1 1)),((3 3, 4 3, 4 4, 3 3)))',
QgsWkbTypes.MultiPoint), ['MultiPoint ((1 1),(1 2),(2 2),(3 3),(4 3),(4 4))'])
# polygon -> lines
self.assertEqual(coerce_to_wkt('Polygon ((1 1, 1 2, 2 2, 1 1))', QgsWkbTypes.LineString),
['LineString (1 1, 1 2, 2 2, 1 1)'])
self.assertEqual(coerce_to_wkt('Polygon ((1 1, 1 2, 2 2, 1 1))', QgsWkbTypes.MultiLineString),
['MultiLineString ((1 1, 1 2, 2 2, 1 1))'])
self.assertEqual(coerce_to_wkt('MultiPolygon (((1 1, 1 2, 2 2, 1 1)),((3 3, 4 3, 4 4, 3 3)))',
QgsWkbTypes.LineString),
['LineString (1 1, 1 2, 2 2, 1 1)', 'LineString (3 3, 4 3, 4 4, 3 3)'])
self.assertEqual(coerce_to_wkt('MultiPolygon (((1 1, 1 2, 2 2, 1 1)),((3 3, 4 3, 4 4, 3 3)))',
QgsWkbTypes.MultiLineString),
['MultiLineString ((1 1, 1 2, 2 2, 1 1),(3 3, 4 3, 4 4, 3 3))'])
def testGeosCrash(self):
# test we don't crash when geos returns a point geometry with no points
QgsGeometry.fromWkt('Polygon ((0 0, 1 1, 1 0, 0 0))').intersection(QgsGeometry.fromWkt('Point (42 0)')).isNull()
def testIsRectangle(self):
"""
Test checking if geometries are rectangles
"""
# non polygons
self.assertFalse(QgsGeometry().isAxisParallelRectangle(0))
self.assertFalse(QgsGeometry.fromWkt('Point(0 1)').isAxisParallelRectangle(0))
self.assertFalse(QgsGeometry.fromWkt('LineString(0 1, 1 2)').isAxisParallelRectangle(0))
self.assertFalse(QgsGeometry.fromWkt('Polygon((0 0, 0 1, 1 1, 0 0))').isAxisParallelRectangle(0))
self.assertFalse(QgsGeometry.fromWkt('Polygon((0 0, 0 1, 1 1, 0 0))').isAxisParallelRectangle(0, True))
self.assertFalse(QgsGeometry.fromWkt('Polygon((0 0, 0 1, 1 1, 0 1))').isAxisParallelRectangle(0))
self.assertFalse(QgsGeometry.fromWkt('Polygon((0 0, 0 1, 1 1, 0 1))').isAxisParallelRectangle(0, True))
self.assertFalse(QgsGeometry.fromWkt('Polygon(())').isAxisParallelRectangle(0))
self.assertTrue(QgsGeometry.fromWkt('Polygon((0 0, 1 0, 1 1, 0 1, 0 0))').isAxisParallelRectangle(0))
self.assertTrue(QgsGeometry.fromWkt('Polygon((0 0, 1 0, 1 1, 0 1, 0 0))').isAxisParallelRectangle(0, True))
self.assertTrue(QgsGeometry.fromWkt('Polygon((0 0, 0 1, 1 1, 1 0, 0 0))').isAxisParallelRectangle(0))
self.assertTrue(QgsGeometry.fromWkt('Polygon((0 0, 0 1, 1 1, 1 0, 0 0))').isAxisParallelRectangle(0, True))
# with rings
self.assertFalse(QgsGeometry.fromWkt('Polygon((0 0, 1 0, 1 1, 0 1, 0 0), (0.1 0.1, 0.2 0.1, 0.2 0.2, 0.1 0.2, 0.1 0.1))').isAxisParallelRectangle(0))
# densified
self.assertTrue(QgsGeometry.fromWkt('Polygon((0 0, 0.5 0.0, 1 0, 1 1, 0 1, 0 0))').densifyByCount(5).isAxisParallelRectangle(0))
# not a simple rectangle
self.assertFalse(QgsGeometry.fromWkt('Polygon((0 0, 0.5 0.0, 1 0, 1 1, 0 1, 0 0))').densifyByCount(5).isAxisParallelRectangle(0, True))
# starting mid way through a side
self.assertTrue(QgsGeometry.fromWkt('Polygon((0.5 0, 1 0, 1 1, 0 1, 0 0, 0.5 0))').densifyByCount(
5).isAxisParallelRectangle(0))
self.assertFalse(QgsGeometry.fromWkt('Polygon((0.5 0, 1 0, 1 1, 0 1, 0 0, 0.5 0))').densifyByCount(
5).isAxisParallelRectangle(0, True))
# with tolerance
self.assertFalse(QgsGeometry.fromWkt('Polygon((0 0, 1 0.001, 1 1, 0 1, 0 0))').isAxisParallelRectangle(0))
self.assertTrue(QgsGeometry.fromWkt('Polygon((0 0, 1 0.001, 1 1, 0 1, 0 0))').isAxisParallelRectangle(1))
self.assertFalse(QgsGeometry.fromWkt('Polygon((0 0, 1 0.1, 1 1, 0 1, 0 0))').isAxisParallelRectangle(1))
self.assertTrue(QgsGeometry.fromWkt('Polygon((0 0, 1 0.1, 1 1, 0 1, 0 0))').isAxisParallelRectangle(10))
self.assertTrue(QgsGeometry.fromWkt('Polygon((0 0, 1 0.1, 1 1, 0 1, 0 0))').densifyByCount(5).isAxisParallelRectangle(10))
def testTransformWithClass(self):
"""
Test transforming using a python based class (most of the tests for this are in c++, this is just
checking the sip bindings!)
"""
class Transformer(QgsAbstractGeometryTransformer):
def transformPoint(self, x, y, z, m):
return True, x * 2, y + 1, z, m
transformer = Transformer()
g = QgsGeometry.fromWkt('LineString(0 0, 10 0, 10 10)')
self.assertTrue(g.get().transform(transformer))
self.assertEqual(g.asWkt(0), 'LineString (0 1, 20 1, 20 11)')
@unittest.skipIf(Qgis.geosVersionInt() < 30900, "GEOS 3.9 required")
def testFrechetDistance(self):
"""
Test QgsGeometry.frechetDistance
"""
l1 = QgsGeometry.fromWkt('LINESTRING (0 0, 100 0)')
l2 = QgsGeometry.fromWkt('LINESTRING (0 0, 50 50, 100 0)')
self.assertAlmostEqual(l1.frechetDistance(l2), 70.711, 3)
self.assertAlmostEqual(l2.frechetDistance(l1), 70.711, 3)
@unittest.skipIf(Qgis.geosVersionInt() < 30900, "GEOS 3.9 required")
def testFrechetDistanceDensify(self):
"""
Test QgsGeometry.frechetDistanceDensify
"""
l1 = QgsGeometry.fromWkt('LINESTRING (0 0, 100 0)')
l2 = QgsGeometry.fromWkt('LINESTRING (0 0, 50 50, 100 0)')
self.assertAlmostEqual(l1.frechetDistanceDensify(l2, 0.5), 50.000, 3)
self.assertAlmostEqual(l2.frechetDistanceDensify(l1, 0.5), 50.000, 3)
@unittest.skipIf(Qgis.geosVersionInt() < 30900, "GEOS 3.9 required")
def testLargestEmptyCircle(self):
"""
Test QgsGeometry.largestEmptyCircle
"""
g1 = QgsGeometry.fromWkt('POLYGON ((50 50, 150 50, 150 150, 50 150, 50 50))')
self.assertEqual(g1.largestEmptyCircle(1).asWkt(), 'LineString (100 100, 100 50)')
self.assertEqual(g1.largestEmptyCircle(0.1).asWkt(), 'LineString (100 100, 100 50)')
g2 = QgsGeometry.fromWkt('MultiPolygon (((95.03667481662591854 163.45354523227382515, 95.03667481662591854 122.0354523227383936, 34.10757946210270575 122.0354523227383936, 34.10757946210270575 163.45354523227382515, 95.03667481662591854 163.45354523227382515)),((35.64792176039119198 76.3386308068459698, 94.52322738386308743 76.3386308068459698, 94.52322738386308743 41.25305623471882654, 35.64792176039119198 41.25305623471882654, 35.64792176039119198 76.3386308068459698)),((185.23227383863081741 108.34352078239608375, 185.23227383863081741 78.56356968215158076, 118.99755501222495013 78.56356968215158076, 118.99755501222495013 108.34352078239608375, 185.23227383863081741 108.34352078239608375)))')
self.assertEqual(g2.largestEmptyCircle(0.1).asWkt(1), 'LineString (129.3 142.5, 129.3 108.3)')
@unittest.skipIf(Qgis.geosVersionInt() < 30600, "GEOS 3.6 required")
def testMinimumClearance(self):
"""
Test QgsGeometry.minimumClearance
"""
l1 = QgsGeometry.fromWkt('POLYGON ((0 0, 1 0, 1 1, 0.5 3.2e-4, 0 0))')
self.assertAlmostEqual(l1.minimumClearance(), 0.00032, 5)
@unittest.skipIf(Qgis.geosVersionInt() < 30600, "GEOS 3.6 required")
def testMinimumClearanceLine(self):
"""
Test QgsGeometry.minimumClearanceLine
"""
l1 = QgsGeometry.fromWkt('POLYGON ((0 0, 1 0, 1 1, 0.5 3.2e-4, 0 0))')
self.assertEqual(l1.minimumClearanceLine().asWkt(6), 'LineString (0.5 0.00032, 0.5 0)')
@unittest.skipIf(Qgis.geosVersionInt() < 30600, "GEOS 3.6 required")
def testMinimumWidth(self):
"""
Test QgsGeometry.minimumWidth
"""
l1 = QgsGeometry.fromWkt('POLYGON ((0 0, 1 0, 1 1, 0.5 3.2e-4, 0 0))')
self.assertEqual(l1.minimumWidth().asWkt(6), 'LineString (0.5 0.5, 1 0)')
def testNode(self):
"""
Test QgsGeometry.node
"""
l1 = QgsGeometry.fromWkt('LINESTRINGZ(0 0 0, 10 10 10, 0 10 5, 10 0 3)')
self.assertEqual(l1.node().asWkt(6), 'MultiLineStringZ ((0 0 0, 5 5 4.5),(5 5 4.5, 10 10 10, 0 10 5, 5 5 4.5),(5 5 4.5, 10 0 3))')
l1 = QgsGeometry.fromWkt('MULTILINESTRING ((2 5, 2 1, 7 1), (6 1, 4 1, 2 3, 2 5))')
self.assertEqual(l1.node().asWkt(6), 'MultiLineString ((2 5, 2 3),(2 3, 2 1, 4 1),(4 1, 6 1),(6 1, 7 1),(4 1, 2 3))')
def testSharedPaths(self):
"""
Test QgsGeometry.sharedPaths
"""
l1 = QgsGeometry.fromWkt('MULTILINESTRING((26 125,26 200,126 200,126 125,26 125),(51 150,101 150,76 175,51 150))')
l2 = QgsGeometry.fromWkt('LINESTRING(151 100,126 156.25,126 125,90 161, 76 175)')
self.assertEqual(l1.sharedPaths(l2).asWkt(6), 'GeometryCollection (MultiLineString ((126 156.25, 126 125),(101 150, 90 161),(90 161, 76 175)),MultiLineString EMPTY)')
l1 = QgsGeometry.fromWkt('LINESTRING(76 175,90 161,126 125,126 156.25,151 100)')
l2 = QgsGeometry.fromWkt('MULTILINESTRING((26 125,26 200,126 200,126 125,26 125),(51 150,101 150,76 175,51 150))')
self.assertEqual(l1.sharedPaths(l2).asWkt(6), 'GeometryCollection (MultiLineString EMPTY,MultiLineString ((76 175, 90 161),(90 161, 101 150),(126 125, 126 156.25)))')
def renderGeometry(self, geom, use_pen, as_polygon=False, as_painter_path=False):
image = QImage(200, 200, QImage.Format_RGB32)
image.fill(QColor(0, 0, 0))
painter = QPainter(image)
if use_pen:
painter.setPen(QPen(QColor(255, 255, 255), 4))
else:
painter.setBrush(QBrush(QColor(255, 255, 255)))
if as_painter_path:
path = QPainterPath()
geom.constGet().addToPainterPath(path)
painter.drawPath(path)
else:
if as_polygon:
geom.constGet().drawAsPolygon(painter)
else:
geom.draw(painter)
painter.end()
return image
def testGeometryDraw(self):
'''Tests drawing geometries'''
tests = [{'name': 'Point',
'wkt': 'Point (40 60)',
'reference_image': 'point',
'use_pen': False},
{'name': 'LineString',
'wkt': 'LineString (20 30, 50 30, 50 90)',
'reference_image': 'linestring',
'as_polygon_reference_image': 'linestring_aspolygon',
'use_pen': True},
{'name': 'CircularString',
'wkt': 'CircularString (20 30, 50 30, 50 90)',
'reference_image': 'circularstring',
'as_polygon_reference_image': 'circularstring_aspolygon',
'use_pen': True},
{'name': 'CurvePolygon',
'wkt': 'CurvePolygon(CircularString (20 30, 50 30, 50 90, 10 50, 20 30))',
'reference_image': 'curvepolygon_circularstring',
'use_pen': False},
{'name': 'CurvePolygonInteriorRings',
'wkt': 'CurvePolygon(CircularString (20 30, 50 30, 50 90, 10 50, 20 30),LineString(30 45, 55 45, 30 75, 30 45))',
'reference_image': 'curvepolygon_circularstring_interiorrings',
'use_pen': False},
{'name': 'CompoundCurve',
'wkt': 'CompoundCurve(CircularString (20 30, 50 30, 50 90),LineString(50 90, 10 90))',
'reference_image': 'compoundcurve',
'use_pen': True,
'as_polygon_reference_image': 'compoundcurve_aspolygon'},
{'name': 'GeometryCollection',
'wkt': 'GeometryCollection(LineString (20 30, 50 30, 50 70),LineString(10 90, 90 90))',
'reference_image': 'geometrycollection',
'use_pen': True}
]
for test in tests:
geom = QgsGeometry.fromWkt(test['wkt'])
self.assertTrue(geom and not geom.isNull(), 'Could not create geometry {}'.format(test['wkt']))
rendered_image = self.renderGeometry(geom, test['use_pen'])
assert self.imageCheck(test['name'], test['reference_image'], rendered_image)
if hasattr(geom.constGet(), 'addToPainterPath'):
# also check using painter path
rendered_image = self.renderGeometry(geom, test['use_pen'], as_painter_path=True)
assert self.imageCheck(test['name'], test['reference_image'], rendered_image)
if 'as_polygon_reference_image' in test:
rendered_image = self.renderGeometry(geom, False, True)
assert self.imageCheck(test['name'] + '_aspolygon', test['as_polygon_reference_image'], rendered_image)
def testGeometryAsQPainterPath(self):
'''Tests conversion of different geometries to QPainterPath, including bad/odd geometries.'''
empty_multipolygon = QgsMultiPolygon()
empty_multipolygon.addGeometry(QgsPolygon())
empty_polygon = QgsPolygon()
empty_linestring = QgsLineString()
tests = [{'name': 'LineString',
'wkt': 'LineString (0 0,3 4,4 3)',
'reference_image': 'linestring'},
{'name': 'Empty LineString',
'geom': QgsGeometry(empty_linestring),
'reference_image': 'empty'},
{'name': 'MultiLineString',
'wkt': 'MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 0), (3 1, 5 1, 5 0, 6 0))',
'reference_image': 'multilinestring'},
{'name': 'Polygon',
'wkt': 'Polygon ((0 0, 10 0, 10 10, 0 10, 0 0),(5 5, 7 5, 7 7 , 5 7, 5 5))',
'reference_image': 'polygon'},
{'name': 'Empty Polygon',
'geom': QgsGeometry(empty_polygon),
'reference_image': 'empty'},
{'name': 'MultiPolygon',
'wkt': 'MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))',
'reference_image': 'multipolygon'},
{'name': 'Empty MultiPolygon',
'geom': QgsGeometry(empty_multipolygon),
'reference_image': 'empty'},
{'name': 'CircularString',
'wkt': 'CIRCULARSTRING(268 415,227 505,227 406)',
'reference_image': 'circular_string'},
{'name': 'CompoundCurve',
'wkt': 'COMPOUNDCURVE((5 3, 5 13), CIRCULARSTRING(5 13, 7 15, 9 13), (9 13, 9 3), CIRCULARSTRING(9 3, 7 1, 5 3))',
'reference_image': 'compound_curve'},
{'name': 'CurvePolygon',
'wkt': 'CURVEPOLYGON(CIRCULARSTRING(1 3, 3 5, 4 7, 7 3, 1 3))',
'reference_image': 'curve_polygon'},
{'name': 'MultiCurve',
'wkt': 'MultiCurve((5 5,3 5,3 3,0 3),CIRCULARSTRING(0 0, 2 1,2 2))',
'reference_image': 'multicurve'},
{'name': 'CurvePolygon_no_arc', # refs #14028
'wkt': 'CURVEPOLYGON(LINESTRING(1 3, 3 5, 4 7, 7 3, 1 3))',
'reference_image': 'curve_polygon_no_arc'},
{'name': 'CurvePolygonInteriorRings',
'wkt': 'CurvePolygon(CircularString (20 30, 50 30, 50 90, 10 50, 20 30),LineString(30 45, 55 45, 30 75, 30 45))',
'reference_image': 'curvepolygon_circularstring_interiorrings'},
{'name': 'CompoundCurve With Line',
'wkt': 'CompoundCurve(CircularString (20 30, 50 30, 50 90),LineString(50 90, 10 90))',
'reference_image': 'compoundcurve_with_line'},
{'name': 'Collection LineString',
'wkt': 'GeometryCollection( LineString (0 0,3 4,4 3) )',
'reference_image': 'collection_linestring'},
{'name': 'Collection MultiLineString',
'wkt': 'GeometryCollection (LineString(0 0, 1 0, 1 1, 2 1, 2 0), LineString(3 1, 5 1, 5 0, 6 0))',
'reference_image': 'collection_multilinestring'},
{'name': 'Collection Polygon',
'wkt': 'GeometryCollection(Polygon ((0 0, 10 0, 10 10, 0 10, 0 0),(5 5, 7 5, 7 7 , 5 7, 5 5)))',
'reference_image': 'collection_polygon'},
{'name': 'Collection MultiPolygon',
'wkt': 'GeometryCollection( Polygon((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),Polygon((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))',
'reference_image': 'collection_multipolygon'},
{'name': 'Collection CircularString',
'wkt': 'GeometryCollection(CIRCULARSTRING(268 415,227 505,227 406))',
'reference_image': 'collection_circular_string'},
{'name': 'Collection CompoundCurve',
'wkt': 'GeometryCollection(COMPOUNDCURVE((5 3, 5 13), CIRCULARSTRING(5 13, 7 15, 9 13), (9 13, 9 3), CIRCULARSTRING(9 3, 7 1, 5 3)))',
'reference_image': 'collection_compound_curve'},
{'name': 'Collection CurvePolygon',
'wkt': 'GeometryCollection(CURVEPOLYGON(CIRCULARSTRING(1 3, 3 5, 4 7, 7 3, 1 3)))',
'reference_image': 'collection_curve_polygon'},
{'name': 'Collection CurvePolygon_no_arc', # refs #14028
'wkt': 'GeometryCollection(CURVEPOLYGON(LINESTRING(1 3, 3 5, 4 7, 7 3, 1 3)))',
'reference_image': 'collection_curve_polygon_no_arc'},
{'name': 'Collection Mixed',
'wkt': 'GeometryCollection(Point(1 2), MultiPoint(3 3, 2 3), LineString (0 0,3 4,4 3), MultiLineString((3 1, 3 2, 4 2)), Polygon((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)), MultiPolygon(((4 0, 5 0, 5 1, 6 1, 6 2, 4 2, 4 0)),(( 1 4, 2 4, 1 5, 1 4))))',
'reference_image': 'collection_mixed'},
{'name': 'MultiCurvePolygon',
'wkt': 'MultiSurface (CurvePolygon (CompoundCurve (CircularString (-12942312 4593500, -11871048 5481118, -11363838 5065730, -11551856 4038191, -12133399 4130014),(-12133399 4130014, -12942312 4593500)),(-12120281 5175043, -12456964 4694067, -11752991 4256817, -11569346 4943300, -12120281 5175043)),Polygon ((-10856627 5625411, -11083997 4995770, -10887235 4357384, -9684796 4851477, -10069576 5428648, -10856627 5625411)))',
'reference_image': 'multicurvepolygon_with_rings'}
]
for test in tests:
def get_geom():
if 'geom' not in test:
geom = QgsGeometry.fromWkt(test['wkt'])
assert geom and not geom.isNull(), 'Could not create geometry {}'.format(test['wkt'])
else:
geom = test['geom']
return geom
geom = get_geom()
rendered_image = self.renderGeometryUsingPath(geom)
self.assertTrue(self.imageCheck(test['name'], test['reference_image'], rendered_image, control_path="geometry_path"), test['name'])
# Note - each test is repeated with the same geometry and reference image, but with added
# z and m dimensions. This tests that presence of the dimensions does not affect rendering
# test with Z
geom_z = get_geom()
geom_z.get().addZValue(5)
rendered_image = self.renderGeometryUsingPath(geom_z)
assert self.imageCheck(test['name'] + 'Z', test['reference_image'], rendered_image, control_path="geometry_path")
# test with ZM
geom_z.get().addMValue(15)
rendered_image = self.renderGeometryUsingPath(geom_z)
assert self.imageCheck(test['name'] + 'ZM', test['reference_image'], rendered_image, control_path="geometry_path")
# test with M
geom_m = get_geom()
geom_m.get().addMValue(15)
rendered_image = self.renderGeometryUsingPath(geom_m)
assert self.imageCheck(test['name'] + 'M', test['reference_image'], rendered_image, control_path="geometry_path")
def renderGeometryUsingPath(self, geom):
image = QImage(200, 200, QImage.Format_RGB32)
dest_bounds = image.rect()
geom = QgsGeometry(geom)
src_bounds = geom.buffer(geom.boundingBox().width() / 10, 5).boundingBox()
if src_bounds.width() and src_bounds.height():
scale = min(dest_bounds.width() / src_bounds.width(), dest_bounds.height() / src_bounds.height())
t = QTransform.fromScale(scale, -scale)
geom.transform(t)
src_bounds = geom.buffer(geom.boundingBox().width() / 10, 5).boundingBox()
t = QTransform.fromTranslate(-src_bounds.xMinimum(), -src_bounds.yMinimum())
geom.transform(t)
path = geom.constGet().asQPainterPath()
painter = QPainter()
painter.begin(image)
pen = QPen(QColor(0, 255, 255))
pen.setWidth(6)
painter.setPen(pen)
painter.setBrush(QBrush(QColor(255, 255, 0)))
try:
image.fill(QColor(0, 0, 0))
painter.drawPath(path)
finally:
painter.end()
return image
def imageCheck(self, name, reference_image, image, control_path="geometry"):
self.report += "<h2>Render {}</h2>\n".format(name)
temp_dir = QDir.tempPath() + '/'
file_name = temp_dir + 'geometry_' + name + ".png"
image.save(file_name, "PNG")
checker = QgsRenderChecker()
checker.setControlPathPrefix(control_path)
checker.setControlName("expected_" + reference_image)
checker.setRenderedImage(file_name)
checker.setColorTolerance(2)
result = checker.compareImages(name, 20)
self.report += checker.report()
print((self.report))
return result
if __name__ == '__main__':
unittest.main()
|
RevelSystems/django | refs/heads/master | tests/auth_tests/settings.py | 331 | import os
from django.utils._os import upath
AUTH_MIDDLEWARE_CLASSES = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
]
AUTH_TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(upath(__file__)), 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
}]
|
leeslove/libyuv | refs/heads/master | download_vs_toolchain.py | 187 | #!/usr/bin/env python
#
# Copyright 2014 The LibYuv Project Authors. All rights reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
# This script is used to run the vs_toolchain.py script to download the
# Visual Studio toolchain. It's just a temporary measure while waiting for the
# Chrome team to move find_depot_tools into src/build to get rid of these
# workarounds (similar one in gyp_libyuv).
import os
import sys
checkout_root = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(checkout_root, 'build'))
sys.path.insert(0, os.path.join(checkout_root, 'tools', 'find_depot_tools'))
import vs_toolchain
if __name__ == '__main__':
sys.exit(vs_toolchain.main())
|
xmbcrios/xmbcrios.repository | refs/heads/master | script.module.urlresolver/lib/urlresolver/plugins/vidag.py | 3 | '''
thevideo urlresolver plugin
Copyright (C) 2014 Eldorado
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
from t0mm0.common.net import Net
from urlresolver.plugnplay.interfaces import UrlResolver
from urlresolver.plugnplay.interfaces import PluginSettings
from urlresolver.plugnplay import Plugin
import re
from urlresolver import common
from lib import jsunpack
class VidAgResolver(Plugin, UrlResolver, PluginSettings):
implements = [UrlResolver, PluginSettings]
name = "vid.ag"
domains = ["vid.ag"]
pattern = '//((?:www\.)?vid\.ag)/(?:embed-)?([0-9A-Za-z]+)'
def __init__(self):
p = self.get_setting('priority') or 100
self.priority = int(p)
self.net = Net()
def get_media_url(self, host, media_id):
web_url = self.get_url(host, media_id)
html = self.net.http_GET(web_url).content
for match in re.finditer('(eval\(function.*?)</script>', html, re.DOTALL):
js_data = jsunpack.unpack(match.group(1))
r = re.search('file\s*:\s*"([^"]+)', js_data)
if r:
return r.group(1)
r = re.search('file\s*:\s*"([^"]+)', html)
if r:
return r.group(1)
raise UrlResolver.ResolverError('File Not Found or removed')
def get_url(self, host, media_id):
return 'http://%s/embed-%s.html' % (host, media_id)
def get_host_and_id(self, url):
r = re.search(self.pattern, url)
if r:
return r.groups()
else:
return False
def valid_url(self, url, host):
if self.get_setting('enabled') == 'false': return False
return (re.search(self.pattern, url) or 'vid.ag' in host)
|
freakboy3742/django | refs/heads/main | tests/gis_tests/geoapp/feeds.py | 133 | from django.contrib.gis import feeds
from .models import City
class TestGeoRSS1(feeds.Feed):
link = '/city/'
title = 'Test GeoDjango Cities'
def items(self):
return City.objects.all()
def item_link(self, item):
return '/city/%s/' % item.pk
def item_geometry(self, item):
return item.point
class TestGeoRSS2(TestGeoRSS1):
def geometry(self, obj):
# This should attach a <georss:box> element for the extent of
# of the cities in the database. This tuple came from
# calling `City.objects.aggregate(Extent())` -- we can't do that call
# here because `Extent` is not implemented for MySQL/Oracle.
return (-123.30, -41.32, 174.78, 48.46)
def item_geometry(self, item):
# Returning a simple tuple for the geometry.
return item.point.x, item.point.y
class TestGeoAtom1(TestGeoRSS1):
feed_type = feeds.GeoAtom1Feed
class TestGeoAtom2(TestGeoRSS2):
feed_type = feeds.GeoAtom1Feed
def geometry(self, obj):
# This time we'll use a 2-tuple of coordinates for the box.
return ((-123.30, -41.32), (174.78, 48.46))
class TestW3CGeo1(TestGeoRSS1):
feed_type = feeds.W3CGeoFeed
# The following feeds are invalid, and will raise exceptions.
class TestW3CGeo2(TestGeoRSS2):
feed_type = feeds.W3CGeoFeed
class TestW3CGeo3(TestGeoRSS1):
feed_type = feeds.W3CGeoFeed
def item_geometry(self, item):
from django.contrib.gis.geos import Polygon
return Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
# The feed dictionary to use for URLs.
feed_dict = {
'rss1': TestGeoRSS1,
'rss2': TestGeoRSS2,
'atom1': TestGeoAtom1,
'atom2': TestGeoAtom2,
'w3cgeo1': TestW3CGeo1,
'w3cgeo2': TestW3CGeo2,
'w3cgeo3': TestW3CGeo3,
}
|
FireBladeNooT/Medusa_1_6 | refs/heads/master | lib/chardet/sbcharsetprober.py | 3 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
# Shy Shalom - original C code
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .charsetprober import CharSetProber
from .compat import wrap_ord
from .enums import ProbingState
class SingleByteCharSetProber(CharSetProber):
SAMPLE_SIZE = 64
SB_ENOUGH_REL_THRESHOLD = 1024
POSITIVE_SHORTCUT_THRESHOLD = 0.95
NEGATIVE_SHORTCUT_THRESHOLD = 0.05
SYMBOL_CAT_ORDER = 250
NUMBER_OF_SEQ_CAT = 4
POSITIVE_CAT = NUMBER_OF_SEQ_CAT - 1
def __init__(self, model, reversed=False, name_prober=None):
super(SingleByteCharSetProber, self).__init__()
self._model = model
# TRUE if we need to reverse every pair in the model lookup
self._reversed = reversed
# Optional auxiliary prober for name decision
self._name_prober = name_prober
self._last_order = None
self._seq_counters = None
self._total_seqs = None
self._total_char = None
self._freq_char = None
self.reset()
def reset(self):
super(SingleByteCharSetProber, self).reset()
# char order of last character
self._last_order = 255
self._seq_counters = [0] * self.NUMBER_OF_SEQ_CAT
self._total_seqs = 0
self._total_char = 0
# characters that fall in our sampling range
self._freq_char = 0
@property
def charset_name(self):
if self._name_prober:
return self._name_prober.charset_name
else:
return self._model['charset_name']
def feed(self, byte_str):
if not self._model['keep_english_letter']:
byte_str = self.filter_international_words(byte_str)
num_bytes = len(byte_str)
if not num_bytes:
return self.state
for c in byte_str:
order = self._model['char_to_order_map'][wrap_ord(c)]
if order < self.SYMBOL_CAT_ORDER:
self._total_char += 1
if order < self.SAMPLE_SIZE:
self._freq_char += 1
if self._last_order < self.SAMPLE_SIZE:
self._total_seqs += 1
if not self._reversed:
i = (self._last_order * self.SAMPLE_SIZE) + order
model = self._model['precedence_matrix'][i]
else: # reverse the order of the letters in the lookup
i = (order * self.SAMPLE_SIZE) + self._last_order
model = self._model['precedence_matrix'][i]
self._seq_counters[model] += 1
self._last_order = order
if self.state == ProbingState.detecting:
if self._total_seqs > self.SB_ENOUGH_REL_THRESHOLD:
cf = self.get_confidence()
if cf > self.POSITIVE_SHORTCUT_THRESHOLD:
self.logger.debug('%s confidence = %s, we have a winner',
self._model['charset_name'], cf)
self._state = ProbingState.found_it
elif cf < self.NEGATIVE_SHORTCUT_THRESHOLD:
self.logger.debug('%s confidence = %s, below negative '
'shortcut threshold %s',
self._model['charset_name'], cf,
self.NEGATIVE_SHORTCUT_THRESHOLD)
self._state = ProbingState.not_me
return self.state
def get_confidence(self):
r = 0.01
if self._total_seqs > 0:
r = ((1.0 * self._seq_counters[self.POSITIVE_CAT]) / self._total_seqs
/ self._model['typical_positive_ratio'])
r = r * self._freq_char / self._total_char
if r >= 1.0:
r = 0.99
return r
|
schinzelh/dash | refs/heads/master | qa/rpc-tests/test_framework/bignum.py | 230 | #
#
# bignum.py
#
# This file is copied from python-bitcoinlib.
#
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
"""Bignum routines"""
from __future__ import absolute_import, division, print_function, unicode_literals
import struct
# generic big endian MPI format
def bn_bytes(v, have_ext=False):
ext = 0
if have_ext:
ext = 1
return ((v.bit_length()+7)//8) + ext
def bn2bin(v):
s = bytearray()
i = bn_bytes(v)
while i > 0:
s.append((v >> ((i-1) * 8)) & 0xff)
i -= 1
return s
def bin2bn(s):
l = 0
for ch in s:
l = (l << 8) | ch
return l
def bn2mpi(v):
have_ext = False
if v.bit_length() > 0:
have_ext = (v.bit_length() & 0x07) == 0
neg = False
if v < 0:
neg = True
v = -v
s = struct.pack(b">I", bn_bytes(v, have_ext))
ext = bytearray()
if have_ext:
ext.append(0)
v_bin = bn2bin(v)
if neg:
if have_ext:
ext[0] |= 0x80
else:
v_bin[0] |= 0x80
return s + ext + v_bin
def mpi2bn(s):
if len(s) < 4:
return None
s_size = bytes(s[:4])
v_len = struct.unpack(b">I", s_size)[0]
if len(s) != (v_len + 4):
return None
if v_len == 0:
return 0
v_str = bytearray(s[4:])
neg = False
i = v_str[0]
if i & 0x80:
neg = True
i &= ~0x80
v_str[0] = i
v = bin2bn(v_str)
if neg:
return -v
return v
# bitcoin-specific little endian format, with implicit size
def mpi2vch(s):
r = s[4:] # strip size
r = r[::-1] # reverse string, converting BE->LE
return r
def bn2vch(v):
return bytes(mpi2vch(bn2mpi(v)))
def vch2mpi(s):
r = struct.pack(b">I", len(s)) # size
r += s[::-1] # reverse string, converting LE->BE
return r
def vch2bn(s):
return mpi2bn(vch2mpi(s))
|
cbrewster/servo | refs/heads/master | tests/wpt/web-platform-tests/tools/third_party/pytest/testing/acceptance_test.py | 30 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import os
import sys
import types
import six
import _pytest._code
import py
import pytest
from _pytest.main import EXIT_NOTESTSCOLLECTED, EXIT_USAGEERROR
class TestGeneralUsage(object):
def test_config_error(self, testdir):
testdir.makeconftest(
"""
def pytest_configure(config):
import pytest
raise pytest.UsageError("hello")
"""
)
result = testdir.runpytest(testdir.tmpdir)
assert result.ret != 0
result.stderr.fnmatch_lines(["*ERROR: hello"])
def test_root_conftest_syntax_error(self, testdir):
testdir.makepyfile(conftest="raise SyntaxError\n")
result = testdir.runpytest()
result.stderr.fnmatch_lines(["*raise SyntaxError*"])
assert result.ret != 0
def test_early_hook_error_issue38_1(self, testdir):
testdir.makeconftest(
"""
def pytest_sessionstart():
0 / 0
"""
)
result = testdir.runpytest(testdir.tmpdir)
assert result.ret != 0
# tracestyle is native by default for hook failures
result.stdout.fnmatch_lines(
["*INTERNALERROR*File*conftest.py*line 2*", "*0 / 0*"]
)
result = testdir.runpytest(testdir.tmpdir, "--fulltrace")
assert result.ret != 0
# tracestyle is native by default for hook failures
result.stdout.fnmatch_lines(
["*INTERNALERROR*def pytest_sessionstart():*", "*INTERNALERROR*0 / 0*"]
)
def test_early_hook_configure_error_issue38(self, testdir):
testdir.makeconftest(
"""
def pytest_configure():
0 / 0
"""
)
result = testdir.runpytest(testdir.tmpdir)
assert result.ret != 0
# here we get it on stderr
result.stderr.fnmatch_lines(
["*INTERNALERROR*File*conftest.py*line 2*", "*0 / 0*"]
)
def test_file_not_found(self, testdir):
result = testdir.runpytest("asd")
assert result.ret != 0
result.stderr.fnmatch_lines(["ERROR: file not found*asd"])
def test_file_not_found_unconfigure_issue143(self, testdir):
testdir.makeconftest(
"""
def pytest_configure():
print("---configure")
def pytest_unconfigure():
print("---unconfigure")
"""
)
result = testdir.runpytest("-s", "asd")
assert result.ret == 4 # EXIT_USAGEERROR
result.stderr.fnmatch_lines(["ERROR: file not found*asd"])
result.stdout.fnmatch_lines(["*---configure", "*---unconfigure"])
def test_config_preparse_plugin_option(self, testdir):
testdir.makepyfile(
pytest_xyz="""
def pytest_addoption(parser):
parser.addoption("--xyz", dest="xyz", action="store")
"""
)
testdir.makepyfile(
test_one="""
def test_option(pytestconfig):
assert pytestconfig.option.xyz == "123"
"""
)
result = testdir.runpytest("-p", "pytest_xyz", "--xyz=123", syspathinsert=True)
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])
def test_assertion_magic(self, testdir):
p = testdir.makepyfile(
"""
def test_this():
x = 0
assert x
"""
)
result = testdir.runpytest(p)
result.stdout.fnmatch_lines(["> assert x", "E assert 0"])
assert result.ret == 1
def test_nested_import_error(self, testdir):
p = testdir.makepyfile(
"""
import import_fails
def test_this():
assert import_fails.a == 1
"""
)
testdir.makepyfile(import_fails="import does_not_work")
result = testdir.runpytest(p)
result.stdout.fnmatch_lines(
[
# XXX on jython this fails: "> import import_fails",
"ImportError while importing test module*",
"*No module named *does_not_work*",
]
)
assert result.ret == 2
def test_not_collectable_arguments(self, testdir):
p1 = testdir.makepyfile("")
p2 = testdir.makefile(".pyc", "123")
result = testdir.runpytest(p1, p2)
assert result.ret
result.stderr.fnmatch_lines(["*ERROR: not found:*%s" % (p2.basename,)])
def test_issue486_better_reporting_on_conftest_load_failure(self, testdir):
testdir.makepyfile("")
testdir.makeconftest("import qwerty")
result = testdir.runpytest("--help")
result.stdout.fnmatch_lines(
"""
*--version*
*warning*conftest.py*
"""
)
result = testdir.runpytest()
result.stderr.fnmatch_lines(
"""
*ERROR*could not load*conftest.py*
"""
)
def test_early_skip(self, testdir):
testdir.mkdir("xyz")
testdir.makeconftest(
"""
import pytest
def pytest_collect_directory():
pytest.skip("early")
"""
)
result = testdir.runpytest()
assert result.ret == EXIT_NOTESTSCOLLECTED
result.stdout.fnmatch_lines(["*1 skip*"])
def test_issue88_initial_file_multinodes(self, testdir):
testdir.makeconftest(
"""
import pytest
class MyFile(pytest.File):
def collect(self):
return [MyItem("hello", parent=self)]
def pytest_collect_file(path, parent):
return MyFile(path, parent)
class MyItem(pytest.Item):
pass
"""
)
p = testdir.makepyfile("def test_hello(): pass")
result = testdir.runpytest(p, "--collect-only")
result.stdout.fnmatch_lines(["*MyFile*test_issue88*", "*Module*test_issue88*"])
def test_issue93_initialnode_importing_capturing(self, testdir):
testdir.makeconftest(
"""
import sys
print ("should not be seen")
sys.stderr.write("stder42\\n")
"""
)
result = testdir.runpytest()
assert result.ret == EXIT_NOTESTSCOLLECTED
assert "should not be seen" not in result.stdout.str()
assert "stderr42" not in result.stderr.str()
def test_conftest_printing_shows_if_error(self, testdir):
testdir.makeconftest(
"""
print ("should be seen")
assert 0
"""
)
result = testdir.runpytest()
assert result.ret != 0
assert "should be seen" in result.stdout.str()
@pytest.mark.skipif(
not hasattr(py.path.local, "mksymlinkto"),
reason="symlink not available on this platform",
)
def test_chdir(self, testdir):
testdir.tmpdir.join("py").mksymlinkto(py._pydir)
p = testdir.tmpdir.join("main.py")
p.write(
_pytest._code.Source(
"""
import sys, os
sys.path.insert(0, '')
import py
print (py.__file__)
print (py.__path__)
os.chdir(os.path.dirname(os.getcwd()))
print (py.log)
"""
)
)
result = testdir.runpython(p)
assert not result.ret
def test_issue109_sibling_conftests_not_loaded(self, testdir):
sub1 = testdir.mkdir("sub1")
sub2 = testdir.mkdir("sub2")
sub1.join("conftest.py").write("assert 0")
result = testdir.runpytest(sub2)
assert result.ret == EXIT_NOTESTSCOLLECTED
sub2.ensure("__init__.py")
p = sub2.ensure("test_hello.py")
result = testdir.runpytest(p)
assert result.ret == EXIT_NOTESTSCOLLECTED
result = testdir.runpytest(sub1)
assert result.ret == EXIT_USAGEERROR
def test_directory_skipped(self, testdir):
testdir.makeconftest(
"""
import pytest
def pytest_ignore_collect():
pytest.skip("intentional")
"""
)
testdir.makepyfile("def test_hello(): pass")
result = testdir.runpytest()
assert result.ret == EXIT_NOTESTSCOLLECTED
result.stdout.fnmatch_lines(["*1 skipped*"])
def test_multiple_items_per_collector_byid(self, testdir):
c = testdir.makeconftest(
"""
import pytest
class MyItem(pytest.Item):
def runtest(self):
pass
class MyCollector(pytest.File):
def collect(self):
return [MyItem(name="xyz", parent=self)]
def pytest_collect_file(path, parent):
if path.basename.startswith("conftest"):
return MyCollector(path, parent)
"""
)
result = testdir.runpytest(c.basename + "::" + "xyz")
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 pass*"])
def test_skip_on_generated_funcarg_id(self, testdir):
testdir.makeconftest(
"""
import pytest
def pytest_generate_tests(metafunc):
metafunc.addcall({'x': 3}, id='hello-123')
def pytest_runtest_setup(item):
print (item.keywords)
if 'hello-123' in item.keywords:
pytest.skip("hello")
assert 0
"""
)
p = testdir.makepyfile("""def test_func(x): pass""")
res = testdir.runpytest(p)
assert res.ret == 0
res.stdout.fnmatch_lines(["*1 skipped*"])
def test_direct_addressing_selects(self, testdir):
p = testdir.makepyfile(
"""
def pytest_generate_tests(metafunc):
metafunc.addcall({'i': 1}, id="1")
metafunc.addcall({'i': 2}, id="2")
def test_func(i):
pass
"""
)
res = testdir.runpytest(p.basename + "::" + "test_func[1]")
assert res.ret == 0
res.stdout.fnmatch_lines(["*1 passed*"])
def test_direct_addressing_notfound(self, testdir):
p = testdir.makepyfile(
"""
def test_func():
pass
"""
)
res = testdir.runpytest(p.basename + "::" + "test_notfound")
assert res.ret
res.stderr.fnmatch_lines(["*ERROR*not found*"])
def test_docstring_on_hookspec(self):
from _pytest import hookspec
for name, value in vars(hookspec).items():
if name.startswith("pytest_"):
assert value.__doc__, "no docstring for %s" % name
def test_initialization_error_issue49(self, testdir):
testdir.makeconftest(
"""
def pytest_configure():
x
"""
)
result = testdir.runpytest()
assert result.ret == 3 # internal error
result.stderr.fnmatch_lines(["INTERNAL*pytest_configure*", "INTERNAL*x*"])
assert "sessionstarttime" not in result.stderr.str()
@pytest.mark.parametrize("lookfor", ["test_fun.py::test_a"])
def test_issue134_report_error_when_collecting_member(self, testdir, lookfor):
testdir.makepyfile(
test_fun="""
def test_a():
pass
def"""
)
result = testdir.runpytest(lookfor)
result.stdout.fnmatch_lines(["*SyntaxError*"])
if "::" in lookfor:
result.stderr.fnmatch_lines(["*ERROR*"])
assert result.ret == 4 # usage error only if item not found
def test_report_all_failed_collections_initargs(self, testdir):
testdir.makepyfile(test_a="def", test_b="def")
result = testdir.runpytest("test_a.py::a", "test_b.py::b")
result.stderr.fnmatch_lines(["*ERROR*test_a.py::a*", "*ERROR*test_b.py::b*"])
@pytest.mark.usefixtures("recwarn")
def test_namespace_import_doesnt_confuse_import_hook(self, testdir):
"""
Ref #383. Python 3.3's namespace package messed with our import hooks
Importing a module that didn't exist, even if the ImportError was
gracefully handled, would make our test crash.
Use recwarn here to silence this warning in Python 2.7:
ImportWarning: Not importing directory '...\not_a_package': missing __init__.py
"""
testdir.mkdir("not_a_package")
p = testdir.makepyfile(
"""
try:
from not_a_package import doesnt_exist
except ImportError:
# We handle the import error gracefully here
pass
def test_whatever():
pass
"""
)
res = testdir.runpytest(p.basename)
assert res.ret == 0
def test_unknown_option(self, testdir):
result = testdir.runpytest("--qwlkej")
result.stderr.fnmatch_lines(
"""
*unrecognized*
"""
)
def test_getsourcelines_error_issue553(self, testdir, monkeypatch):
monkeypatch.setattr("inspect.getsourcelines", None)
p = testdir.makepyfile(
"""
def raise_error(obj):
raise IOError('source code not available')
import inspect
inspect.getsourcelines = raise_error
def test_foo(invalid_fixture):
pass
"""
)
res = testdir.runpytest(p)
res.stdout.fnmatch_lines(
["*source code not available*", "E*fixture 'invalid_fixture' not found"]
)
def test_plugins_given_as_strings(self, tmpdir, monkeypatch):
"""test that str values passed to main() as `plugins` arg
are interpreted as module names to be imported and registered.
#855.
"""
with pytest.raises(ImportError) as excinfo:
pytest.main([str(tmpdir)], plugins=["invalid.module"])
assert "invalid" in str(excinfo.value)
p = tmpdir.join("test_test_plugins_given_as_strings.py")
p.write("def test_foo(): pass")
mod = types.ModuleType("myplugin")
monkeypatch.setitem(sys.modules, "myplugin", mod)
assert pytest.main(args=[str(tmpdir)], plugins=["myplugin"]) == 0
def test_parametrized_with_bytes_regex(self, testdir):
p = testdir.makepyfile(
"""
import re
import pytest
@pytest.mark.parametrize('r', [re.compile(b'foo')])
def test_stuff(r):
pass
"""
)
res = testdir.runpytest(p)
res.stdout.fnmatch_lines(["*1 passed*"])
def test_parametrized_with_null_bytes(self, testdir):
"""Test parametrization with values that contain null bytes and unicode characters (#2644, #2957)"""
p = testdir.makepyfile(
u"""
# encoding: UTF-8
import pytest
@pytest.mark.parametrize("data", [b"\\x00", "\\x00", u'ação'])
def test_foo(data):
assert data
"""
)
res = testdir.runpytest(p)
res.assert_outcomes(passed=3)
class TestInvocationVariants(object):
def test_earlyinit(self, testdir):
p = testdir.makepyfile(
"""
import pytest
assert hasattr(pytest, 'mark')
"""
)
result = testdir.runpython(p)
assert result.ret == 0
@pytest.mark.xfail("sys.platform.startswith('java')")
def test_pydoc(self, testdir):
for name in ("py.test", "pytest"):
result = testdir.runpython_c("import %s;help(%s)" % (name, name))
assert result.ret == 0
s = result.stdout.str()
assert "MarkGenerator" in s
def test_import_star_py_dot_test(self, testdir):
p = testdir.makepyfile(
"""
from py.test import *
#collect
#cmdline
#Item
# assert collect.Item is Item
# assert collect.Collector is Collector
main
skip
xfail
"""
)
result = testdir.runpython(p)
assert result.ret == 0
def test_import_star_pytest(self, testdir):
p = testdir.makepyfile(
"""
from pytest import *
#Item
#File
main
skip
xfail
"""
)
result = testdir.runpython(p)
assert result.ret == 0
def test_double_pytestcmdline(self, testdir):
p = testdir.makepyfile(
run="""
import pytest
pytest.main()
pytest.main()
"""
)
testdir.makepyfile(
"""
def test_hello():
pass
"""
)
result = testdir.runpython(p)
result.stdout.fnmatch_lines(["*1 passed*", "*1 passed*"])
def test_python_minus_m_invocation_ok(self, testdir):
p1 = testdir.makepyfile("def test_hello(): pass")
res = testdir.run(sys.executable, "-m", "pytest", str(p1))
assert res.ret == 0
def test_python_minus_m_invocation_fail(self, testdir):
p1 = testdir.makepyfile("def test_fail(): 0/0")
res = testdir.run(sys.executable, "-m", "pytest", str(p1))
assert res.ret == 1
def test_python_pytest_package(self, testdir):
p1 = testdir.makepyfile("def test_pass(): pass")
res = testdir.run(sys.executable, "-m", "pytest", str(p1))
assert res.ret == 0
res.stdout.fnmatch_lines(["*1 passed*"])
def test_equivalence_pytest_pytest(self):
assert pytest.main == py.test.cmdline.main
def test_invoke_with_string(self, capsys):
retcode = pytest.main("-h")
assert not retcode
out, err = capsys.readouterr()
assert "--help" in out
pytest.raises(ValueError, lambda: pytest.main(0))
def test_invoke_with_path(self, tmpdir, capsys):
retcode = pytest.main(tmpdir)
assert retcode == EXIT_NOTESTSCOLLECTED
out, err = capsys.readouterr()
def test_invoke_plugin_api(self, testdir, capsys):
class MyPlugin(object):
def pytest_addoption(self, parser):
parser.addoption("--myopt")
pytest.main(["-h"], plugins=[MyPlugin()])
out, err = capsys.readouterr()
assert "--myopt" in out
def test_pyargs_importerror(self, testdir, monkeypatch):
monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", False)
path = testdir.mkpydir("tpkg")
path.join("test_hello.py").write("raise ImportError")
result = testdir.runpytest("--pyargs", "tpkg.test_hello", syspathinsert=True)
assert result.ret != 0
result.stdout.fnmatch_lines(["collected*0*items*/*1*errors"])
def test_cmdline_python_package(self, testdir, monkeypatch):
import warnings
monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", False)
path = testdir.mkpydir("tpkg")
path.join("test_hello.py").write("def test_hello(): pass")
path.join("test_world.py").write("def test_world(): pass")
result = testdir.runpytest("--pyargs", "tpkg")
assert result.ret == 0
result.stdout.fnmatch_lines(["*2 passed*"])
result = testdir.runpytest("--pyargs", "tpkg.test_hello", syspathinsert=True)
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])
def join_pythonpath(what):
cur = os.environ.get("PYTHONPATH")
if cur:
return str(what) + os.pathsep + cur
return what
empty_package = testdir.mkpydir("empty_package")
monkeypatch.setenv("PYTHONPATH", join_pythonpath(empty_package))
# the path which is not a package raises a warning on pypy;
# no idea why only pypy and not normal python warn about it here
with warnings.catch_warnings():
warnings.simplefilter("ignore", ImportWarning)
result = testdir.runpytest("--pyargs", ".")
assert result.ret == 0
result.stdout.fnmatch_lines(["*2 passed*"])
monkeypatch.setenv("PYTHONPATH", join_pythonpath(testdir))
result = testdir.runpytest("--pyargs", "tpkg.test_missing", syspathinsert=True)
assert result.ret != 0
result.stderr.fnmatch_lines(["*not*found*test_missing*"])
def test_cmdline_python_namespace_package(self, testdir, monkeypatch):
"""
test --pyargs option with namespace packages (#1567)
"""
monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
search_path = []
for dirname in "hello", "world":
d = testdir.mkdir(dirname)
search_path.append(d)
ns = d.mkdir("ns_pkg")
ns.join("__init__.py").write(
"__import__('pkg_resources').declare_namespace(__name__)"
)
lib = ns.mkdir(dirname)
lib.ensure("__init__.py")
lib.join("test_{}.py".format(dirname)).write(
"def test_{}(): pass\n" "def test_other():pass".format(dirname)
)
# The structure of the test directory is now:
# .
# ├── hello
# │ └── ns_pkg
# │ ├── __init__.py
# │ └── hello
# │ ├── __init__.py
# │ └── test_hello.py
# └── world
# └── ns_pkg
# ├── __init__.py
# └── world
# ├── __init__.py
# └── test_world.py
def join_pythonpath(*dirs):
cur = os.environ.get("PYTHONPATH")
if cur:
dirs += (cur,)
return os.pathsep.join(str(p) for p in dirs)
monkeypatch.setenv("PYTHONPATH", join_pythonpath(*search_path))
for p in search_path:
monkeypatch.syspath_prepend(p)
# mixed module and filenames:
os.chdir("world")
result = testdir.runpytest("--pyargs", "-v", "ns_pkg.hello", "ns_pkg/world")
assert result.ret == 0
result.stdout.fnmatch_lines(
[
"*test_hello.py::test_hello*PASSED*",
"*test_hello.py::test_other*PASSED*",
"*test_world.py::test_world*PASSED*",
"*test_world.py::test_other*PASSED*",
"*4 passed*",
]
)
# specify tests within a module
testdir.chdir()
result = testdir.runpytest(
"--pyargs", "-v", "ns_pkg.world.test_world::test_other"
)
assert result.ret == 0
result.stdout.fnmatch_lines(
["*test_world.py::test_other*PASSED*", "*1 passed*"]
)
@pytest.mark.skipif(not hasattr(os, "symlink"), reason="requires symlinks")
def test_cmdline_python_package_symlink(self, testdir, monkeypatch):
"""
test --pyargs option with packages with path containing symlink can
have conftest.py in their package (#2985)
"""
# dummy check that we can actually create symlinks: on Windows `os.symlink` is available,
# but normal users require special admin privileges to create symlinks.
if sys.platform == "win32":
try:
os.symlink(
str(testdir.tmpdir.ensure("tmpfile")),
str(testdir.tmpdir.join("tmpfile2")),
)
except OSError as e:
pytest.skip(six.text_type(e.args[0]))
monkeypatch.delenv("PYTHONDONTWRITEBYTECODE", raising=False)
search_path = ["lib", os.path.join("local", "lib")]
dirname = "lib"
d = testdir.mkdir(dirname)
foo = d.mkdir("foo")
foo.ensure("__init__.py")
lib = foo.mkdir("bar")
lib.ensure("__init__.py")
lib.join("test_bar.py").write(
"def test_bar(): pass\n" "def test_other(a_fixture):pass"
)
lib.join("conftest.py").write(
"import pytest\n" "@pytest.fixture\n" "def a_fixture():pass"
)
d_local = testdir.mkdir("local")
symlink_location = os.path.join(str(d_local), "lib")
if six.PY2:
os.symlink(str(d), symlink_location)
else:
os.symlink(str(d), symlink_location, target_is_directory=True)
# The structure of the test directory is now:
# .
# ├── local
# │ └── lib -> ../lib
# └── lib
# └── foo
# ├── __init__.py
# └── bar
# ├── __init__.py
# ├── conftest.py
# └── test_bar.py
def join_pythonpath(*dirs):
cur = os.getenv("PYTHONPATH")
if cur:
dirs += (cur,)
return os.pathsep.join(str(p) for p in dirs)
monkeypatch.setenv("PYTHONPATH", join_pythonpath(*search_path))
for p in search_path:
monkeypatch.syspath_prepend(p)
# module picked up in symlink-ed directory:
result = testdir.runpytest("--pyargs", "-v", "foo.bar")
testdir.chdir()
assert result.ret == 0
result.stdout.fnmatch_lines(
[
"*lib/foo/bar/test_bar.py::test_bar*PASSED*",
"*lib/foo/bar/test_bar.py::test_other*PASSED*",
"*2 passed*",
]
)
def test_cmdline_python_package_not_exists(self, testdir):
result = testdir.runpytest("--pyargs", "tpkgwhatv")
assert result.ret
result.stderr.fnmatch_lines(["ERROR*file*or*package*not*found*"])
@pytest.mark.xfail(reason="decide: feature or bug")
def test_noclass_discovery_if_not_testcase(self, testdir):
testpath = testdir.makepyfile(
"""
import unittest
class TestHello(object):
def test_hello(self):
assert self.attr
class RealTest(unittest.TestCase, TestHello):
attr = 42
"""
)
reprec = testdir.inline_run(testpath)
reprec.assertoutcome(passed=1)
def test_doctest_id(self, testdir):
testdir.makefile(
".txt",
"""
>>> x=3
>>> x
4
""",
)
result = testdir.runpytest("-rf")
lines = result.stdout.str().splitlines()
for line in lines:
if line.startswith("FAIL "):
testid = line[5:].strip()
break
result = testdir.runpytest(testid, "-rf")
result.stdout.fnmatch_lines([line, "*1 failed*"])
def test_core_backward_compatibility(self):
"""Test backward compatibility for get_plugin_manager function. See #787."""
import _pytest.config
assert type(
_pytest.config.get_plugin_manager()
) is _pytest.config.PytestPluginManager
def test_has_plugin(self, request):
"""Test hasplugin function of the plugin manager (#932)."""
assert request.config.pluginmanager.hasplugin("python")
class TestDurations(object):
source = """
import time
frag = 0.002
def test_something():
pass
def test_2():
time.sleep(frag*5)
def test_1():
time.sleep(frag)
def test_3():
time.sleep(frag*10)
"""
def test_calls(self, testdir):
testdir.makepyfile(self.source)
result = testdir.runpytest("--durations=10")
assert result.ret == 0
result.stdout.fnmatch_lines_random(
["*durations*", "*call*test_3*", "*call*test_2*", "*call*test_1*"]
)
def test_calls_show_2(self, testdir):
testdir.makepyfile(self.source)
result = testdir.runpytest("--durations=2")
assert result.ret == 0
lines = result.stdout.get_lines_after("*slowest*durations*")
assert "4 passed" in lines[2]
def test_calls_showall(self, testdir):
testdir.makepyfile(self.source)
result = testdir.runpytest("--durations=0")
assert result.ret == 0
for x in "123":
for y in ("call",): # 'setup', 'call', 'teardown':
for line in result.stdout.lines:
if ("test_%s" % x) in line and y in line:
break
else:
raise AssertionError("not found %s %s" % (x, y))
def test_with_deselected(self, testdir):
testdir.makepyfile(self.source)
result = testdir.runpytest("--durations=2", "-k test_1")
assert result.ret == 0
result.stdout.fnmatch_lines(["*durations*", "*call*test_1*"])
def test_with_failing_collection(self, testdir):
testdir.makepyfile(self.source)
testdir.makepyfile(test_collecterror="""xyz""")
result = testdir.runpytest("--durations=2", "-k test_1")
assert result.ret == 2
result.stdout.fnmatch_lines(["*Interrupted: 1 errors during collection*"])
# Collection errors abort test execution, therefore no duration is
# output
assert "duration" not in result.stdout.str()
def test_with_not(self, testdir):
testdir.makepyfile(self.source)
result = testdir.runpytest("-k not 1")
assert result.ret == 0
class TestDurationWithFixture(object):
source = """
import time
frag = 0.001
def setup_function(func):
time.sleep(frag * 3)
def test_1():
time.sleep(frag*2)
def test_2():
time.sleep(frag)
"""
def test_setup_function(self, testdir):
testdir.makepyfile(self.source)
result = testdir.runpytest("--durations=10")
assert result.ret == 0
result.stdout.fnmatch_lines_random(
"""
*durations*
* setup *test_1*
* call *test_1*
"""
)
def test_zipimport_hook(testdir, tmpdir):
"""Test package loader is being used correctly (see #1837)."""
zipapp = pytest.importorskip("zipapp")
testdir.tmpdir.join("app").ensure(dir=1)
testdir.makepyfile(
**{
"app/foo.py": """
import pytest
def main():
pytest.main(['--pyarg', 'foo'])
"""
}
)
target = tmpdir.join("foo.zip")
zipapp.create_archive(str(testdir.tmpdir.join("app")), str(target), main="foo:main")
result = testdir.runpython(target)
assert result.ret == 0
result.stderr.fnmatch_lines(["*not found*foo*"])
assert "INTERNALERROR>" not in result.stdout.str()
def test_import_plugin_unicode_name(testdir):
testdir.makepyfile(myplugin="")
testdir.makepyfile(
"""
def test(): pass
"""
)
testdir.makeconftest(
"""
pytest_plugins = [u'myplugin']
"""
)
r = testdir.runpytest()
assert r.ret == 0
def test_deferred_hook_checking(testdir):
"""
Check hooks as late as possible (#1821).
"""
testdir.syspathinsert()
testdir.makepyfile(
**{
"plugin.py": """
class Hooks(object):
def pytest_my_hook(self, config):
pass
def pytest_configure(config):
config.pluginmanager.add_hookspecs(Hooks)
""",
"conftest.py": """
pytest_plugins = ['plugin']
def pytest_my_hook(config):
return 40
""",
"test_foo.py": """
def test(request):
assert request.config.hook.pytest_my_hook(config=request.config) == [40]
""",
}
)
result = testdir.runpytest()
result.stdout.fnmatch_lines(["* 1 passed *"])
def test_fixture_values_leak(testdir):
"""Ensure that fixture objects are properly destroyed by the garbage collector at the end of their expected
life-times (#2981).
"""
testdir.makepyfile(
"""
import attr
import gc
import pytest
import weakref
@attr.s
class SomeObj(object):
name = attr.ib()
fix_of_test1_ref = None
session_ref = None
@pytest.fixture(scope='session')
def session_fix():
global session_ref
obj = SomeObj(name='session-fixture')
session_ref = weakref.ref(obj)
return obj
@pytest.fixture
def fix(session_fix):
global fix_of_test1_ref
obj = SomeObj(name='local-fixture')
fix_of_test1_ref = weakref.ref(obj)
return obj
def test1(fix):
assert fix_of_test1_ref() is fix
def test2():
gc.collect()
# fixture "fix" created during test1 must have been destroyed by now
assert fix_of_test1_ref() is None
"""
)
result = testdir.runpytest()
result.stdout.fnmatch_lines(["* 2 passed *"])
def test_fixture_order_respects_scope(testdir):
"""Ensure that fixtures are created according to scope order, regression test for #2405
"""
testdir.makepyfile(
"""
import pytest
data = {}
@pytest.fixture(scope='module')
def clean_data():
data.clear()
@pytest.fixture(autouse=True)
def add_data():
data.update(value=True)
@pytest.mark.usefixtures('clean_data')
def test_value():
assert data.get('value')
"""
)
result = testdir.runpytest()
assert result.ret == 0
def test_frame_leak_on_failing_test(testdir):
"""pytest would leak garbage referencing the frames of tests that failed that could never be reclaimed (#2798)
Unfortunately it was not possible to remove the actual circles because most of them
are made of traceback objects which cannot be weakly referenced. Those objects at least
can be eventually claimed by the garbage collector.
"""
testdir.makepyfile(
"""
import gc
import weakref
class Obj:
pass
ref = None
def test1():
obj = Obj()
global ref
ref = weakref.ref(obj)
assert 0
def test2():
gc.collect()
assert ref() is None
"""
)
result = testdir.runpytest_subprocess()
result.stdout.fnmatch_lines(["*1 failed, 1 passed in*"])
|
atruberg/django-custom | refs/heads/master | tests/admin_registration/tests.py | 150 | from __future__ import absolute_import
from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from .models import Person, Place, Location
class NameAdmin(admin.ModelAdmin):
list_display = ['name']
save_on_top = True
class TestRegistration(TestCase):
def setUp(self):
self.site = admin.AdminSite()
def test_bare_registration(self):
self.site.register(Person)
self.assertTrue(
isinstance(self.site._registry[Person], admin.options.ModelAdmin)
)
def test_registration_with_model_admin(self):
self.site.register(Person, NameAdmin)
self.assertTrue(
isinstance(self.site._registry[Person], NameAdmin)
)
def test_prevent_double_registration(self):
self.site.register(Person)
self.assertRaises(admin.sites.AlreadyRegistered,
self.site.register,
Person)
def test_registration_with_star_star_options(self):
self.site.register(Person, search_fields=['name'])
self.assertEqual(self.site._registry[Person].search_fields, ['name'])
def test_star_star_overrides(self):
self.site.register(Person, NameAdmin,
search_fields=["name"], list_display=['__str__'])
self.assertEqual(self.site._registry[Person].search_fields, ['name'])
self.assertEqual(self.site._registry[Person].list_display,
['__str__'])
self.assertTrue(self.site._registry[Person].save_on_top)
def test_iterable_registration(self):
self.site.register([Person, Place], search_fields=['name'])
self.assertTrue(
isinstance(self.site._registry[Person], admin.options.ModelAdmin)
)
self.assertEqual(self.site._registry[Person].search_fields, ['name'])
self.assertTrue(
isinstance(self.site._registry[Place], admin.options.ModelAdmin)
)
self.assertEqual(self.site._registry[Place].search_fields, ['name'])
def test_abstract_model(self):
"""
Exception is raised when trying to register an abstract model.
Refs #12004.
"""
self.assertRaises(ImproperlyConfigured, self.site.register, Location)
|
alex-pyasetskiy/rgapi | refs/heads/master | rgapi/services/matches.py | 1 | class MatchesAPIService(object):
__api_version__ = '2.2'
__service_name__ = 'matches_api'
def __init__(self, client):
self.api_request = client.api_request
def __repr__(self):
return u"<{name}>({service}-v{version})".format(name=self.__class__.__name__,
service=self.__service_name__,
version=self.__api_version__)
# match-v2.2
def _match_request(self, end_url, region, **kwargs):
return self.api_request(
'v{version}/match/{end_url}'.format(
version=self.__api_version__,
end_url=end_url
),
region,
**kwargs
)
# match list-v2.2
def _match_list_request(self, end_url, region, **kwargs):
return self.api_request(
'v{version}/matchlist/by-summoner/{end_url}'.format(
version=self.__api_version__,
end_url=end_url,
),
region,
**kwargs
)
# game-v1.3
def _game_request(self, end_url, region, **kwargs):
return self.api_request(
'v{version}/game/{end_url}'.format(
version="v1.3", # TODO: remove
end_url=end_url
),
region,
**kwargs
)
def get_match(self, match_id, region=None, include_timeline=False):
return self._match_request(
'{match_id}'.format(match_id=match_id),
region,
includeTimeline=include_timeline
)
def get_match_list(self, summoner_id, region=None, champion_ids=None, ranked_queues=None, seasons=None,
begin_time=None, end_time=None, begin_index=None, end_index=None):
return self._match_list_request(
'{summoner_id}'.format(summoner_id=summoner_id),
region,
championsIds=champion_ids,
rankedQueues=ranked_queues,
seasons=seasons,
beginTime=begin_time,
endTime=end_time,
beginIndex=begin_index,
endIndex=end_index
)
def get_recent_games(self, summoner_id, region=None):
return self._game_request('by-summoner/{summoner_id}/recent'.format(summoner_id=summoner_id), region)
|
brainwane/zulip | refs/heads/master | zerver/migrations/0272_realm_default_code_block_language.py | 7 | # Generated by Django 2.2.10 on 2020-03-31 00:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0271_huddle_set_recipient_column_values'),
]
operations = [
migrations.AddField(
model_name='realm',
name='default_code_block_language',
field=models.TextField(default=None, null=True),
),
]
|
Nemo112/mediDbase | refs/heads/master | main.py | 1 | #!/usr/bin/python
# -*- coding: utf-8 -*-
## \file main.py
## \brief Louncher method
import os.path
import subprocess
class Chdir:
""" \brief Class for rewriting path
"""
def __init__( self, newPath ):
""" Constructor of the class
\param self Pointer on class
\param newPath New path
"""
## Saved path
self.savedPath = os.getcwd()
os.chdir(newPath)
def __del__( self ):
""" Desctructor on class
\param self Pointer on class
"""
os.chdir( self.savedPath)
if __name__ == "__main__":
## Instantion of new path
cd=Chdir("/usr/share/mediDbase")
## return code
bc=subprocess.call("./mnWindow.py", shell=True)
exit(bc)
##
##\mainpage Documentation
##
##\section About
## Use make to install.
##
## Small app for indexing CDs, USB Flashes, ...
##
##\section Contact
## Development guided by Martin Beránek martin.beranek112@gmail.com
##
|
molotof/infernal-twin | refs/heads/master | build/reportlab/src/reportlab/graphics/testdrawings.py | 32 | #!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/testdrawings.py
__version__=''' $Id $ '''
__doc__="""Defines some standard drawings to use as test cases
This contains a number of routines to generate test drawings
for reportlab/graphics. For now they are contrived, but we will expand them
to try and trip up any parser. Feel free to add more.
"""
from reportlab.graphics.shapes import *
from reportlab.lib import colors
def getDrawing1():
"""Hello World, on a rectangular background"""
D = Drawing(400, 200)
D.add(Rect(50, 50, 300, 100, fillColor=colors.yellow)) #round corners
D.add(String(180,100, 'Hello World', fillColor=colors.red))
return D
def getDrawing2():
"""This demonstrates the basic shapes. There are
no groups or references. Each solid shape should have
a purple fill."""
D = Drawing(400, 200) #, fillColor=colors.purple)
D.add(Line(10,10,390,190))
D.add(Circle(100,100,20, fillColor=colors.purple))
D.add(Circle(200,100,20, fillColor=colors.purple))
D.add(Circle(300,100,20, fillColor=colors.purple))
D.add(Wedge(330,100,40, -10,40, fillColor=colors.purple))
D.add(PolyLine([120,10,130,20,140,10,150,20,160,10,
170,20,180,10,190,20,200,10]))
D.add(Polygon([300,20,350,20,390,80,300,75, 330, 40]))
D.add(Ellipse(50, 150, 40, 20))
D.add(Rect(120, 150, 60, 30,
strokeWidth=10,
strokeColor=colors.red,
fillColor=colors.yellow)) #square corners
D.add(Rect(220, 150, 60, 30, 10, 10)) #round corners
D.add(String(10,50, 'Basic Shapes', fillColor=colors.black))
return D
##def getDrawing2():
## """This drawing uses groups. Each group has two circles and a comment.
## The line style is set at group level and should be red for the left,
## bvlue for the right."""
## D = Drawing(400, 200)
##
## Group1 = Group()
##
## Group1.add(String(50, 50, 'Group 1', fillColor=colors.black))
## Group1.add(Circle(75,100,25))
## Group1.add(Circle(125,100,25))
## D.add(Group1)
##
## Group2 = Group(
## String(250, 50, 'Group 2', fillColor=colors.black),
## Circle(275,100,25),
## Circle(325,100,25)#,
##def getDrawing2():
## """This drawing uses groups. Each group has two circles and a comment.
## The line style is set at group level and should be red for the left,
## bvlue for the right."""
## D = Drawing(400, 200)
##
## Group1 = Group()
##
## Group1.add(String(50, 50, 'Group 1', fillColor=colors.black))
## Group1.add(Circle(75,100,25))
## Group1.add(Circle(125,100,25))
## D.add(Group1)
##
## Group2 = Group(
## String(250, 50, 'Group 2', fillColor=colors.black),
## Circle(275,100,25),
## Circle(325,100,25)#,
##
## #group attributes
## #strokeColor=colors.blue
## )
## D.add(Group2)
## return D
##
##
##def getDrawing3():
## """This uses a named reference object. The house is a 'subroutine'
## the basic brick colored walls are defined, but the roof and window
## color are undefined and may be set by the container."""
##
## D = Drawing(400, 200, fill=colors.bisque)
##
##
## House = Group(
## Rect(2,20,36,30, fill=colors.bisque), #walls
## Polygon([0,20,40,20,20,5]), #roof
## Rect(8, 38, 8, 12), #door
## Rect(25, 38, 8, 7), #window
## Rect(8, 25, 8, 7), #window
## Rect(25, 25, 8, 7) #window
##
## )
## D.addDef('MyHouse', House)
##
## # one row all the same color
## D.add(String(20, 40, 'British Street...',fill=colors.black))
## for i in range(6):
## x = i * 50
## D.add(NamedReference('MyHouse',
## House,
## transform=translate(x, 40),
## fill = colors.brown
## )
## )
##
## # now do a row all different
## D.add(String(20, 120, 'Mediterranean Street...',fill=colors.black))
## x = 0
## for color in (colors.blue, colors.yellow, colors.orange,
## colors.red, colors.green, colors.chartreuse):
## D.add(NamedReference('MyHouse',
## House,
## transform=translate(x,120),
## fill = color,
## )
## )
## x = x + 50
## #..by popular demand, the mayor gets a big one at the end
## D.add(NamedReference('MyHouse',
## House,
## transform=mmult(translate(x,110), scale(1.2,1.2)),
## fill = color,
## )
## )
##
##
## return D
##
##def getDrawing4():
## """This tests that attributes are 'unset' correctly when
## one steps back out of a drawing node. All the circles are part of a
## group setting the line color to blue; the second circle explicitly
## sets it to red. Ideally, the third circle should go back to blue."""
## D = Drawing(400, 200)
##
##
## G = Group(
## Circle(100,100,20),
## Circle(200,100,20, stroke=colors.blue),
## Circle(300,100,20),
## stroke=colors.red,
## stroke_width=3,
## fill=colors.aqua
## )
## D.add(G)
##
##
## D.add(String(10,50, 'Stack Unwinding - should be red, blue, red'))
##
## return D
##
##
##def getDrawing5():
## """This Rotates Coordinate Axes"""
## D = Drawing(400, 200)
##
##
##
## Axis = Group(
## Line(0,0,100,0), #x axis
## Line(0,0,0,50), # y axis
## Line(0,10,10,10), #ticks on y axis
## Line(0,20,10,20),
## Line(0,30,10,30),
## Line(0,40,10,40),
## Line(10,0,10,10), #ticks on x axis
## Line(20,0,20,10),
## Line(30,0,30,10),
## Line(40,0,40,10),
## Line(50,0,50,10),
## Line(60,0,60,10),
## Line(70,0,70,10),
## Line(80,0,80,10),
## Line(90,0,90,10),
## String(20, 35, 'Axes', fill=colors.black)
## )
##
## D.addDef('Axes', Axis)
##
## D.add(NamedReference('Axis', Axis,
## transform=translate(10,10)))
## D.add(NamedReference('Axis', Axis,
## transform=mmult(translate(150,10),rotate(15)))
## )
## return D
##
##def getDrawing6():
## """This Rotates Text"""
## D = Drawing(400, 300, fill=colors.black)
##
## xform = translate(200,150)
## C = (colors.black,colors.red,colors.green,colors.blue,colors.brown,colors.gray, colors.pink,
## colors.lavender,colors.lime, colors.mediumblue, colors.magenta, colors.limegreen)
##
## for i in range(12):
## D.add(String(0, 0, ' - - Rotated Text', fill=C[i%len(C)], transform=mmult(xform, rotate(30*i))))
##
## return D
##
##def getDrawing7():
## """This defines and tests a simple UserNode0 (the trailing zero denotes
## an experimental method which is not part of the supported API yet).
## Each of the four charts is a subclass of UserNode which generates a random
## series when rendered."""
##
## class MyUserNode(UserNode0):
## import whrandom, math
##
##
## def provideNode(self, sender):
## """draw a simple chart that changes everytime it's drawn"""
## # print "here's a random number %s" % self.whrandom.random()
## #print "MyUserNode.provideNode being called by %s" % sender
## g = Group()
## #g._state = self._state # this is naughty
## PingoNode.__init__(g, self._state) # is this less naughty ?
## w = 80.0
## h = 50.0
## g.add(Rect(0,0, w, h, stroke=colors.black))
## N = 10.0
## x,y = (0,h)
## dx = w/N
## for ii in range(N):
## dy = (h/N) * self.whrandom.random()
## g.add(Line(x,y,x+dx, y-dy))
## x = x + dx
## y = y - dy
## return g
##
## D = Drawing(400,200, fill=colors.white) # AR - same size as others
##
## D.add(MyUserNode())
##
## graphcolor= [colors.green, colors.red, colors.brown, colors.purple]
## for ii in range(4):
## D.add(Group( MyUserNode(stroke=graphcolor[ii], stroke_width=2),
## transform=translate(ii*90,0) ))
##
## #un = MyUserNode()
## #print un.provideNode()
## return D
##
##def getDrawing8():
## """Test Path operations--lineto, curveTo, etc."""
## D = Drawing(400, 200, fill=None, stroke=colors.purple, stroke_width=2)
##
## xform = translate(200,100)
## C = (colors.black,colors.red,colors.green,colors.blue,colors.brown,colors.gray, colors.pink,
## colors.lavender,colors.lime, colors.mediumblue, colors.magenta, colors.limegreen)
## p = Path(50,50)
## p.lineTo(100,100)
## p.moveBy(-25,25)
## p.curveTo(150,125, 125,125, 200,50)
## p.curveTo(175, 75, 175, 98, 62, 87)
##
##
## D.add(p)
## D.add(String(10,30, 'Tests of path elements-lines and bezier curves-and text formating'))
## D.add(Line(220,150, 220,200, stroke=colors.red))
## D.add(String(220,180, "Text should be centered", text_anchor="middle") )
##
##
## return D
if __name__=='__main__':
print(__doc__)
|
rruebner/odoo | refs/heads/master | addons/l10n_ar/__init__.py | 2120 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2011 Cubic ERP - Teradata SAC. (http://cubicerp.com).
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
##############################################################################
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
mnicholl/MOSFiT | refs/heads/master | mosfit/modules/parameters/gaussian.py | 5 | """Definitions for the `Gaussian` class."""
import numpy as np
from scipy.special import erfinv
from mosfit.modules.parameters.parameter import Parameter
# Important: Only define one ``Module`` class per file.
class Gaussian(Parameter):
"""Parameter with Gaussian prior.
If the parameter must be positive, set the `pos` keyword to True.
"""
def __init__(self, **kwargs):
"""Initialize module."""
super(Gaussian, self).__init__(**kwargs)
self._mu = kwargs.get(self.key('mu'), None)
self._sigma = kwargs.get(self.key('sigma'), None)
if self._log:
self._mu = np.log(self._mu)
self._sigma = np.log(10.0 ** self._sigma)
if not self._mu:
raise ValueError('Need to set a value for mu!')
if not self._sigma:
raise ValueError('Need to set a value for sigma!')
def lnprior_pdf(self, x):
"""Evaluate natural log of probability density function."""
value = self.value(x)
if self._log:
value = np.log(value)
return -(value - self._mu) ** 2 / (2. * self._sigma ** 2)
def prior_icdf(self, u):
"""Evaluate inverse cumulative density function."""
value = (erfinv(2.0 * u - 1.0) * np.sqrt(2.)) * self._sigma + self._mu
value = (value - self._min_value) / (self._max_value - self._min_value)
return np.clip(value, 0.0, 1.0)
|
cyc805/FR_Comparison_LRD | refs/heads/master | src/tap-bridge/bindings/modulegen__gcc_LP64.py | 12 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
import pybindgen.settings
import warnings
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
return True
pybindgen.settings.error_handler = ErrorHandler()
import sys
def module_init():
root_module = Module('ns.tap_bridge', cpp_namespace='::ns3')
return root_module
def register_types(module):
root_module = module.get_root()
## address.h (module 'network'): ns3::Address [class]
module.add_class('Address', import_from_module='ns.network')
## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration]
module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network')
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class]
module.add_class('AttributeConstructionList', import_from_module='ns.core')
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct]
module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList'])
## buffer.h (module 'network'): ns3::Buffer [class]
module.add_class('Buffer', import_from_module='ns.network')
## buffer.h (module 'network'): ns3::Buffer::Iterator [class]
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer'])
## packet.h (module 'network'): ns3::ByteTagIterator [class]
module.add_class('ByteTagIterator', import_from_module='ns.network')
## packet.h (module 'network'): ns3::ByteTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList [class]
module.add_class('ByteTagList', import_from_module='ns.network')
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class]
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator'])
## callback.h (module 'core'): ns3::CallbackBase [class]
module.add_class('CallbackBase', import_from_module='ns.core')
## data-rate.h (module 'network'): ns3::DataRate [class]
module.add_class('DataRate', import_from_module='ns.network')
## event-id.h (module 'core'): ns3::EventId [class]
module.add_class('EventId', import_from_module='ns.core')
## hash.h (module 'core'): ns3::Hasher [class]
module.add_class('Hasher', import_from_module='ns.core')
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
module.add_class('Ipv4Address', import_from_module='ns.network')
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class]
module.add_class('Ipv4Mask', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
module.add_class('Ipv6Address', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class]
module.add_class('Ipv6Prefix', import_from_module='ns.network')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
module.add_class('Mac48Address', import_from_module='ns.network')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address'])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class]
module.add_class('NetDeviceContainer', import_from_module='ns.network')
## object-base.h (module 'core'): ns3::ObjectBase [class]
module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core')
## object.h (module 'core'): ns3::ObjectDeleter [struct]
module.add_class('ObjectDeleter', import_from_module='ns.core')
## object-factory.h (module 'core'): ns3::ObjectFactory [class]
module.add_class('ObjectFactory', import_from_module='ns.core')
## packet-metadata.h (module 'network'): ns3::PacketMetadata [class]
module.add_class('PacketMetadata', import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration]
module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class]
module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet.h (module 'network'): ns3::PacketTagIterator [class]
module.add_class('PacketTagIterator', import_from_module='ns.network')
## packet.h (module 'network'): ns3::PacketTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator'])
## packet-tag-list.h (module 'network'): ns3::PacketTagList [class]
module.add_class('PacketTagList', import_from_module='ns.network')
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct]
module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList'])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration]
module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network')
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## tag.h (module 'network'): ns3::Tag [class]
module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
## tag-buffer.h (module 'network'): ns3::TagBuffer [class]
module.add_class('TagBuffer', import_from_module='ns.network')
## tap-bridge-helper.h (module 'tap-bridge'): ns3::TapBridgeHelper [class]
module.add_class('TapBridgeHelper')
## type-id.h (module 'core'): ns3::TypeId [class]
module.add_class('TypeId', import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration]
module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core')
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct]
module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct]
module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId'])
## empty.h (module 'core'): ns3::empty [class]
module.add_class('empty', import_from_module='ns.core')
## int64x64-double.h (module 'core'): ns3::int64x64_t [class]
module.add_class('int64x64_t', import_from_module='ns.core')
## chunk.h (module 'network'): ns3::Chunk [class]
module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
## header.h (module 'network'): ns3::Header [class]
module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## object.h (module 'core'): ns3::Object [class]
module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
## object.h (module 'core'): ns3::Object::AggregateIterator [class]
module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object'])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::FdReader', 'ns3::empty', 'ns3::DefaultDeleter<ns3::FdReader>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::SystemThread', 'ns3::empty', 'ns3::DefaultDeleter<ns3::SystemThread>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## system-thread.h (module 'core'): ns3::SystemThread [class]
module.add_class('SystemThread', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >'])
## nstime.h (module 'core'): ns3::Time [class]
module.add_class('Time', import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time::Unit [enumeration]
module.add_enum('Unit', ['S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time [class]
root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t'])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class]
module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
## trailer.h (module 'network'): ns3::Trailer [class]
module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## attribute.h (module 'core'): ns3::AttributeAccessor [class]
module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
## attribute.h (module 'core'): ns3::AttributeChecker [class]
module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
## attribute.h (module 'core'): ns3::AttributeValue [class]
module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
## callback.h (module 'core'): ns3::CallbackChecker [class]
module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## callback.h (module 'core'): ns3::CallbackImplBase [class]
module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
## callback.h (module 'core'): ns3::CallbackValue [class]
module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## data-rate.h (module 'network'): ns3::DataRateChecker [class]
module.add_class('DataRateChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## data-rate.h (module 'network'): ns3::DataRateValue [class]
module.add_class('DataRateValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## attribute.h (module 'core'): ns3::EmptyAttributeValue [class]
module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## event-impl.h (module 'core'): ns3::EventImpl [class]
module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
## unix-fd-reader.h (module 'core'): ns3::FdReader [class]
module.add_class('FdReader', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class]
module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class]
module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class]
module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class]
module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class]
module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class]
module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class]
module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class]
module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class]
module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class]
module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## net-device.h (module 'network'): ns3::NetDevice [class]
module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object'])
## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration]
module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network')
## nix-vector.h (module 'network'): ns3::NixVector [class]
module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
## node.h (module 'network'): ns3::Node [class]
module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object'])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class]
module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class]
module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## packet.h (module 'network'): ns3::Packet [class]
module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge [class]
module.add_class('TapBridge', parent=root_module['ns3::NetDevice'])
## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge::Mode [enumeration]
module.add_enum('Mode', ['ILLEGAL', 'CONFIGURE_LOCAL', 'USE_LOCAL', 'USE_BRIDGE'], outer_class=root_module['ns3::TapBridge'])
## tap-bridge.h (module 'tap-bridge'): ns3::TapBridgeFdReader [class]
module.add_class('TapBridgeFdReader', parent=root_module['ns3::FdReader'])
## nstime.h (module 'core'): ns3::TimeValue [class]
module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## type-id.h (module 'core'): ns3::TypeIdChecker [class]
module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## type-id.h (module 'core'): ns3::TypeIdValue [class]
module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## address.h (module 'network'): ns3::AddressChecker [class]
module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## address.h (module 'network'): ns3::AddressValue [class]
module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## Register a nested module for the namespace FatalImpl
nested_module = module.add_cpp_namespace('FatalImpl')
register_types_ns3_FatalImpl(nested_module)
## Register a nested module for the namespace Hash
nested_module = module.add_cpp_namespace('Hash')
register_types_ns3_Hash(nested_module)
def register_types_ns3_FatalImpl(module):
root_module = module.get_root()
def register_types_ns3_Hash(module):
root_module = module.get_root()
## hash-function.h (module 'core'): ns3::Hash::Implementation [class]
module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >'])
typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) *', 'ns3::Hash::Hash32Function_ptr')
typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) **', 'ns3::Hash::Hash32Function_ptr*')
typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) *&', 'ns3::Hash::Hash32Function_ptr&')
typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) *', 'ns3::Hash::Hash64Function_ptr')
typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) **', 'ns3::Hash::Hash64Function_ptr*')
typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) *&', 'ns3::Hash::Hash64Function_ptr&')
## Register a nested module for the namespace Function
nested_module = module.add_cpp_namespace('Function')
register_types_ns3_Hash_Function(nested_module)
def register_types_ns3_Hash_Function(module):
root_module = module.get_root()
## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class]
module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class]
module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class]
module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class]
module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation'])
def register_methods(root_module):
register_Ns3Address_methods(root_module, root_module['ns3::Address'])
register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList'])
register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item'])
register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer'])
register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator'])
register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator'])
register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item'])
register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList'])
register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator'])
register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item'])
register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase'])
register_Ns3DataRate_methods(root_module, root_module['ns3::DataRate'])
register_Ns3EventId_methods(root_module, root_module['ns3::EventId'])
register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher'])
register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address'])
register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask'])
register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address'])
register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix'])
register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address'])
register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer'])
register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase'])
register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter'])
register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory'])
register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata'])
register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item'])
register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator'])
register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator'])
register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item'])
register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList'])
register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData'])
register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
register_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
register_Ns3TapBridgeHelper_methods(root_module, root_module['ns3::TapBridgeHelper'])
register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId'])
register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation'])
register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation'])
register_Ns3Empty_methods(root_module, root_module['ns3::empty'])
register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t'])
register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk'])
register_Ns3Header_methods(root_module, root_module['ns3::Header'])
register_Ns3Object_methods(root_module, root_module['ns3::Object'])
register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator'])
register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
register_Ns3SimpleRefCount__Ns3FdReader_Ns3Empty_Ns3DefaultDeleter__lt__ns3FdReader__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >'])
register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >'])
register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
register_Ns3SimpleRefCount__Ns3SystemThread_Ns3Empty_Ns3DefaultDeleter__lt__ns3SystemThread__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >'])
register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
register_Ns3SystemThread_methods(root_module, root_module['ns3::SystemThread'])
register_Ns3Time_methods(root_module, root_module['ns3::Time'])
register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor'])
register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer'])
register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor'])
register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker'])
register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue'])
register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker'])
register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase'])
register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue'])
register_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker'])
register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue'])
register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue'])
register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl'])
register_Ns3FdReader_methods(root_module, root_module['ns3::FdReader'])
register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker'])
register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue'])
register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker'])
register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue'])
register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker'])
register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue'])
register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker'])
register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue'])
register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker'])
register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue'])
register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice'])
register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector'])
register_Ns3Node_methods(root_module, root_module['ns3::Node'])
register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker'])
register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue'])
register_Ns3Packet_methods(root_module, root_module['ns3::Packet'])
register_Ns3TapBridge_methods(root_module, root_module['ns3::TapBridge'])
register_Ns3TapBridgeFdReader_methods(root_module, root_module['ns3::TapBridgeFdReader'])
register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue'])
register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker'])
register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue'])
register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker'])
register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue'])
register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation'])
register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a'])
register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32'])
register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64'])
register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3'])
return
def register_Ns3Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## address.h (module 'network'): ns3::Address::Address() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor]
cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor]
cls.add_constructor([param('ns3::Address const &', 'address')])
## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function]
cls.add_method('CheckCompatible',
'bool',
[param('uint8_t', 'type'), param('uint8_t', 'len')],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function]
cls.add_method('CopyAllFrom',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function]
cls.add_method('CopyAllTo',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint8_t', 'len')],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function]
cls.add_method('CopyFrom',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint8_t', 'len')])
## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'uint32_t',
[param('uint8_t *', 'buffer')],
is_const=True)
## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'buffer')])
## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function]
cls.add_method('GetLength',
'uint8_t',
[],
is_const=True)
## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function]
cls.add_method('IsInvalid',
'bool',
[],
is_const=True)
## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function]
cls.add_method('IsMatchingType',
'bool',
[param('uint8_t', 'type')],
is_const=True)
## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function]
cls.add_method('Register',
'uint8_t',
[],
is_static=True)
## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'buffer')],
is_const=True)
return
def register_Ns3AttributeConstructionList_methods(root_module, cls):
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor]
cls.add_constructor([])
## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')])
## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::AttributeConstructionList::Item >',
[],
is_const=True)
## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::AttributeConstructionList::Item >',
[],
is_const=True)
## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('Find',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True)
return
def register_Ns3AttributeConstructionListItem_methods(root_module, cls):
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor]
cls.add_constructor([])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable]
cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False)
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable]
cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False)
return
def register_Ns3Buffer_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor]
cls.add_constructor([param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function]
cls.add_method('AddAtEnd',
'bool',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function]
cls.add_method('AddAtStart',
'bool',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function]
cls.add_method('Begin',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Buffer',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function]
cls.add_method('CreateFullCopy',
'ns3::Buffer',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function]
cls.add_method('End',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function]
cls.add_method('GetCurrentEndOffset',
'int32_t',
[],
is_const=True)
## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function]
cls.add_method('GetCurrentStartOffset',
'int32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function]
cls.add_method('PeekData',
'uint8_t const *',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3BufferIterator_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')])
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function]
cls.add_method('GetDistanceFrom',
'uint32_t',
[param('ns3::Buffer::Iterator const &', 'o')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function]
cls.add_method('IsEnd',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function]
cls.add_method('IsStart',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function]
cls.add_method('Next',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function]
cls.add_method('Next',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function]
cls.add_method('Prev',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function]
cls.add_method('Prev',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function]
cls.add_method('ReadLsbtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function]
cls.add_method('ReadLsbtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function]
cls.add_method('ReadLsbtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function]
cls.add_method('ReadNtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function]
cls.add_method('ReadNtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function]
cls.add_method('ReadNtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function]
cls.add_method('Write',
'void',
[param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function]
cls.add_method('WriteHtolsbU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function]
cls.add_method('WriteHtolsbU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function]
cls.add_method('WriteHtolsbU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function]
cls.add_method('WriteHtonU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function]
cls.add_method('WriteHtonU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function]
cls.add_method('WriteHtonU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data'), param('uint32_t', 'len')])
return
def register_Ns3ByteTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagIterator::Item',
[])
return
def register_Ns3ByteTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function]
cls.add_method('GetEnd',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function]
cls.add_method('GetStart',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3ByteTagList_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor]
cls.add_constructor([])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function]
cls.add_method('Add',
'ns3::TagBuffer',
[param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function]
cls.add_method('Add',
'void',
[param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function]
cls.add_method('AddAtEnd',
'void',
[param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function]
cls.add_method('AddAtStart',
'void',
[param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function]
cls.add_method('Begin',
'ns3::ByteTagList::Iterator',
[param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')],
is_const=True)
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
return
def register_Ns3ByteTagListIterator_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')])
## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function]
cls.add_method('GetOffsetStart',
'uint32_t',
[],
is_const=True)
## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagList::Iterator::Item',
[])
return
def register_Ns3ByteTagListIteratorItem_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor]
cls.add_constructor([param('ns3::TagBuffer', 'buf')])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable]
cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable]
cls.add_instance_attribute('end', 'int32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable]
cls.add_instance_attribute('size', 'uint32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable]
cls.add_instance_attribute('start', 'int32_t', is_const=False)
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3CallbackBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function]
cls.add_method('GetImpl',
'ns3::Ptr< ns3::CallbackImplBase >',
[],
is_const=True)
## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')],
visibility='protected')
## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function]
cls.add_method('Demangle',
'std::string',
[param('std::string const &', 'mangled')],
is_static=True, visibility='protected')
return
def register_Ns3DataRate_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('>=')
## data-rate.h (module 'network'): ns3::DataRate::DataRate(ns3::DataRate const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRate const &', 'arg0')])
## data-rate.h (module 'network'): ns3::DataRate::DataRate() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRate::DataRate(uint64_t bps) [constructor]
cls.add_constructor([param('uint64_t', 'bps')])
## data-rate.h (module 'network'): ns3::DataRate::DataRate(std::string rate) [constructor]
cls.add_constructor([param('std::string', 'rate')])
## data-rate.h (module 'network'): double ns3::DataRate::CalculateTxTime(uint32_t bytes) const [member function]
cls.add_method('CalculateTxTime',
'double',
[param('uint32_t', 'bytes')],
is_const=True)
## data-rate.h (module 'network'): uint64_t ns3::DataRate::GetBitRate() const [member function]
cls.add_method('GetBitRate',
'uint64_t',
[],
is_const=True)
return
def register_Ns3EventId_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('==')
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventId const &', 'arg0')])
## event-id.h (module 'core'): ns3::EventId::EventId() [constructor]
cls.add_constructor([])
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')])
## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function]
cls.add_method('GetTs',
'uint64_t',
[],
is_const=True)
## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function]
cls.add_method('GetUid',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function]
cls.add_method('IsExpired',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function]
cls.add_method('IsRunning',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function]
cls.add_method('PeekEventImpl',
'ns3::EventImpl *',
[],
is_const=True)
return
def register_Ns3Hasher_methods(root_module, cls):
## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hasher const &', 'arg0')])
## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor]
cls.add_constructor([])
## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')])
## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')])
## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('std::string const', 's')])
## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')])
## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('std::string const', 's')])
## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function]
cls.add_method('clear',
'ns3::Hasher &',
[])
return
def register_Ns3Ipv4Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor]
cls.add_constructor([param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('CombineMask',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv4Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv4Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('GetSubnetDirectedBroadcast',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Address const &', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function]
cls.add_method('IsLocalMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('IsSubnetDirectedBroadcast',
'bool',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
return
def register_Ns3Ipv4Mask_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor]
cls.add_constructor([param('uint32_t', 'mask')])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor]
cls.add_constructor([param('char const *', 'mask')])
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function]
cls.add_method('GetInverse',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint16_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Mask',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Mask', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'mask')])
return
def register_Ns3Ipv6Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor]
cls.add_constructor([param('uint8_t *', 'address')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')])
## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function]
cls.add_method('CombinePrefix',
'ns3::Ipv6Address',
[param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv6Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv6Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function]
cls.add_method('GetAllHostsMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function]
cls.add_method('GetAllNodesMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function]
cls.add_method('GetAllRoutersMulticast',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function]
cls.add_method('GetIpv4MappedAddress',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function]
cls.add_method('IsAllHostsMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function]
cls.add_method('IsAllNodesMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function]
cls.add_method('IsAllRoutersMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function]
cls.add_method('IsAny',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function]
cls.add_method('IsDocumentation',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Address const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() [member function]
cls.add_method('IsIpv4MappedAddress',
'bool',
[])
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function]
cls.add_method('IsLinkLocal',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function]
cls.add_method('IsLinkLocalMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function]
cls.add_method('IsLocalhost',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function]
cls.add_method('IsSolicitedMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function]
cls.add_method('MakeAutoconfiguredAddress',
'ns3::Ipv6Address',
[param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac16Address', 'mac')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac48Address', 'mac')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function]
cls.add_method('MakeAutoconfiguredLinkLocalAddress',
'ns3::Ipv6Address',
[param('ns3::Mac64Address', 'mac')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function]
cls.add_method('MakeIpv4MappedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv4Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function]
cls.add_method('MakeSolicitedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv6Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function]
cls.add_method('Set',
'void',
[param('uint8_t *', 'address')])
return
def register_Ns3Ipv6Prefix_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor]
cls.add_constructor([param('uint8_t *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor]
cls.add_constructor([param('char const *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor]
cls.add_constructor([param('uint8_t', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint8_t',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Prefix const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
return
def register_Ns3Mac48Address_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')])
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor]
cls.add_constructor([param('char const *', 'str')])
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Mac48Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'buffer')])
## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'buffer')],
is_const=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function]
cls.add_method('GetMulticast',
'ns3::Mac48Address',
[param('ns3::Ipv4Address', 'address')],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function]
cls.add_method('GetMulticast',
'ns3::Mac48Address',
[param('ns3::Ipv6Address', 'address')],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function]
cls.add_method('GetMulticast6Prefix',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function]
cls.add_method('GetMulticastPrefix',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function]
cls.add_method('IsGroup',
'bool',
[],
is_const=True)
## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3NetDeviceContainer_methods(root_module, cls):
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor]
cls.add_constructor([])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor]
cls.add_constructor([param('std::string', 'devName')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NetDeviceContainer', 'other')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'deviceName')])
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True)
## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3ObjectBase_methods(root_module, cls):
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor]
cls.add_constructor([])
## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')])
## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function]
cls.add_method('GetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'value')],
is_const=True)
## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function]
cls.add_method('GetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')],
is_const=True)
## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttributeFailSafe',
'bool',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceConnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnect',
'bool',
[param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function]
cls.add_method('TraceDisconnectWithoutContext',
'bool',
[param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')])
## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function]
cls.add_method('ConstructSelf',
'void',
[param('ns3::AttributeConstructionList const &', 'attributes')],
visibility='protected')
## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function]
cls.add_method('NotifyConstructionCompleted',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectDeleter_methods(root_module, cls):
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor]
cls.add_constructor([])
## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')])
## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function]
cls.add_method('Delete',
'void',
[param('ns3::Object *', 'object')],
is_static=True)
return
def register_Ns3ObjectFactory_methods(root_module, cls):
cls.add_output_stream_operator()
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor]
cls.add_constructor([param('std::string', 'typeId')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('ns3::TypeId', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('char const *', 'tid')])
## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function]
cls.add_method('SetTypeId',
'void',
[param('std::string', 'tid')])
return
def register_Ns3PacketMetadata_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor]
cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[param('ns3::Buffer', 'buffer')],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function]
cls.add_method('CreateFragment',
'ns3::PacketMetadata',
[param('uint32_t', 'start'), param('uint32_t', 'end')],
is_const=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function]
cls.add_method('Enable',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('RemoveHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('RemoveTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3PacketMetadataItem_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor]
cls.add_constructor([])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable]
cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable]
cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable]
cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable]
cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable]
cls.add_instance_attribute('isFragment', 'bool', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3PacketMetadataItemIterator_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor]
cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')])
## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketMetadata::Item',
[])
return
def register_Ns3PacketTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketTagIterator::Item',
[])
return
def register_Ns3PacketTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3PacketTagList_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList const &', 'o')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function]
cls.add_method('Add',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function]
cls.add_method('Head',
'ns3::PacketTagList::TagData const *',
[],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function]
cls.add_method('Peek',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function]
cls.add_method('Remove',
'bool',
[param('ns3::Tag &', 'tag')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function]
cls.add_method('Replace',
'bool',
[param('ns3::Tag &', 'tag')])
return
def register_Ns3PacketTagListTagData_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable]
cls.add_instance_attribute('count', 'uint32_t', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable]
cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable]
cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Tag_methods(root_module, cls):
## tag.h (module 'network'): ns3::Tag::Tag() [constructor]
cls.add_constructor([])
## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Tag const &', 'arg0')])
## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_virtual=True)
## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TagBuffer_methods(root_module, cls):
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')])
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor]
cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function]
cls.add_method('CopyFrom',
'void',
[param('ns3::TagBuffer', 'o')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function]
cls.add_method('ReadDouble',
'double',
[])
## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function]
cls.add_method('TrimAtEnd',
'void',
[param('uint32_t', 'trim')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function]
cls.add_method('WriteDouble',
'void',
[param('double', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'v')])
return
def register_Ns3TapBridgeHelper_methods(root_module, cls):
## tap-bridge-helper.h (module 'tap-bridge'): ns3::TapBridgeHelper::TapBridgeHelper(ns3::TapBridgeHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TapBridgeHelper const &', 'arg0')])
## tap-bridge-helper.h (module 'tap-bridge'): ns3::TapBridgeHelper::TapBridgeHelper() [constructor]
cls.add_constructor([])
## tap-bridge-helper.h (module 'tap-bridge'): ns3::TapBridgeHelper::TapBridgeHelper(ns3::Ipv4Address gateway) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'gateway')])
## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::NetDevice> nd) [member function]
cls.add_method('Install',
'ns3::Ptr< ns3::NetDevice >',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::NetDevice >', 'nd')])
## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(std::string nodeName, ns3::Ptr<ns3::NetDevice> nd) [member function]
cls.add_method('Install',
'ns3::Ptr< ns3::NetDevice >',
[param('std::string', 'nodeName'), param('ns3::Ptr< ns3::NetDevice >', 'nd')])
## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(ns3::Ptr<ns3::Node> node, std::string ndName) [member function]
cls.add_method('Install',
'ns3::Ptr< ns3::NetDevice >',
[param('ns3::Ptr< ns3::Node >', 'node'), param('std::string', 'ndName')])
## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(std::string nodeName, std::string ndName) [member function]
cls.add_method('Install',
'ns3::Ptr< ns3::NetDevice >',
[param('std::string', 'nodeName'), param('std::string', 'ndName')])
## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::NetDevice> nd, ns3::AttributeValue const & bridgeType) [member function]
cls.add_method('Install',
'ns3::Ptr< ns3::NetDevice >',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('ns3::AttributeValue const &', 'bridgeType')])
## tap-bridge-helper.h (module 'tap-bridge'): void ns3::TapBridgeHelper::SetAttribute(std::string n1, ns3::AttributeValue const & v1) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')])
return
def register_Ns3TypeId_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor]
cls.add_constructor([param('char const *', 'name')])
## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor]
cls.add_constructor([param('ns3::TypeId const &', 'o')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function]
cls.add_method('GetAttribute',
'ns3::TypeId::AttributeInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function]
cls.add_method('GetAttributeFullName',
'std::string',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function]
cls.add_method('GetAttributeN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function]
cls.add_method('GetConstructor',
'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function]
cls.add_method('GetGroupName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function]
cls.add_method('GetHash',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function]
cls.add_method('GetParent',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function]
cls.add_method('GetRegistered',
'ns3::TypeId',
[param('uint32_t', 'i')],
is_static=True)
## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function]
cls.add_method('GetRegisteredN',
'uint32_t',
[],
is_static=True)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function]
cls.add_method('GetTraceSource',
'ns3::TypeId::TraceSourceInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function]
cls.add_method('GetTraceSourceN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function]
cls.add_method('GetUid',
'uint16_t',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function]
cls.add_method('HasConstructor',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function]
cls.add_method('HasParent',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function]
cls.add_method('HideFromDocumentation',
'ns3::TypeId',
[])
## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function]
cls.add_method('IsChildOf',
'bool',
[param('ns3::TypeId', 'other')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function]
cls.add_method('LookupAttributeByName',
'bool',
[param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function]
cls.add_method('LookupByHash',
'ns3::TypeId',
[param('uint32_t', 'hash')],
is_static=True)
## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function]
cls.add_method('LookupByHashFailSafe',
'bool',
[param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')],
is_static=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function]
cls.add_method('LookupByName',
'ns3::TypeId',
[param('std::string', 'name')],
is_static=True)
## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function]
cls.add_method('LookupTraceSourceByName',
'ns3::Ptr< ns3::TraceSourceAccessor const >',
[param('std::string', 'name')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function]
cls.add_method('MustHideFromDocumentation',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function]
cls.add_method('SetAttributeInitialValue',
'bool',
[param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function]
cls.add_method('SetGroupName',
'ns3::TypeId',
[param('std::string', 'groupName')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function]
cls.add_method('SetParent',
'ns3::TypeId',
[param('ns3::TypeId', 'tid')])
## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function]
cls.add_method('SetUid',
'void',
[param('uint16_t', 'tid')])
return
def register_Ns3TypeIdAttributeInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable]
cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable]
cls.add_instance_attribute('flags', 'uint32_t', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable]
cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable]
cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
return
def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
return
def register_Ns3Empty_methods(root_module, cls):
## empty.h (module 'core'): ns3::empty::empty() [constructor]
cls.add_constructor([])
## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor]
cls.add_constructor([param('ns3::empty const &', 'arg0')])
return
def register_Ns3Int64x64_t_methods(root_module, cls):
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_unary_numeric_operator('-')
cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right'))
cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', 'right'))
cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', 'right'))
cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', 'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor]
cls.add_constructor([])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor]
cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')])
## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'o')])
## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function]
cls.add_method('GetHigh',
'int64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function]
cls.add_method('GetLow',
'uint64_t',
[],
is_const=True)
## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function]
cls.add_method('Invert',
'ns3::int64x64_t',
[param('uint64_t', 'v')],
is_static=True)
## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function]
cls.add_method('MulByInvert',
'void',
[param('ns3::int64x64_t const &', 'o')])
return
def register_Ns3Chunk_methods(root_module, cls):
## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor]
cls.add_constructor([])
## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Chunk const &', 'arg0')])
## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_virtual=True)
## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Header_methods(root_module, cls):
cls.add_output_stream_operator()
## header.h (module 'network'): ns3::Header::Header() [constructor]
cls.add_constructor([])
## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Header const &', 'arg0')])
## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_virtual=True)
## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Object_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::Object() [constructor]
cls.add_constructor([])
## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function]
cls.add_method('AggregateObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'other')])
## object.h (module 'core'): void ns3::Object::Dispose() [member function]
cls.add_method('Dispose',
'void',
[])
## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function]
cls.add_method('GetAggregateIterator',
'ns3::Object::AggregateIterator',
[],
is_const=True)
## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object.h (module 'core'): void ns3::Object::Initialize() [member function]
cls.add_method('Initialize',
'void',
[])
## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor]
cls.add_constructor([param('ns3::Object const &', 'o')],
visibility='protected')
## object.h (module 'core'): void ns3::Object::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## object.h (module 'core'): void ns3::Object::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectAggregateIterator_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')])
## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor]
cls.add_constructor([])
## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function]
cls.add_method('Next',
'ns3::Ptr< ns3::Object const >',
[])
return
def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3FdReader_Ns3Empty_Ns3DefaultDeleter__lt__ns3FdReader__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >::SimpleRefCount(ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::FdReader, ns3::empty, ns3::DefaultDeleter< ns3::FdReader > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3SystemThread_Ns3Empty_Ns3DefaultDeleter__lt__ns3SystemThread__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >::SimpleRefCount(ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::SystemThread, ns3::empty, ns3::DefaultDeleter< ns3::SystemThread > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SystemThread_methods(root_module, cls):
## system-thread.h (module 'core'): ns3::SystemThread::SystemThread(ns3::SystemThread const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SystemThread const &', 'arg0')])
## system-thread.h (module 'core'): ns3::SystemThread::SystemThread(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [constructor]
cls.add_constructor([param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## system-thread.h (module 'core'): static bool ns3::SystemThread::Equals(pthread_t id) [member function]
cls.add_method('Equals',
'bool',
[param('pthread_t', 'id')],
is_static=True)
## system-thread.h (module 'core'): void ns3::SystemThread::Join() [member function]
cls.add_method('Join',
'void',
[])
## system-thread.h (module 'core'): static pthread_t ns3::SystemThread::Self() [member function]
cls.add_method('Self',
'pthread_t',
[],
is_static=True)
## system-thread.h (module 'core'): void ns3::SystemThread::Start() [member function]
cls.add_method('Start',
'void',
[])
return
def register_Ns3Time_methods(root_module, cls):
cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right'))
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right'))
cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', 'right'))
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>=')
## nstime.h (module 'core'): ns3::Time::Time() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor]
cls.add_constructor([param('ns3::Time const &', 'o')])
## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor]
cls.add_constructor([param('double', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor]
cls.add_constructor([param('int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor]
cls.add_constructor([param('long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor]
cls.add_constructor([param('long long int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor]
cls.add_constructor([param('unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor]
cls.add_constructor([param('long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor]
cls.add_constructor([param('long long unsigned int', 'v')])
## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor]
cls.add_constructor([param('std::string const &', 's')])
## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor]
cls.add_constructor([param('ns3::int64x64_t const &', 'value')])
## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function]
cls.add_method('Compare',
'int',
[param('ns3::Time const &', 'o')],
is_const=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & from, ns3::Time::Unit timeUnit) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function]
cls.add_method('From',
'ns3::Time',
[param('ns3::int64x64_t const &', 'value')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit timeUnit) [member function]
cls.add_method('FromDouble',
'ns3::Time',
[param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function]
cls.add_method('FromInteger',
'ns3::Time',
[param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function]
cls.add_method('GetDouble',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function]
cls.add_method('GetFemtoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function]
cls.add_method('GetInteger',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function]
cls.add_method('GetMicroSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function]
cls.add_method('GetMilliSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function]
cls.add_method('GetNanoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function]
cls.add_method('GetPicoSeconds',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function]
cls.add_method('GetResolution',
'ns3::Time::Unit',
[],
is_static=True)
## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function]
cls.add_method('GetSeconds',
'double',
[],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function]
cls.add_method('GetTimeStep',
'int64_t',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function]
cls.add_method('IsNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function]
cls.add_method('IsPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function]
cls.add_method('IsStrictlyNegative',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function]
cls.add_method('IsStrictlyPositive',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function]
cls.add_method('IsZero',
'bool',
[],
is_const=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function]
cls.add_method('Max',
'ns3::Time',
[],
is_static=True)
## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function]
cls.add_method('Min',
'ns3::Time',
[],
is_static=True)
## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function]
cls.add_method('SetResolution',
'void',
[param('ns3::Time::Unit', 'resolution')],
is_static=True)
## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function]
cls.add_method('StaticInit',
'bool',
[],
is_static=True)
## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('To',
'ns3::int64x64_t',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('ToDouble',
'double',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function]
cls.add_method('ToInteger',
'int64_t',
[param('ns3::Time::Unit', 'timeUnit')],
is_const=True)
return
def register_Ns3TraceSourceAccessor_methods(root_module, cls):
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor]
cls.add_constructor([])
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Connect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('ConnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function]
cls.add_method('Disconnect',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function]
cls.add_method('DisconnectWithoutContext',
'bool',
[param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3Trailer_methods(root_module, cls):
cls.add_output_stream_operator()
## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor]
cls.add_constructor([])
## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Trailer const &', 'arg0')])
## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'end')],
is_pure_virtual=True, is_virtual=True)
## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeAccessor_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function]
cls.add_method('Get',
'bool',
[param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function]
cls.add_method('HasGetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function]
cls.add_method('HasSetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function]
cls.add_method('Set',
'bool',
[param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeChecker_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function]
cls.add_method('CreateValidValue',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::AttributeValue const &', 'value')],
is_const=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3CallbackChecker_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')])
return
def register_Ns3CallbackImplBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')])
## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3CallbackValue_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'base')])
## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function]
cls.add_method('Set',
'void',
[param('ns3::CallbackBase', 'base')])
return
def register_Ns3DataRateChecker_methods(root_module, cls):
## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker(ns3::DataRateChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRateChecker const &', 'arg0')])
return
def register_Ns3DataRateValue_methods(root_module, cls):
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRateValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRateValue const &', 'arg0')])
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRate const & value) [constructor]
cls.add_constructor([param('ns3::DataRate const &', 'value')])
## data-rate.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::DataRateValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## data-rate.h (module 'network'): bool ns3::DataRateValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## data-rate.h (module 'network'): ns3::DataRate ns3::DataRateValue::Get() const [member function]
cls.add_method('Get',
'ns3::DataRate',
[],
is_const=True)
## data-rate.h (module 'network'): std::string ns3::DataRateValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## data-rate.h (module 'network'): void ns3::DataRateValue::Set(ns3::DataRate const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::DataRate const &', 'value')])
return
def register_Ns3EmptyAttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, visibility='private', is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
visibility='private', is_virtual=True)
## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3EventImpl_methods(root_module, cls):
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventImpl const &', 'arg0')])
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor]
cls.add_constructor([])
## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function]
cls.add_method('Invoke',
'void',
[])
## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function]
cls.add_method('IsCancelled',
'bool',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function]
cls.add_method('Notify',
'void',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
return
def register_Ns3FdReader_methods(root_module, cls):
## unix-fd-reader.h (module 'core'): ns3::FdReader::FdReader(ns3::FdReader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FdReader const &', 'arg0')])
## unix-fd-reader.h (module 'core'): ns3::FdReader::FdReader() [constructor]
cls.add_constructor([])
## unix-fd-reader.h (module 'core'): void ns3::FdReader::Start(int fd, ns3::Callback<void, unsigned char*, long, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> readCallback) [member function]
cls.add_method('Start',
'void',
[param('int', 'fd'), param('ns3::Callback< void, unsigned char *, long, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'readCallback')])
## unix-fd-reader.h (module 'core'): void ns3::FdReader::Stop() [member function]
cls.add_method('Stop',
'void',
[])
## unix-fd-reader.h (module 'core'): ns3::FdReader::Data ns3::FdReader::DoRead() [member function]
cls.add_method('DoRead',
'ns3::FdReader::Data',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
return
def register_Ns3Ipv4AddressChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')])
return
def register_Ns3Ipv4AddressValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Address const &', 'value')])
return
def register_Ns3Ipv4MaskChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')])
return
def register_Ns3Ipv4MaskValue_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor]
cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')])
## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv4Mask',
[],
is_const=True)
## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv4Mask const &', 'value')])
return
def register_Ns3Ipv6AddressChecker_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')])
return
def register_Ns3Ipv6AddressValue_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Address const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv6Address',
[],
is_const=True)
## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv6Address const &', 'value')])
return
def register_Ns3Ipv6PrefixChecker_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')])
return
def register_Ns3Ipv6PrefixValue_methods(root_module, cls):
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')])
## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ipv6Prefix',
[],
is_const=True)
## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ipv6Prefix const &', 'value')])
return
def register_Ns3Mac48AddressChecker_methods(root_module, cls):
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')])
return
def register_Ns3Mac48AddressValue_methods(root_module, cls):
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor]
cls.add_constructor([param('ns3::Mac48Address const &', 'value')])
## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Mac48Address',
[],
is_const=True)
## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Mac48Address const &', 'value')])
return
def register_Ns3NetDevice_methods(root_module, cls):
## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor]
cls.add_constructor([])
## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDevice const &', 'arg0')])
## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3NixVector_methods(root_module, cls):
cls.add_output_stream_operator()
## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor]
cls.add_constructor([])
## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor]
cls.add_constructor([param('ns3::NixVector const &', 'o')])
## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function]
cls.add_method('AddNeighborIndex',
'void',
[param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function]
cls.add_method('BitCount',
'uint32_t',
[param('uint32_t', 'numberOfNeighbors')],
is_const=True)
## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint32_t const *', 'buffer'), param('uint32_t', 'size')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function]
cls.add_method('ExtractNeighborIndex',
'uint32_t',
[param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function]
cls.add_method('GetRemainingBits',
'uint32_t',
[])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3Node_methods(root_module, cls):
## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Node const &', 'arg0')])
## node.h (module 'network'): ns3::Node::Node() [constructor]
cls.add_constructor([])
## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor]
cls.add_constructor([param('uint32_t', 'systemId')])
## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function]
cls.add_method('AddApplication',
'uint32_t',
[param('ns3::Ptr< ns3::Application >', 'application')])
## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('AddDevice',
'uint32_t',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function]
cls.add_method('ChecksumEnabled',
'bool',
[],
is_static=True)
## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function]
cls.add_method('GetApplication',
'ns3::Ptr< ns3::Application >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function]
cls.add_method('GetNApplications',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('RegisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function]
cls.add_method('RegisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')])
## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('UnregisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function]
cls.add_method('UnregisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')])
## node.h (module 'network'): void ns3::Node::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## node.h (module 'network'): void ns3::Node::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectFactoryChecker_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')])
return
def register_Ns3ObjectFactoryValue_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'value')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function]
cls.add_method('Get',
'ns3::ObjectFactory',
[],
is_const=True)
## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::ObjectFactory const &', 'value')])
return
def register_Ns3Packet_methods(root_module, cls):
cls.add_output_stream_operator()
## packet.h (module 'network'): ns3::Packet::Packet() [constructor]
cls.add_constructor([])
## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor]
cls.add_constructor([param('ns3::Packet const &', 'o')])
## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor]
cls.add_constructor([param('uint32_t', 'size')])
## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor]
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')])
## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor]
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function]
cls.add_method('AddByteTag',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header')])
## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function]
cls.add_method('AddPacketTag',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer')])
## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function]
cls.add_method('EnablePrinting',
'void',
[],
is_static=True)
## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function]
cls.add_method('FindFirstMatchingByteTag',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function]
cls.add_method('GetByteTagIterator',
'ns3::ByteTagIterator',
[],
is_const=True)
## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function]
cls.add_method('GetNixVector',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function]
cls.add_method('GetPacketTagIterator',
'ns3::PacketTagIterator',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function]
cls.add_method('PeekData',
'uint8_t const *',
[],
deprecated=True, is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function]
cls.add_method('PeekHeader',
'uint32_t',
[param('ns3::Header &', 'header')],
is_const=True)
## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function]
cls.add_method('PeekPacketTag',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function]
cls.add_method('PeekTrailer',
'uint32_t',
[param('ns3::Trailer &', 'trailer')])
## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function]
cls.add_method('PrintByteTags',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function]
cls.add_method('PrintPacketTags',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function]
cls.add_method('RemoveAllByteTags',
'void',
[])
## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function]
cls.add_method('RemoveAllPacketTags',
'void',
[])
## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'size')])
## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function]
cls.add_method('RemoveHeader',
'uint32_t',
[param('ns3::Header &', 'header')])
## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function]
cls.add_method('RemovePacketTag',
'bool',
[param('ns3::Tag &', 'tag')])
## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function]
cls.add_method('RemoveTrailer',
'uint32_t',
[param('ns3::Trailer &', 'trailer')])
## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function]
cls.add_method('ReplacePacketTag',
'bool',
[param('ns3::Tag &', 'tag')])
## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> arg0) [member function]
cls.add_method('SetNixVector',
'void',
[param('ns3::Ptr< ns3::NixVector >', 'arg0')])
return
def register_Ns3TapBridge_methods(root_module, cls):
## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge::TapBridge(ns3::TapBridge const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TapBridge const &', 'arg0')])
## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge::TapBridge() [constructor]
cls.add_constructor([])
## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): ns3::Address ns3::TapBridge::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridge::GetBridgedNetDevice() [member function]
cls.add_method('GetBridgedNetDevice',
'ns3::Ptr< ns3::NetDevice >',
[])
## tap-bridge.h (module 'tap-bridge'): ns3::Address ns3::TapBridge::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): ns3::Ptr<ns3::Channel> ns3::TapBridge::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): uint32_t ns3::TapBridge::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge::Mode ns3::TapBridge::GetMode() [member function]
cls.add_method('GetMode',
'ns3::TapBridge::Mode',
[])
## tap-bridge.h (module 'tap-bridge'): uint16_t ns3::TapBridge::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): ns3::Address ns3::TapBridge::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): ns3::Address ns3::TapBridge::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): ns3::Ptr<ns3::Node> ns3::TapBridge::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): static ns3::TypeId ns3::TapBridge::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetBridgedNetDevice(ns3::Ptr<ns3::NetDevice> bridgedDevice) [member function]
cls.add_method('SetBridgedNetDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'bridgedDevice')])
## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetMode(ns3::TapBridge::Mode mode) [member function]
cls.add_method('SetMode',
'void',
[param('ns3::TapBridge::Mode', 'mode')])
## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::Start(ns3::Time tStart) [member function]
cls.add_method('Start',
'void',
[param('ns3::Time', 'tStart')])
## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::Stop(ns3::Time tStop) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time', 'tStop')])
## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::DiscardFromBridgedDevice(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Address const & src) [member function]
cls.add_method('DiscardFromBridgedDevice',
'bool',
[param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'src')],
visibility='protected')
## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::ReceiveFromBridgedDevice(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Address const & src, ns3::Address const & dst, ns3::NetDevice::PacketType packetType) [member function]
cls.add_method('ReceiveFromBridgedDevice',
'bool',
[param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'src'), param('ns3::Address const &', 'dst'), param('ns3::NetDevice::PacketType', 'packetType')],
visibility='protected')
return
def register_Ns3TapBridgeFdReader_methods(root_module, cls):
## tap-bridge.h (module 'tap-bridge'): ns3::TapBridgeFdReader::TapBridgeFdReader() [constructor]
cls.add_constructor([])
## tap-bridge.h (module 'tap-bridge'): ns3::TapBridgeFdReader::TapBridgeFdReader(ns3::TapBridgeFdReader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TapBridgeFdReader const &', 'arg0')])
## tap-bridge.h (module 'tap-bridge'): ns3::FdReader::Data ns3::TapBridgeFdReader::DoRead() [member function]
cls.add_method('DoRead',
'ns3::FdReader::Data',
[],
visibility='private', is_virtual=True)
return
def register_Ns3TimeValue_methods(root_module, cls):
## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeValue const &', 'arg0')])
## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor]
cls.add_constructor([param('ns3::Time const &', 'value')])
## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function]
cls.add_method('Get',
'ns3::Time',
[],
is_const=True)
## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Time const &', 'value')])
return
def register_Ns3TypeIdChecker_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')])
return
def register_Ns3TypeIdValue_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor]
cls.add_constructor([param('ns3::TypeId const &', 'value')])
## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function]
cls.add_method('Get',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::TypeId const &', 'value')])
return
def register_Ns3AddressChecker_methods(root_module, cls):
## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')])
return
def register_Ns3AddressValue_methods(root_module, cls):
## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AddressValue const &', 'arg0')])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor]
cls.add_constructor([param('ns3::Address const &', 'value')])
## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Address',
[],
is_const=True)
## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Address const &', 'value')])
return
def register_Ns3HashImplementation_methods(root_module, cls):
## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')])
## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor]
cls.add_constructor([])
## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_pure_virtual=True, is_virtual=True)
## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function]
cls.add_method('clear',
'void',
[],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3HashFunctionFnv1a_methods(root_module, cls):
## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')])
## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor]
cls.add_constructor([])
## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_Ns3HashFunctionHash32_methods(root_module, cls):
## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor]
cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')])
## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_Ns3HashFunctionHash64_methods(root_module, cls):
## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')])
## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor]
cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')])
## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_Ns3HashFunctionMurmur3_methods(root_module, cls):
## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')])
## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor]
cls.add_constructor([])
## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')],
is_virtual=True)
## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function]
cls.add_method('clear',
'void',
[],
is_virtual=True)
return
def register_functions(root_module):
module = root_module
register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module)
register_functions_ns3_Hash(module.get_submodule('Hash'), root_module)
return
def register_functions_ns3_FatalImpl(module, root_module):
return
def register_functions_ns3_Hash(module, root_module):
register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module)
return
def register_functions_ns3_Hash_Function(module, root_module):
return
def main():
out = FileCodeSink(sys.stdout)
root_module = module_init()
register_types(root_module)
register_methods(root_module)
register_functions(root_module)
root_module.generate(out)
if __name__ == '__main__':
main()
|
HuimingCheng/AutoGrading | refs/heads/master | learning/web_Haotian/venv/Lib/encodings/raw_unicode_escape.py | 852 | """ Python 'raw-unicode-escape' Codec
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""
import codecs
### Codec APIs
class Codec(codecs.Codec):
# Note: Binding these as C functions will result in the class not
# converting them to methods. This is intended.
encode = codecs.raw_unicode_escape_encode
decode = codecs.raw_unicode_escape_decode
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.raw_unicode_escape_encode(input, self.errors)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.raw_unicode_escape_decode(input, self.errors)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='raw-unicode-escape',
encode=Codec.encode,
decode=Codec.decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamwriter=StreamWriter,
streamreader=StreamReader,
)
|
MJJoyce/apachestuff | refs/heads/master | name_to_committer_id.py | 2 | #!/usr/bin/env python
# encoding: utf-8
# 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 re
import urllib2
import sys
import unicodedata
import string
people_url = "http://people.apache.org/committer-index.html"
name = unicode(sys.argv[1], "utf-8")
name_toks = name.split(" ")
namePattern = ""
selectMentorIdPattern = ".*id\=\'([a-z0-9]+)\'.*"
selectMentorIdCompiled = re.compile(selectMentorIdPattern)
# source:
# http://stackoverflow.com/questions/20729827/compare-2-strings-without-considering-accents-in-python
def remove_accents(data):
return ''.join(x for x in unicodedata.normalize('NFKD', data) if x in string.ascii_letters).lower()
if " " not in name:
namePattern = ".*"+remove_accents(name.lower())+"\<.*"
else:
name_toks = re.split('\s+|\-',name)
namePattern = ".*"
for tok in name_toks:
if (len(tok) == 1 or len(tok) == 2 and "." in tok) and len(name_toks) == 3:
namePattern = namePattern+"("+remove_accents(tok.lower())+")*\s*[A-Za-z.\-]*\s*"
else:
# total hack
replaced=False
if tok == "Dave":
tok = u"(David|Dave)"
replaced=True
elif tok == "Matt":
tok = u"(Matthew|Matt)"
replaced=True
elif tok == "Tom":
tok = u"(Tom|Thomas)"
replaced=True
elif tok == "Henri":
tok = u"(Gomez|Henri)"
replaced=True
elif tok == "Gomez":
tok = u"(Henri|Gomez)"
replaced=True
elif tok == "Mike":
tok = u"(Mike|Michael)"
replaced=True
elif tok == "Fromm":
continue # skip due to Isabel still being listen under maiden name
elif tok == "O'Malley":
replaced=True # hack so this doesn't get accents removed
elif tok == "Pietro":
continue # skip due to not being included by his last name.
elif tok == "Tomaz":
tok = u"(Tomaž|Tomaz)"
replaced=True
elif tok == "Afkham":
tok = u"(Mohamed Afkham)"
replaced=True
if replaced:
namePattern = namePattern+tok.lower()+"\s*[A-Za-z.\-]*\s*"
else:
namePattern = namePattern+remove_accents(tok.lower())+"\s*[A-Za-z.\-]*\s*"
namePattern = namePattern + ".*\<"
namePatternCompiled = re.compile(namePattern)
prevLine = ""
theMatch=""
for line in urllib2.urlopen(people_url).readlines():
if namePatternCompiled.match(unicode(line.lower(), "utf-8")) and prevLine <> None and prevLine.find("<tr>") == -1:
mentorIdMatch = selectMentorIdCompiled.match(prevLine)
if mentorIdMatch:
theMatch = mentorIdMatch.group(1).strip().lower()
if "id='" in line:
prevLine = line.lower()
# take the last match
if theMatch <> None and theMatch.strip() <> "":
print theMatch.strip()
|
gcodetogit/depot_tools | refs/heads/master | third_party/coverage/annotate.py | 55 | """Source file annotation for Coverage."""
import os, re
from coverage.report import Reporter
class AnnotateReporter(Reporter):
"""Generate annotated source files showing line coverage.
This reporter creates annotated copies of the measured source files. Each
.py file is copied as a .py,cover file, with a left-hand margin annotating
each line::
> def h(x):
- if 0: #pragma: no cover
- pass
> if x == 1:
! a = 1
> else:
> a = 2
> h(2)
Executed lines use '>', lines not executed use '!', lines excluded from
consideration use '-'.
"""
def __init__(self, coverage, config):
super(AnnotateReporter, self).__init__(coverage, config)
self.directory = None
blank_re = re.compile(r"\s*(#|$)")
else_re = re.compile(r"\s*else\s*:\s*(#|$)")
def report(self, morfs, directory=None):
"""Run the report.
See `coverage.report()` for arguments.
"""
self.report_files(self.annotate_file, morfs, directory)
def annotate_file(self, cu, analysis):
"""Annotate a single file.
`cu` is the CodeUnit for the file to annotate.
"""
if not cu.relative:
return
filename = cu.filename
source = cu.source_file()
if self.directory:
dest_file = os.path.join(self.directory, cu.flat_rootname())
dest_file += ".py,cover"
else:
dest_file = filename + ",cover"
dest = open(dest_file, 'w')
statements = analysis.statements
missing = analysis.missing
excluded = analysis.excluded
lineno = 0
i = 0
j = 0
covered = True
while True:
line = source.readline()
if line == '':
break
lineno += 1
while i < len(statements) and statements[i] < lineno:
i += 1
while j < len(missing) and missing[j] < lineno:
j += 1
if i < len(statements) and statements[i] == lineno:
covered = j >= len(missing) or missing[j] > lineno
if self.blank_re.match(line):
dest.write(' ')
elif self.else_re.match(line):
# Special logic for lines containing only 'else:'.
if i >= len(statements) and j >= len(missing):
dest.write('! ')
elif i >= len(statements) or j >= len(missing):
dest.write('> ')
elif statements[i] == missing[j]:
dest.write('! ')
else:
dest.write('> ')
elif lineno in excluded:
dest.write('- ')
elif covered:
dest.write('> ')
else:
dest.write('! ')
dest.write(line)
source.close()
dest.close()
|
sephiroth6/nodeshot | refs/heads/master | nodeshot/core/metrics/views.py | 3 | import json
from django.shortcuts import get_object_or_404
from rest_framework.decorators import api_view
from rest_framework.response import Response
from influxdb.client import InfluxDBClientError
from .models import Metric
@api_view(('GET', 'POST'))
def metric_details(request, pk, format=None):
"""
Get or write metric values
"""
metric = get_object_or_404(Metric, pk=pk)
# get
if request.method == 'GET':
try:
results = metric.select(q=request.QUERY_PARAMS.get('q', metric.query))
except InfluxDBClientError as e:
return Response(json.loads(e.content), status=e.code)
return Response(results)
# post
else:
if not request.DATA:
return Response({'detail': 'expected values in POST data or JSON payload'},
status=400)
data = request.DATA.copy()
# try converting strings to floats when sending form-data
if request.content_type != 'application/json':
for key, value in data.items():
try:
data[key] = float(value) if '.' in value else int(value)
except ValueError:
pass
# write
metric.write(data)
return Response({'detail': 'ok'})
|
Effective-Quadratures/Effective-Quadratures | refs/heads/master | tests/test_subspaces.py | 1 | from unittest import TestCase
import unittest
from equadratures import *
from equadratures.scalers import scaler_minmax
import numpy as np
import scipy.stats as st
import os
def data():
Y = np.asarray([[0.214794386299531],
[0.0304864358995189],
[0.181108826199520],
[0.0364174877995254],
[-0.388114785300473],
[0.0438257486995184],
[0.148544215099520],
[-0.135653950600471],
[-0.0672785594004779],
[0.151946461699524],
[-0.341502000900476],
[0.141843179199526],
[0.0806830478995266],
[-0.197027939800478],
[-0.000576330000470193],
[0.0840840311995237],
[0.125764284799530],
[-0.237702105900482],
[0.0781943433995309],
[0.131515575999529],
[0.0177330054995224],
[0.109803669599529],
[-0.208028892900472],
[0.141115927999522],
[-0.00914745520047688],
[-0.0461956932004739],
[-0.210949033300480],
[-0.257511610600474],
[0.183193029499520],
[0.0545309729995296],
[-0.120057568400469],
[0.227336520799526],
[0.204247055499522],
[-0.0616932087004756],
[0.161420647999520],
[-0.0180615302004696],
[-0.0118099877004738],
[0.0748339604995323],
[0.0745070069995251],
[-0.185076108700471],
[0.0849124082995303],
[-0.0199544130004767],
[0.153037546299529],
[0.0367098921995250],
[-0.242223654600480],
[0.0274205508995209],
[0.134563126199524],
[-0.195156222900479],
[0.0638141560995251],
[-0.128088542300475],
[0.109499632199530],
[0.0782561047995216],
[0.110476785699532],
[0.0241224618995233],
[-0.449582174200472],
[-0.0157697312004785],
[-0.0209440301004804],
[0.168155087199523],
[-0.168625143900471],
[-0.0414124356004777],
[0.233078659799531],
[-0.000759223900473671],
[-0.0701863196004808],
[0.152463798999520],
[0.0726099892995222],
[0.0411974184995216],
[-0.222654263500473],
[0.204070374999532],
[-0.274498326100471],
[0.0708688562995263],
[0.138623533999521],
[-0.189396612900481],
[0.0540059301995228],
[0.0991160263995283],
[-0.135643495900482],
[0.233049322699529],
[-0.154967996400472],
[-0.631046417900478],
[-0.0779334462004755],
[0.153380938199518],
[-0.155231895300474],
[0.0736116841995198],
[-0.00645852450047357],
[0.141611343699523],
[0.0295416722995299],
[-0.321736905300469],
[-0.217625299100476],
[-0.0189160950004776],
[0.0194677688995313],
[-0.313642062700481],
[0.134496847299531],
[0.0573074155995244],
[-0.209072587400470],
[0.169205586999524],
[0.119481082599521],
[0.194061367399527],
[0.0626582642995288],
[-0.458475699300479],
[-0.472494397800475],
[0.171130899099524],
[0.160384905899519],
[-0.0143868728004719],
[-0.324650780400475],
[0.0772631575995320],
[-0.550226859300480],
[-0.0626761048004738],
[0.108108206499523],
[0.140159608099523],
[0.108501425699529],
[0.0999191759995313],
[0.103752496899531],
[0.103608776599529],
[0.168472986599525],
[-0.00998671270048135],
[-0.125462812600475],
[-0.00117008070047575],
[-0.0812177097004678],
[-0.0986191162004815],
[0.0213149108995196],
[0.0631004149995249],
[-0.583006764400480],
[0.0945855181995228],
[-0.0879035083004709],
[-0.793577578100468],
[-0.542894171900471],
[0.189553869999529],
[0.180521780899525],
[-0.00424665820047210],
[-0.125371998100476],
[0.0200500877995182],
[-0.228110993700469],
[0.0737166533995293],
[0.0158440191995197],
[0.156549758699526],
[0.0696423894995206],
[0.132558027199522],
[0.0775897087995219],
[-0.124140992400470],
[0.220779741199522],
[0.135866635099532],
[-0.174960463000474],
[-0.529304618300472],
[0.0656745672995243],
[0.0805166130995190],
[-0.00443530900047051],
[0.176677183199530],
[0.104310766599525],
[0.0980333244995251],
[0.000191290399527588],
[0.107555870499525],
[-0.196662744600474],
[-0.162197365900468],
[0.0834747983995214],
[0.0851487841995322],
[0.111727981799518],
[0.174598671999519],
[0.117171712499527],
[0.0731327892995211],
[0.0696163890995223],
[0.179499686299522],
[-0.243074504400468],
[0.0839834533995258],
[0.0157608777995222],
[0.0108822281995202],
[0.114337857299532],
[0.123824851599522],
[-0.159377405900472],
[0.0776320028995201],
[0.0653742019995320],
[-0.00210355500047399],
[0.0912588671995280],
[0.180848868299520],
[0.150250253099529],
[0.175843499999530],
[-0.320397018500472],
[0.0822831741995316],
[0.147099239499525],
[0.0612997872995322],
[-0.359024781000471],
[0.0542501979995222],
[0.116691579699520],
[0.164019259799531],
[0.0297407982995281],
[0.0192861675995317],
[0.139297769699525],
[0.0882705996995270],
[0.0950385867995323],
[-0.107752629300478],
[0.0473162408995194],
[-0.230748620800469],
[0.196552499599520],
[-0.119922477800472],
[0.0212145083995239],
[-0.236157846000481],
[0.0848690502995311],
[0.0904056784995220],
[0.0603606912995218],
[0.0119565401995203],
[-0.0113516351004677],
[0.0328624994995295],
[-0.00430806700047981],
[0.163563947999521],
[0.139620018499528],
[0.113107005399527],
[0.120860772199521],
[0.0808816400995198],
[0.0604271935995229],
[0.205514615299521],
[0.0479690408995310],
[-0.321254294600479],
[0.0632042959995260],
[0.120114433099531],
[0.0748610498995248],
[0.109594417499522],
[0.160020060899527],
[0.0245053195995268],
[0.0127019119995282],
[-0.277159179600474],
[-0.0118930425004748],
[0.0905430362995219],
[0.112444446399522],
[0.176573024599520],
[-0.293329093400473],
[-0.0594143153004723],
[-0.120330663800473],
[0.0153887310995202],
[-0.259821891800470],
[-0.100099102600481],
[0.123078455599526],
[0.0875035776995219],
[-0.0161959447004705],
[0.181561658799524],
[0.0683309792995317],
[-0.175586930500472],
[0.0293433842995228],
[0.0818931746995304],
[0.258866349699531],
[0.0324536610995239],
[0.0792430783995286],
[-0.0299509270004705],
[0.0647850729995270],
[-0.0914756371004728],
[-0.220374963100468],
[-0.351253467000475],
[0.133310589399528],
[0.0945419518995294],
[0.162259478499522],
[-0.0485002696004813],
[0.0202396279995298],
[0.151078609299532],
[-0.0650836562004713],
[0.0975682618995251],
[0.184756516799524],
[0.0955608516995312],
[-0.345798543900472],
[0.130781813299521],
[0.0711370970995233],
[0.0286061356995191],
[-0.134320615900478],
[0.0666438685995274],
[-0.148287702200477],
[0.0623764749995246],
[0.00917974739952854],
[0.153732945399526],
[-0.0767784306004700],
[0.156712380699531],
[0.0842286593995283],
[0.0801534656995244],
[-0.175097697100469],
[0.0300963610995240],
[0.0667589602995236],
[0.0638937947995260],
[0.128762529599527],
[0.122514236899519],
[-0.459801502600470],
[-0.0848779269004751],
[0.132455226399529],
[-0.115939519200481],
[0.0292607909995297],
[0.0382036034995252],
[0.0921355731995277],
[0.157910732199525],
[0.0961198541995287],
[-0.407369653000472],
[-0.0103334867004747],
[0.127438813299520],
[0.00818742489953195],
[-0.187620622700479],
[-0.343500936000481],
[-0.319586542700478],
[-0.0480417755004794],
[0.171385428799525],
[-0.0228790512004764],
[0.146299715599525],
[0.000214571699530097],
[-0.169738899100480],
[0.0906952828995316],
[-0.314823059400482],
[0.0690663116995296],
[0.138684729099523],
[0.0289694859995251],
[0.0985871361995265],
[-0.0144951174004717],
[0.0840272010995307],
[0.0608369824995236],
[-0.238280947000476],
[0.133133071799520],
[0.0257260253995213],
[0.0471222716995214],
[0.0483109278995215],
[-0.0478133367004716],
[0.105381771699527],
[0.00838750639952934],
[0.0177622516995228],
[-0.00616568070047663],
[0.0557430874995220],
[0.0898689151995313],
[0.0898277670995213],
[0.00456935089952992],
[-0.187953259700478],
[-0.0780650933004807],
[0.0710368142995321],
[-0.326853319500472],
[-0.0650983021004805],
[0.161513439599531],
[-0.460204786500469],
[0.233121549199524],
[0.0708891591995240],
[0.0491630639995293],
[0.141085203599530],
[0.0507988267995216],
[-0.257742885300473],
[-0.159807573400471],
[0.162493103899521],
[-0.0599515949004683],
[0.140789858899524],
[0.0818634856995288],
[0.178364036099524],
[0.180796084299530],
[0.109725847399531],
[0.129581550999532],
[0.127677284399525],
[-0.349510104900475],
[-0.122046208700468],
[-0.0358421192004812],
[0.0345309835995238],
[0.142012091899531],
[0.120857408899525],
[-0.167817914200469],
[0.0133321852995323],
[0.0176090675995226],
[-0.129430604100477],
[0.0292773081995250],
[0.169368050399527],
[0.0305181414995275],
[-0.0638441750004688],
[-0.113179601500477],
[0.166798293899532],
[0.0162736180995182],
[0.0527946769995253],
[0.0947584716995209],
[0.0311304306995197],
[0.0839449812995241],
[-0.128216936200474],
[0.0318150658995222],
[0.0139013393995242],
[-0.0126105156004712],
[0.154178962999524],
[0.0549426464995264],
[0.157239916299531],
[0.114192288399522],
[-0.0797570352004726],
[0.0192872869995284],
[-0.00926635240047347],
[0.123313871699523],
[0.199464715799522],
[0.109633813999523],
[0.0798440121995299],
[0.163664476699523],
[-0.0323856638004685],
[0.228455003899526],
[0.201880290699521],
[0.0487547710995244],
[-0.360505695900471],
[-0.0698146163004765],
[0.117355223999525],
[-0.111042011800478],
[0.0682092957995195],
[0.0150243247995263],
[0.208994546099532],
[0.113677161499524],
[0.196637127499528],
[0.158814903099525],
[-0.661821914900472],
[0.150469333399528],
[0.138941686699525],
[0.0665537991995251],
[0.0893819390995247],
[0.0884417451995319],
[0.0137149108995231],
[0.213352602999521],
[-0.101525370400481],
[0.0530821395995247],
[-0.176521198600469],
[-0.277691602300479],
[0.192398342499530],
[-0.0440776337004678],
[0.180134114299520],
[0.127150805699529],
[-0.408117371100474],
[0.163452714599529],
[0.129875337399525],
[-0.154658492700477],
[0.137662739999527],
[0.0801360601995214],
[-0.0405032024004726],
[-0.641784071900474],
[-0.0619887244004786],
[-0.429366463400470],
[0.0321311068995271],
[0.0350706434995232],
[0.0145265152995222],
[0.0197122699995305],
[-0.168454993700479],
[0.138859359399518],
[-0.475443459300479],
[0.110587096099522],
[-0.344534334300477],
[0.165150308599522],
[0.0329606993995242],
[-0.469759912200473],
[0.114620658399531],
[0.0290598181995279],
[-0.171348968100475],
[0.188396895999531],
[-0.0896583549004788],
[0.000743012399524901],
[-0.00328755900046929],
[0.108288636399521],
[0.209561755999530],
[0.0301214671995211],
[-0.450993753500470],
[-0.0258869862004758],
[-0.0199979226004814],
[0.119549109799522],
[0.0247774857995182],
[-0.0905169224004681],
[0.0460369061995323],
[0.212384665199522],
[-0.328844503800468],
[0.0898977736995192],
[0.0271398930995304],
[0.229546684299521],
[-0.119681875200470],
[0.0588759322995287],
[-0.226316561100475],
[-0.0777017435004694],
[-0.0163957016004730],
[0.112230149099531],
[0.0484490733995244],
[-0.278726787400473],
[0.0570800295995184],
[0.0319428944995224],
[0.0647721007995301],
[-0.0196911934004760],
[0.0860737926995228],
[0.0250292890995212],
[-0.0398410190004768],
[0.000616646799528553],
[0.190895887699526],
[0.141418897999529],
[0.141689574599525],
[-0.163957612200477],
[0.218269934199526],
[0.0779105449995257],
[0.112958750299526],
[-0.217436090200479],
[-0.0221392657004742],
[-0.119405763700470],
[-0.0750915142004800],
[-0.268576392400476],
[0.177774447099523],
[0.148076016999525],
[0.173641486699523],
[-0.245689732200475],
[-0.347956204000468],
[0.0891225799995254],
[0.0527641896995306],
[0.155183887999527],
[-0.335188775600471],
[0.0506065342995186],
[0.214425515599530],
[0.0480266013995276],
[0.198452532999525],
[-0.101006102500477],
[-0.00527502340047192],
[0.0126590006995286],
[-0.136667151000481],
[0.0251241673995253],
[0.168276310599524],
[-0.469844888900468],
[-0.0621168316004770],
[0.0821124914995295],
[0.143613941499524],
[0.0328147569995281],
[0.0211372392995202],
[-0.0479252427004724],
[-0.243150005300478],
[0.152589977999526],
[0.0100695815995238],
[0.145968968199526],
[-0.0293733570004804],
[0.180251259399526],
[0.123284955899521],
[0.0748001880995304],
[0.258317554099520],
[-0.277403643500477],
[0.0503778183995252],
[0.163231288699521],
[-0.106680020900470],
[0.116783201399528],
[0.0778877776995302],
[-0.463969193700478],
[-0.376284701600468],
[0.0809322244995201],
[-0.404836217200469],
[0.150206254899530],
[0.182002918699524],
[0.107993837699524],
[-0.108125807000476],
[0.148171155599528],
[-0.0332993399004806],
[0.190952886499531],
[0.0258692020995284],
[0.103455538899524],
[0.0357476143995257],
[0.0103473016995252],
[0.00511007619952864],
[0.157947827599529],
[0.0430639671995294],
[-0.170492062200481],
[0.114268020399521],
[0.113847543899524],
[0.0775385946995186],
[-0.492880865700471],
[0.123420013299523],
[-0.358916839900473],
[0.173556227899525]])
X = np.asarray( [ [-0.996512,0.23415088,-0.14674416,-0.895788,-0.09476392,-0.28386376,0.25137264,-0.9609556,-0.4560592,-0.1981624,-0.07014196,-0.07142384,0.8078256,-0.8507328,0.7462676,-0.13834682,-0.289386,0.0671634,0.02889124,0.4424618,0.37987332,-0.35240744,-0.9130328,0.8085,-0.2665888],
[-0.9856896,-0.21795832,0.20988064,0.73222936,-0.8060976,0.4400208,0.34943584,-0.8513628,-0.001159749,0.5693064,0.7103376,0.4054248,-0.8526212,0.12977268,0.30150504,-0.223785,-0.7864298,0.917624,0.948186,0.390635,-0.6093724,0.8588504,-0.90812,-0.5793908,0.70259168],
[-0.9855984,0.62600336,-0.54664944,0.6003696,0.990116,0.6344212,-0.4753192,-0.5356344,0.09399352,-0.684366,-0.6098016,-0.7199676,0.404286,-0.4775376,0.19799236,-0.7488376,-0.8013194,-0.2450134,0.6726062,-0.5649798,-0.35617172,-0.7538856,0.37695744,0.36690616,0.53696208],
[-0.9814072,0.14507952,0.28050552,-0.029315704,-0.65606984,0.8590864,-0.813006,-0.607958,-0.5501308,-0.1782532,-0.30588856,-0.8998244,0.33920588,-0.9313064,-0.6357976,-0.528679,-0.402181,0.9692762,-0.2242034,0.8688206,0.6652152,-0.8151256,-0.53410408,0.19213904,0.14906304],
[-0.9724324,0.70213456,0.56241488,-0.56090712,-0.893496,0.9056932,-0.13313976,0.9194272,0.7803088,0.38787932,-0.04775252,0.5737292,0.798088,0.877684,-0.6682644,0.6502342,-0.08462352,-0.2454344,0.03860824,0.6449504,0.17894384,-0.35194864,0.54221384,0.77178008,-0.6609508],
[-0.9693876,0.010329848,0.4125092,-0.57442824,-0.8435008,-0.31974932,-0.9238444,0.466746,0.7964096,-0.5864708,0.7883776,-0.9082008,0.4273996,-0.9362596,0.490654,0.9744292,0.981304,0.6935004,-0.03956012,0.992213,0.780768,-0.22275976,0.18815192,0.54665648,-0.49263056],
[-0.9693004,-0.32126864,0.24864104,-0.6012936,-0.22005136,0.4383412,0.500204,-0.5947536,0.21823688,-0.9912284,0.4282628,-0.7755148,-0.08233884,0.03339988,-0.012785244,-0.13142306,-0.6054472,-0.5450824,-0.6056678,0.22568,-0.601578,0.24832864,-0.73634416,-0.8934992,0.17701456],
[-0.9662968,-0.7841776,0.875692,-0.78609488,-0.47889312,0.5048696,-0.04752156,-0.33773364,0.8545948,0.37397896,-0.3518806,-0.4683452,0.5304932,-0.08187024,0.1451292,-0.16019302,-0.0465887,-0.851419,-0.573074,0.6770834,-0.416418,0.4297292,0.45807464,0.71752408,0.8346112],
[-0.9627072,0.37914112,-0.32500656,0.31868504,0.35824336,-0.5027592,-0.9684952,0.5993732,0.33926984,-0.1984186,0.24320112,-0.7385096,0.8844964,-0.38992004,0.7657308,0.3085076,-0.807951,0.3364566,-0.16524062,-0.7284952,0.689264,-0.64990856,0.31770144,0.8821128,-0.69237176],
[-0.959288,0.9805368,0.8938064,-0.50103112,0.5545408,0.7436556,-0.7554808,-0.9421952,0.32072484,-0.18633052,-0.8834988,0.5184172,0.29727708,-0.5181392,0.23239216,0.16195482,-0.9718192,0.5812698,-0.11094616,0.7166808,-0.6337444,0.9591592,-0.23021984,-0.10877296,-0.33924056],
[-0.959012,-0.34011616,-0.52650352,0.2134364,-0.56393176,0.5024224,-0.03612478,0.4565192,0.27131596,0.95199,0.6891252,-0.4595112,0.1519522,-0.30010948,0.8004288,0.1039358,-0.46724,-0.7270498,0.4948728,0.9236574,0.9328648,-0.48006632,0.7017384,0.12834544,0.72855288],
[-0.9535576,-0.3201864,0.44319424,-0.69630072,0.17660368,0.5895712,0.4348756,-0.981452,0.7741868,-0.783084,0.21470548,-0.29760992,-0.568004,0.551064,-0.5693192,-0.4248052,-0.4939174,-0.58251,-0.4861614,-0.7843754,0.031181216,-0.9306152,0.58157376,0.58495384,0.75431584],
[-0.9531312,0.22482976,-0.59523624,-0.27857968,-0.41356984,0.5918832,0.515652,0.823666,-0.18363216,-0.39645376,-0.7405596,-0.961192,0.4009604,0.1956954,-0.555444,-0.2597836,0.2973368,-0.8591738,0.09001564,0.15858912,-0.34748092,0.5686796,0.14130696,0.8928032,0.65167264],
[-0.9418464,-0.980964,0.62025904,-0.25291768,0.13050208,0.32672992,0.4974544,-0.7846288,0.5158364,0.9131612,-0.4608488,-0.20073564,0.5588864,-0.831102,0.06427308,-0.4877024,0.580089,0.2937172,-0.256883,-0.4429882,-0.10875216,0.78090456,-0.79746672,-0.90822,-0.22477144],
[-0.9395052,-0.64637864,0.023998736,0.47291784,0.09134168,-0.0719098,0.24616036,0.7916112,-0.16203292,-0.4294036,-0.6770468,-0.963942,0.9952812,-0.01107918,0.662196,0.2769704,-0.2736684,0.3628424,-0.3944162,-0.3716688,-0.31675528,-0.8955152,0.8688128,-0.030312912,0.05291392],
[-0.9360108,-0.23165456,0.63948984,0.19036328,0.45828472,0.07800876,0.6874332,0.08810152,-0.5132528,0.32035228,-0.5342392,0.7212668,-0.6316092,-0.6633096,0.4486356,0.4673776,-0.6986322,0.6164082,-0.551999,0.8097938,-0.7599416,0.79594672,-0.8358272,0.49524408,-0.54783616],
[-0.9336548,-0.27175728,0.35847648,0.9259752,0.473218,-0.7717316,0.689996,-0.805308,0.6304356,-0.80834,0.23527844,-0.9116188,-0.30941476,-0.4689428,0.014552812,-0.0319078,0.6445212,0.265953,-0.2720864,-0.6549414,-0.9834436,0.76094856,-0.44675056,0.29770352,0.38320944],
[-0.9302324,-0.35324544,0.43949576,-0.13155928,-0.03465412,0.7558276,-0.19290372,0.37366728,0.4709632,0.8973476,0.8420712,-0.5662588,-0.4383176,-0.947856,0.8450744,-0.6530642,0.2759648,0.282217,0.5365504,-0.2083742,0.5317068,-0.3364812,0.39677312,0.919024,0.49028408],
[-0.917218,0.50269296,-0.44066096,0.74427096,-0.64214904,0.71475,-0.7205348,0.4954304,-0.9121752,0.760212,-0.96661,0.6809868,-0.4864452,-0.8009028,-0.6396236,-0.003776524,0.4304688,-0.7504552,0.5847504,0.6168372,0.9986056,-0.54277424,0.72328544,-0.056306488,0.9521024],
[-0.9159224,0.75213184,0.6460856,-0.005144225,0.02570024,-0.7529952,0.38809876,-0.08240028,-0.39875252,0.4250908,0.36533712,0.682244,-0.7486228,0.18984724,-0.15409776,-0.9618482,0.4368316,0.2054904,-0.9953414,0.789733,0.7396372,-0.60676024,0.8795184,0.38576064,0.826064],
[-0.9148264,0.9300416,-0.7527628,0.32260144,-0.8387272,0.14906964,0.5972864,0.25566972,0.326691,-0.06312632,0.6844692,0.785044,-0.620034,-0.30862724,-0.11768248,-0.2435208,0.6320694,0.295476,-0.30957,0.8791256,0.6789596,-0.8300624,-0.57154192,0.65708664,-0.016086152],
[-0.9053316,-0.8563736,-0.06141856,0.40743536,0.58845288,0.16049932,0.39294668,-0.36480468,-0.9352596,0.4544572,-0.3524702,0.471338,0.9324904,-0.9710044,-0.5327228,0.7876974,-0.420972,-0.9888578,-0.07083126,-0.1564783,-0.030657376,-0.27343112,0.078727744,-0.76768712,-0.72025512],
[-0.9037496,-0.16680728,-0.53319968,-0.778814,0.41653776,-0.1394382,-0.5605244,0.8401844,0.37558904,0.4575608,-0.22443384,-0.9563032,-0.37514716,-0.14655476,0.37794088,-0.6758684,0.3794128,0.9655962,-0.783607,0.310036,0.53341,0.9466584,0.31778104,-0.7465028,0.72573216],
[-0.9018348,-0.43316176,0.584134,0.74180144,0.66460888,0.3084276,-0.2204198,-0.13204044,-0.7864988,-0.4377908,-0.28115184,-0.8722732,-0.5104676,-0.6335056,0.21474212,0.113473,-0.1291366,-0.7999216,0.2106506,0.2042884,0.05542456,-0.11309648,0.63314704,-0.31797176,-0.062468296],
[-0.9015452,0.37070896,0.3666888,-0.61500408,-0.48343368,-0.17740476,0.9104408,0.7399056,-0.6431552,-0.2244256,0.9142972,0.8771584,0.20912988,0.7584196,0.37086116,-0.8910448,0.2708108,-0.4435768,-0.013913738,-0.5217744,0.21408312,-0.9737992,0.11871536,0.37106176,-0.5799044],
[-0.9001224,-0.968448,0.14402496,0.0428602,0.013695496,0.8697428,0.19709028,0.14302632,0.16337696,-0.6164664,0.5305772,0.23702064,-0.06921296,0.5168608,0.624776,0.022506,0.7703644,0.8875468,-0.6972326,0.2479094,-0.93311,0.53513464,-0.8955256,-0.9607032,-0.01660316],
[-0.8992952,-0.55980936,-0.55571616,-0.947648,-0.58631232,0.05063916,-0.525412,0.30697972,0.8548572,0.10293112,0.4667252,-0.38282372,0.9347596,-0.7113776,0.3402356,0.8575134,0.1165825,0.7699842,-0.3638912,-0.9090472,-0.945696,0.79700768,-0.73940896,-0.57071808,-0.035440792],
[-0.8974572,-0.9730152,-0.53535176,0.64472152,0.6042596,0.5364084,0.29612324,-0.2432144,0.12128712,0.19819564,0.23382072,-0.17518772,-0.5668252,0.90975,0.9465936,0.8472734,0.7153756,0.307751,-0.4736928,0.5664274,0.5812924,0.16308816,0.938092,-0.069742368,-0.51356224],
[-0.895132,-0.24543312,0.73587088,0.17994176,0.24961536,0.6767104,-0.4549564,-0.9882756,-0.799642,0.890702,0.27368084,-0.8279024,-0.14241176,-0.5300072,0.6716064,-0.9154214,-0.3403054,0.8420198,-0.00464537,0.14058298,0.5508532,0.131004,0.16030456,0.7342132,-0.50788872],
[-0.891258,0.41236192,0.8112736,-0.20984056,-0.20264576,0.07159916,-0.17152756,0.04794356,-0.031985696,0.8964204,-0.4000892,-0.2042698,-0.5274516,-0.805218,0.19189104,0.749394,-0.2587906,-0.690552,0.6148842,0.001650262,-0.3786496,0.68859944,0.96552,0.67846112,0.9071296],
[-0.8866168,-0.75197,0.6403952,0.08322424,-0.67890512,0.7674308,-0.5962048,-0.4541552,0.919942,0.4135012,-0.3801518,0.9518424,-0.964484,-0.668054,0.7229196,0.04217888,0.2465546,-0.9855674,0.870469,0.8494152,-0.4861288,0.65535064,0.66190656,0.51353184,0.19998512],
[-0.8790748,0.2566844,-0.41981504,-0.19070552,0.72370192,-0.9812316,-0.846546,-0.32667568,-0.5563456,-0.5032124,-0.5522076,0.031710108,0.1550996,0.8571848,0.05392448,-0.13679288,0.8453976,-0.6125172,0.467529,-0.78472,0.9450644,0.35151024,-0.27940032,-0.43488176,-0.09514032],
[-0.8787052,-0.27361608,-0.63809176,0.04537528,-0.86748,-0.39195832,-0.9055468,-0.419316,-0.4663868,-0.11336276,-0.57559,0.4113248,-0.16200892,0.18145312,0.6692272,-0.5866028,-0.2068638,0.918972,-0.611498,0.9725002,-0.31820956,-0.25421088,0.55011464,-0.4421088,0.32619584],
[-0.8784596,0.108482,0.054269864,-0.371832,-0.36363472,0.05735536,-0.778988,0.12655336,0.8603288,-0.4974216,-0.8160508,0.25572348,-0.39754496,-0.3254366,0.7084912,-0.12538396,0.19145786,0.7354752,-0.1207768,-0.6445758,-0.2552198,-0.67922632,-0.77539576,-0.71426936,0.42339992],
[-0.8737088,-0.17170712,0.4601224,0.8566176,-0.8091528,0.4524824,-0.8622212,-0.8055,-0.7424936,0.9390352,0.35213612,0.34435456,0.4371096,0.4719596,-0.31283984,0.6332634,-0.19664892,-0.3063964,0.2995158,0.5974414,0.7023008,0.69914424,0.6288268,-0.8672632,0.40706816],
[-0.8637284,-0.22113112,0.28998896,-0.558656,-0.73390648,0.235703,0.06848668,-0.7848904,0.8014012,0.80594,0.4023496,0.7133268,-0.34906048,-0.9697116,-0.5013212,-0.5270508,0.6266658,0.09964222,-0.8766892,-0.004976734,-0.7789704,-0.035235696,-0.63049776,0.6936644,0.16039408],
[-0.8621944,0.75741024,0.62237584,-0.69286864,0.50809888,0.500504,0.59606,0.19113584,-0.37166896,-0.19942584,0.6306704,0.18063712,-0.7451828,0.5183768,0.905916,-0.6708402,-0.1390702,0.3599326,0.7818118,-0.5671206,-0.598772,-0.18981512,-0.964364,0.1279348,-0.6073032],
[-0.8600648,0.02386592,-0.31024752,-0.46708392,0.09682696,-0.96583,-0.1586054,0.5687132,0.122196,-0.9404108,0.035257452,0.08609004,0.936404,-0.17998884,-0.8088696,-0.9608584,0.6485344,0.535321,0.8017906,-0.2461686,-0.13745648,0.11523192,0.3339272,0.68786152,0.49171176],
[-0.851954,0.1200168,-0.5486928,0.8295048,-0.048655184,-0.13025436,0.8880964,-0.3500266,-0.5765516,0.818714,-0.5538784,-0.530238,0.4052684,-0.9330904,0.4268416,0.2656738,-0.316833,-0.09538316,-0.6441646,0.9061462,-0.24658612,-0.021975336,0.9534392,-0.15473776,-0.08792968],
[-0.8482276,0.61120656,0.04004712,0.9965352,-0.49617096,-0.9777884,-0.22260424,0.29723996,-0.25925736,0.5784832,-0.020102252,-0.12868,0.16900952,0.441024,0.884688,-0.08922512,0.4660216,0.2683298,0.7740754,-0.706963,0.26995232,-0.8934544,0.71013832,0.42908808,0.16570448],
[-0.8466008,0.31631888,-0.32421936,0.13224416,0.6726476,-0.9202228,0.6822372,-0.8416796,0.23616316,-0.30941464,-0.029994336,0.08007832,0.26917068,-0.8134364,-0.7293612,-0.15140106,0.008901256,0.481465,0.4154788,-0.16585918,0.31341892,0.9575376,0.1716616,0.61889384,0.62454688],
[-0.84489,0.28944272,-0.410826,-0.013215792,0.8108976,0.8652352,0.635778,-0.269613,0.5007548,-0.27287576,0.12650332,0.24350788,0.9328804,-0.3713814,0.28044072,0.3419632,0.2046352,-0.07066934,-0.8747456,0.00898436,0.9786368,0.79141664,0.40890016,0.43475464,-0.34760904],
[-0.8442028,0.48649408,-0.903808,0.73109328,-0.77979664,-0.8395452,0.4272284,-0.17998356,0.08821692,-0.8733212,-0.35786632,-0.35716672,0.33621804,-0.4987052,0.5077916,0.16469678,-0.8633304,-0.873582,0.294298,0.1908731,0.389582,0.879404,0.9867368,0.057346664,-0.8459],
[-0.8427308,-0.13869424,0.78882848,0.231712,0.29765816,-0.9465184,0.6156224,0.16560312,-0.24474972,-0.9691048,-0.6800432,0.1516398,-0.1740592,-0.4596392,-0.580822,0.7879626,0.9780832,-0.3177498,0.11224442,-0.9504732,-0.35002604,0.63910272,-0.52738424,0.18016824,-0.256032],
[-0.8404368,0.007900994,0.24604648,-0.60563288,-0.68366872,-0.27549888,0.797008,0.323496,0.8893232,0.3180644,-0.9818456,0.5000228,0.32025496,0.651504,-0.9730868,-0.1684016,0.7606856,0.04660558,-0.6423482,-0.5646504,-0.5651776,0.000669403,-0.4553132,0.14897336,0.52123248],
[-0.8376452,0.905128,-0.79004112,0.1650404,0.59376032,0.01469178,-0.423494,0.6519884,0.37060988,-0.9764688,-0.2490786,0.5408272,0.7550532,-0.30371068,0.935558,0.9406182,-0.08366916,-0.3005484,0.2611676,-0.5871334,-0.9349844,0.040142752,0.65975152,-0.3824936,0.8650032],
[-0.8355584,0.8281672,0.36991648,-0.27675264,-0.47083216,0.5743576,0.12473668,-0.36808316,-0.5524896,-0.05797876,0.98876,-0.5356004,0.17516688,0.010016824,-0.7206936,-0.5216256,-0.2322438,-0.4698206,-0.3556244,0.1965072,0.6117396,0.05279196,-0.32162584,-0.57781224,0.8643408],
[-0.8348848,-0.51237864,0.30895976,-0.024226736,0.07858628,0.27958536,-0.25396068,-0.9560436,0.7261716,0.9412372,-0.9283916,-0.4136416,0.5727756,0.37659512,-0.25582672,-0.9998832,-0.7370096,0.1408348,-0.3810548,0.14679004,-0.6270552,0.9444104,0.23653144,0.19216472,0.9383568],
[-0.815356,-0.51421856,0.07907292,-0.47894464,0.53097552,0.9207512,0.9666364,-0.9666164,0.6139064,-0.8043304,0.09365144,-0.7955072,0.6123048,0.877806,0.21490552,0.5129708,0.2108464,0.1506593,0.1154859,-0.999679,-0.4085448,0.62800912,0.43350872,0.72308392,-0.13264888],
[-0.8067272, -0.37048984, -0.9168016, -0.33268816, -0.81078, -0.5369968, 0.4775556, -0.3728298, 0.7774424, 0.032786764 ,-0.9199148, -0.1176484, 0.5285564, -0.1063892, 0.26188676, 0.7759366, -0.14580748, -0.0237604, -0.4438548, -0.8913804, -0.699768, -0.34659896, 0.49563552, 0.71896656, -0.57937872],
[-0.7980328, -0.9522288, 0.67390008, 0.3746824, 0.9428664, -0.4316216, 0.218418, -0.942164, -0.7281128, 0.7044188 ,-0.24465924, -0.38011756 ,-0.6130284, -0.10730832, 0.9699192, -0.4353618, -0.6154168, -0.7874766, -0.7143518, 0.3842404, 0.5373548 ,0.8140808, -0.4806088, -0.5780236, 0.8017592],
[-0.7960268,0.4031184,0.4323096,-0.77113096,0.8834424,-0.07246608,0.9175976,-0.5019984,0.30464776,-0.4517108,0.22742316,0.5902212,0.31528908,-0.015868844,-0.7838328,0.7340562,-0.262718,-0.4537372,0.8631734,-0.6094146,-0.1106156,-0.514904,-0.68819608,-0.28195784,-0.019259488],
[-0.7790152,-0.37700904,-0.61121248,-0.18860912,-0.11816024,-0.9229956,0.1557496,0.9210944,-0.991054,0.30786404,-0.7972912,-0.17123852,0.2556264,-0.4894768,-0.337971,-0.882681,0.7169998,-0.995132,-0.2541614,0.5616324,0.15352748,0.4512784,-0.16903264,0.060711368,0.85792],
[-0.7768192,0.8170888,0.75700968,-0.93814,-0.15708264,-0.0283991,-0.6256516,-0.8111452,-0.1623698,0.9199328,-0.38002044,0.76326,-0.955098,-0.4634024,0.6714672,0.943659,-0.16040542,0.532662,0.9944372,-0.209184,0.31977896,-0.14951448,-0.15106,-0.062129824,-0.47644296],
[-0.771862,-0.44242696,-0.3161632,0.41096336,0.75017968,0.437102,0.8925472,-0.4513712,0.33654488,0.871344,0.9126508,0.6384664,-0.999744,0.4909828,0.9841788,0.8478938,-0.8691858,0.2640192,0.4397676,-0.7484574,0.29472836,-0.45556664,0.9718752,-0.310304,-0.42144512],
[-0.7715652,0.11651864,-0.29480088,0.41909416,0.71083704,-0.8538556,0.469364,0.6810112,-0.7860628,0.7035276,-0.1769604,-0.2751654,0.31535036,0.32180336,-0.13602868,-0.6343676,-0.00528743,0.6134502,-0.2835076,0.5275658,-0.07759776,0.3518548,-0.14600472,-0.43344136,0.36789584],
[-0.7677428,-0.66873856,-0.25003896,0.66394224,0.58994856,0.7269372,-0.9374064,0.5370364,-0.6624884,0.8348064,-0.12402552,-0.5809828,-0.5958252,0.5180112,0.30439384,-0.9273832,0.17530704,0.3923108,-0.4959522,0.7883386,-0.532122,0.32967088,-0.19613688,0.18821456,0.51291016],
[-0.7675592,-0.18748048,-0.71686504,-0.61743712,-0.77112072,0.4073536,-0.13638788,-0.6835004,-0.017528116,-0.2163496,-0.029308856,0.21000368,0.32145084,-0.5556892,0.7675244,0.8367202,0.419422,0.1873735,0.16339208,-0.3751808,-0.26341772,0.21212736,-0.8440624,0.82718,-0.022741448],
[-0.749346,0.055332864,-0.5604896,-0.59717672,-0.72054832,0.32979796,0.7318056,-0.19342856,0.4864028,-0.0530556,-0.6502668,0.9180884,-0.25588672,0.4213216,0.8905676,-0.07310936,-0.1786823,-0.5495282,0.9255658,0.08229248,0.20981952,-0.15066064,0.456006,0.85658,0.8328832],
[-0.7438392,0.66770248,-0.8643448,-0.34287776,-0.816276,-0.486104,-0.10835032,0.7404216,0.750536,-0.029458692,0.3728994,0.746444,0.32734324,-0.438092,-0.8378504,-0.4660382,0.3762896,0.02545314,0.2495606,-0.6959134,-0.13711772,0.47446152,0.30212248,0.6104088,-0.13107064],
[-0.7416472,0.40747472,-0.4899924,0.70081968,-0.64379928,0.8574216,-0.4498808,-0.5399188,-0.4895756,-0.9484316,-0.5995684,-0.9819696,0.18565412,-0.15013764,0.9274056,-0.3595806,0.8465138,0.586992,-0.506378,-0.8054726,-0.04828456,-0.78002672,0.8252992,-0.55683904,0.75194576],
[-0.7408352,-0.1252196,0.34848416,0.5955764,-0.56463864,-0.08127228,-0.5667536,-0.8589672,-0.8882016,0.10083176,0.6540832,-0.5639004,-0.8428128,-0.8088436,-0.7663948,0.4134828,0.14706878,-0.5240152,-0.087221,0.9348938,-0.6199444,-0.74043288,-0.9333168,-0.20007624,-0.39448184],
[-0.7390788,-0.62627584,-0.22873472,0.9008888,0.8099352,0.32168936,0.114362,-0.873278,-0.4502132,0.8911064,0.9040744,-0.1528828,0.7611792,0.387475,0.17702108,-0.4091736,-0.9410396,0.19915162,-0.5171976,-0.73586,-0.38113092,-0.42553448,-0.68373168,0.21620048,-0.33753576],
[-0.7376992,-0.7663244,0.70418384,0.49370984,-0.2415536,-0.8666664,0.09642552,-0.5831628,-0.4644064,0.12243612,0.4388284,0.434028,0.27144532,-0.4917292,0.7785808,-0.013304348,-0.6815852,-0.707685,0.8712222,0.5112174,0.8120828,0.8413328,-0.8270928,-0.78629096,0.63523984],
[-0.7329844,0.11811656,-0.51307536,-0.2821804,0.53071112,0.13209288,-0.17842008,0.02990292,0.20958948,0.11252512,0.37103604,-0.58013,-0.9710928,-0.5853688,0.001094207,-0.9741942,-0.5634174,-0.846164,0.8363136,-0.5108704,0.9977292,0.55704184,-0.8636,0.77589576,-0.78939184],
[-0.7324908,0.53377304,0.033573136,-0.8407056,0.64309016,-0.7055828,-0.8162456,-0.7641244,0.24595248,0.5196384,0.38981696,0.567256,0.6703656,0.6914736,-0.8218136,-0.5649984,-0.5256274,-0.6107508,-0.4779708,0.18436942,0.6353012,-0.41492272,-0.987916,-0.1477264,0.72346792],
[-0.729052,0.72157184,0.066417448,0.51655296,-0.16441016,0.4787304,0.9584624,0.8776636,-0.31409988,0.8077672,-0.11502456,0.006626928,0.4410752,0.6556108,-0.8027652,-0.13926176,-0.9018598,-0.5879802,0.5655134,0.7902824,-0.28160032,0.76019184,-0.5546768,-0.4329952,-0.9627304],
[-0.7283508,-0.224658,-0.77200424,0.36615704,0.4774252,0.8275276,-0.9640624,-0.8951176,-0.6085136,-0.5104308,-0.7844152,-0.8470492,-0.8170964,-0.23323752,0.503328,0.2611808,-0.8042712,0.7675682,0.6752738,-0.524654,0.7953544,-0.75277952,-0.51164392,-0.65117296,-0.071913264],
[-0.7234292,0.59654384,-0.65628992,-0.5178844,0.52860056,-0.21654304,0.9463412,-0.10414776,0.4147972,0.24779428,-0.5873928,0.6068592,-0.495486,-0.1183924,0.812578,0.6892092,0.3527492,-0.706458,0.2449776,-0.12970486,-0.4835968,-0.12299304,-0.9982288,-0.73006376,0.31765296],
[-0.720552,-0.09033296,-0.68376368,0.50527432,-0.23690448,0.11248216,0.5138056,-0.5702172,-0.011352892,0.24776616,-0.9439116,0.27090636,-0.7524828,0.20096804,0.07174724,0.384875,0.07819688,0.5125202,0.14650818,-0.19380692,0.4743352,-0.8039656,-0.34095416,-0.52317944,0.854],
[-0.70657,-0.9909024,0.15508952,0.22221712,-0.72638272,-0.9496884,-0.08128896,0.6842752,-0.9931228,0.449018,0.6536716,-0.04810396,0.6571504,0.019490588,-0.5051992,0.11858564,-0.13155986,-0.7328058,0.776212,0.5886384,-0.5996068,-0.027518296,0.863528,0.9506864,-0.70824512],
[-0.7062028,-0.35895624,0.16479624,0.79272376,0.46981976,0.36350748,-0.448952,-0.6494916,0.876708,0.8553256,0.9760064,-0.4311316,-0.9039836,0.729482,-0.5526784,0.7795792,-0.234936,0.07159028,0.460723,-0.5104328,-0.18775632,0.006418193,-0.41776144,0.34280672,0.905992],
[-0.6968224,-0.818192,-0.73817584,-0.76153656,-0.61606856,0.2314406,-0.639676,0.6162408,0.5466236,-0.33785416,0.31139944,-0.5727504,0.13047652,-0.9311892,-0.35625716,0.7278722,-0.9342358,-0.7641484,0.2491168,-0.5234016,-0.04371536,-0.33239848,-0.3083264,0.9212808,0.03704004],
[-0.696184,0.9471392,-0.8251128,-0.16582136,0.9316272,-0.4241152,0.21823984,0.307372,-0.24253612,-0.32674792,-0.35387548,-0.5549168,-0.4389512,-0.8348928,0.04898252,0.7871224,-0.07005384,0.4041674,0.7950062,0.3522344,-0.10175136,0.51276304,-0.74794344,-0.73269104,-0.1239728],
[-0.6957888,0.8720712,-0.9913016,0.075367056,-0.32159376,-0.4742748,0.5756844,-0.08187064,0.9065696,0.18528812,-0.8076976,0.5649508,-0.8124728,-0.09161396,-0.36625524,0.925689,0.4377082,-0.12559474,0.788199,0.9251578,0.03393454,-0.24158432,0.30393696,-0.8305848,-0.170402],
[-0.6936896,0.9496744,-0.9852288,-0.60929352,-0.909064,0.008384836,-0.7987052,0.14677024,-0.4874424,-0.996744,-0.975824,0.31426396,0.034993116,0.6546984,0.907428,-0.7415632,0.8323022,-0.15117778,0.5494802,0.922689,-0.21910656,-0.32989136,0.9074832,-0.3506756,0.79924656],
[-0.6899652,-0.21417016,-0.42429704,0.94076,-0.23093904,-0.8928392,-0.5424148,0.7564508,-0.4644868,0.24560252,-0.1424238,0.037742624,-0.35159584,0.6689512,0.9742676,0.527897,0.7976742,-0.7892456,-0.2195702,-0.02268674,0.39503384,-0.9358208,0.9960512,-0.43239952,-0.11976936],
[-0.6842824,-0.66560672,-0.72794376,0.60699824,-0.77811304,-0.603752,0.28216976,0.26625516,0.8080684,0.4169904,-0.014095284,0.16614908,0.3564904,0.5963684,0.916648,0.04124662,-0.08947128,-0.11986784,0.005206224,0.16157678,0.494258,-0.74189464,0.17030592,-0.921488,-0.8187608],
[-0.6813772,-0.74723616,0.8488976,0.33949856,0.12609056,0.8331528,0.17852904,0.6546072,-0.33357824,0.6989888,0.20209684,0.6149312,-0.3572928,-0.05819624,-0.06784004,0.2784212,0.9806398,0.538718,0.5583576,0.4302688,-0.18146696,-0.50770192,0.09387008,0.00043334,-0.34959272],
[-0.6799432,0.3580248,-0.43760408,-0.9293952,0.135592,-0.5840156,0.8293628,0.07348244,-0.6428624,-0.2955938,-0.7468404,-0.6599868,-0.677914,0.965388,-0.10677004,0.784798,0.3213798,-0.5789356,-0.763033,0.8351574,0.32196112,-0.15441728,0.26703848,-0.48154488,-0.08545624],
[-0.6622072,0.76554496,-0.2498196,0.16284688,0.28749928,0.9746924,0.4351936,-0.07677896,0.6543684,0.36817156,0.13415428,0.4783516,0.016146616,-0.6647704,0.6719552,0.5288946,0.9423538,-0.09486848,0.2923292,0.8792118,0.14033888,0.30108616,0.58652768,0.57966536,0.9832472],
[-0.6608064,0.14772352,-0.8982976,0.59289544,-0.360868,0.25508872,-0.47068,0.6101092,-0.22270672,-0.027832356,0.11527348,0.006460224,0.19505224,0.5083544,-0.25782076,-0.73083,0.5941394,-0.5136524,-0.007455558,-0.518573,0.4985848,-0.72231632,0.60502488,-0.20631616,0.4117532],
[-0.6564068,-0.8735424,0.2732104,-0.53249192,0.32681384,0.8556848,0.9377668,-0.5576752,0.702164,0.23124108,0.10493504,-0.9998312,-0.16378256,-0.9037568,0.19521068,-0.010764456,0.5468736,0.9993772,0.8613974,-0.5724148,0.51733,0.68905112,0.54831576,0.64468304,-0.08335856],
[-0.653878,0.45734344,-0.48578096,0.911452,0.8606024,-0.816644,0.8487512,-0.39375372,-0.21253576,-0.6054564,0.9840204,-0.4578012,0.7067516,-0.04390444,-0.4467884,-0.527955,0.07329634,-0.985259,-0.5205998,0.6416968,0.5201492,0.2194636,-0.891752,0.16493736,-0.35187792],
[-0.649748,0.9162216,-0.29185896,-0.6278908,-0.905708,0.28196472,-0.81354,0.9874712,-0.8604604,0.8639628,-0.9243176,-0.14151592,0.9595956,0.32031504,-0.30009336,0.17412108,0.2125744,-0.269332,-0.0128547,0.2843404,-0.8430208,-0.75462736,-0.029697552,0.20235344,0.2154252],
[-0.6494904,0.68503712,-0.52886384,0.5280344,0.8230488,-0.21698828,0.9368636,0.9013488,0.4188828,0.21061352,0.25649688,-0.4180124,-0.22396004,-0.5893112,0.9024332,0.459914,-0.2679762,-0.2259096,-0.09692884,0.07915564,0.6528888,0.4730896,0.15513088,0.08419056,-0.253116],
[-0.6477716,-0.64587584,0.39943224,0.46602504,0.1647644,-0.08632932,-0.5949752,-0.6151072,0.19779232,0.7075232,-0.24252316,-0.7465228,0.10420968,0.817642,0.4334516,0.8527342,-0.6080776,0.06086184,0.4525178,0.377614,-0.039810716,-0.75962208,-0.72970752,-0.20134312,0.50105584],
[-0.6455824,0.8178488,0.15047824,0.1192516,-0.8876512,-0.07104928,0.8382644,0.22457224,0.22858436,-0.450606,0.11128428,0.6080032,0.014450276,0.3642388,0.4074536,-0.6528998,0.677533,-0.6198808,-0.8839294,0.8876738,0.15390192,-0.13744744,0.59956968,0.5673884,-0.61369864],
[-0.637856,-0.9822056,0.067404512,-0.52446048,-0.39874688,-0.9175348,-0.970262,0.3231542,0.23380676,0.17589824,0.4658296,-0.31207264,-0.6636632,-0.7399648,0.5314388,0.8828788,-0.9452626,0.6173942,0.491212,-0.9006292,0.07012268,0.8803064,-0.9814192,-0.59790928,0.45349504],
[-0.6328532,-0.5053424,-0.37114336,0.61776096,0.026146328,0.576854,0.269078,0.8733068,0.31266264,0.5010184,-0.4559596,-0.09887196,-0.512898,-0.518912,0.8594444,0.16435376,-0.4392078,0.3914976,-0.7313938,-0.03034974,0.6042248,-0.73038696,0.5064144,-0.060164448,0.066405888],
[-0.6326484,0.75630544,-0.54340688,0.62892496,0.049490888,0.26493548,0.26684088,-0.3457552,-0.37678036,0.0261113,0.6358292,0.5406256,0.2023044,-0.4743196,-0.38737792,-0.13133718,-0.9586012,0.9222558,0.9910912,-0.208235,0.031227004,0.7133444,-0.16355976,0.08967944,-0.46372872],
[-0.6287684,-0.39531888,-0.53970512,0.71605072,0.32745336,0.18834952,-0.37122744,-0.9411672,0.14053348,0.7505652,-0.8936448,0.2818088,-0.6644316,0.7579476,-0.7797008,0.7108028,0.2696052,-0.9239754,0.80311,-0.454904,-0.9329976,-0.8886864,0.9877888,0.37185224,-0.3014224],
[-0.6258996,0.40846752,-0.32835392,-0.09087312,0.63017824,-0.4315328,0.8686348,0.9911444,-0.6357028,0.5031724,-0.211242,0.6323728,0.578674,0.5084948,0.31914868,-0.7176254,-0.2951428,-0.891053,0.18251376,-0.8275114,0.6772284,0.079011128,-0.4212436,0.69209056,-0.059317792],
[-0.6217496,0.77934248,0.55279848,-0.65906072,-0.949332,-0.6640368,-0.36646024,0.9821528,-0.9827308,-0.7827076,0.2755396,-0.27623048,0.5218768,0.3905788,0.35363244,-0.017592622,0.2930492,0.9719176,0.5688828,0.18237948,0.7661428,0.35273552,-0.77983304,-0.902356,0.0183568],
[-0.62074,0.24944536,0.373424,0.47760672,-0.5527728,-0.959726,0.8035448,-0.6809428,0.4181552,-0.9308852,0.555262,-0.35610936,0.7436904,0.6603196,-0.750764,0.9624908,0.8984194,0.994279,0.3560708,-0.5031044,0.36563892,-0.51240968,0.19930192,-0.19210992,0.57992928],
[-0.6177924,-0.49444128,0.08376848,-0.22593288,-0.53114824,-0.601094,-0.33270504,-0.8651076,-0.8419904,0.07736168,0.32947328,-0.10941604,-0.4506924,0.4863224,-0.542696,-0.3071158,-0.12255062,0.3951874,-0.2282402,0.08158038,0.8793872,0.55452904,0.41826056,-0.74627576,0.45873888],
[-0.616898,-0.9818464,0.64798408,-0.40141512,-0.48444928,0.08525984,0.18763312,-0.4580384,-0.20376492,0.5477964,-0.07896996,0.7269244,-0.4968932,-0.7179524,0.7351528,0.6542104,0.02924966,-0.98359,-0.04906516,-0.4850184,-0.5860604,0.24379504,-0.0975016,-0.50370392,0.8289408],
[-0.613828,-0.9798632,0.9847208,0.66722672,0.8178176,-0.07489528,-0.5787968,-0.38737508,0.9451592,0.7264508,-0.6641056,-0.7083452,0.20971968,0.4015964,0.5554192,-0.6468366,0.3108234,0.9456058,0.15379874,-0.6701534,0.811846,-0.14991304,-0.42300728,-0.855532,0.64638544],
[-0.6068488,0.8210768,0.838144,-0.363916,0.44466984,-0.8398692,0.4930404,0.7355756,0.8644948,0.16613576,0.8251528,0.14883296,-0.33759264,0.30962812,0.7752476,-0.5150408,0.883889,0.7895522,-0.18060706,-0.7746222,-0.30058856,0.018619568,0.45013824,-0.62747848,0.8828912],
[-0.6007196,0.41059352,0.42202248,0.2538016,-0.075599456,0.72339,0.9607904,-0.37823276,-0.8883356,-0.31370788,0.11459528,0.8841392,0.4174584,-0.5681544,0.441326,-0.015657482,-0.2065512,-0.6507306,0.7396598,-0.429088,0.01074048,-0.34620776,0.45419232,0.42129272,-0.406952],
[-0.5923388,-0.6605352,-0.9548768,0.28745216,0.9030568,-0.4434244,0.04284728,-0.6679624,0.004149608,-0.7761684,0.9733076,0.6471672,0.7040364,0.32368644,-0.8365848,-0.4591722,-0.6641982,0.0252877,-0.2438616,0.5205504,0.7220528,-0.069108824,-0.11341464,-0.37367552,-0.54228504],
[-0.5916584,-0.36389296,0.017174896,0.79172592,0.20333024,0.35365872,0.4567152,0.7638388,-0.5910608,0.8331264,0.1707494,-0.848954,-0.4150188,-0.6974,-0.16714532,-0.438929,-0.8304942,0.3043978,0.3191828,-0.9977472,-0.80036,0.67094424,-0.8553008,-0.9443184,-0.167768],
[-0.5906,-0.7144884,0.38797456,-0.8283496,-0.16484288,0.3511454,-0.4266108,0.97984,0.28612812,0.904248,0.5473684,-0.6006744,0.4671692,-0.2372614,0.007220744,0.3600198,-0.435746,0.8035176,0.5005254,0.03156312,0.7681988,0.47646208,0.9051416,-0.022662488,-0.77994816],
[-0.5827696,-0.986328,-0.17052176,-0.16426184,-0.74267016,-0.8823824,0.6775708,0.8536032,-0.871282,0.10375684,0.9045828,-0.6416196,0.08926636,-0.9307768,0.5008616,-0.8991146,-0.1664678,0.03862468,0.7439932,0.433126,-0.5407764,-0.856668,-0.68803056,-0.62129232,-0.77891704],
[-0.5824192,-0.55853944,0.8793432,-0.15503392,0.25294896,-0.4154412,0.7849448,0.7627056,0.877196,-0.029555548,-0.7042284,-0.720358,-0.7147344,0.9411436,0.6127732,0.14820602,-0.3094392,0.7795152,0.5230144,0.9916422,-0.020826596,-0.9324224,-0.70558992,-0.346718,-0.8545752],
[-0.5774376,0.7081384,-0.8093504,-0.13755424,0.1312092,0.7540544,-0.7375156,-0.5252724,0.33428404,0.8692328,0.92514,-0.07378156,0.969498,-0.8785656,0.21182976,-0.9476634,0.03544078,0.7034498,0.1605802,0.7262702,-0.8448576,-0.51846496,0.966308,-0.20088024,0.4318144],
[-0.5761936,0.11832152,0.11081712,-0.54427008,-0.42519632,0.2654812,0.17593116,0.5487324,-0.27936456,-0.8081748,-0.26705484,0.5712376,-0.33642768,0.31025296,-0.10620608,-0.3907152,-0.7098574,-0.2158198,-0.321937,0.10495058,0.0903736,-0.26385376,-0.8498576,-0.7353876,0.035684208],
[-0.5732512,0.8620232,0.30199424,-0.892076,0.4871424,-0.5331316,-0.6176584,0.22885448,-0.21610236,-0.14275224,0.09797468,0.009426252,-0.2631588,0.5120944,-0.6349948,0.927864,-0.8484498,-0.08353602,-0.7940544,-0.06749338,0.11012612,-0.27375152,-0.09298832,0.29060384,-0.35881488],
[-0.564438,-0.38127112,0.41964304,0.150308,-0.77825616,-0.7618812,0.25800736,0.5086916,-0.15358916,-0.8583512,-0.196768,-0.18376624,-0.19668632,0.9620184,0.15591368,0.8521356,0.5904458,-0.13392754,-0.9510898,-0.7552226,0.3099886,-0.45301424,-0.30890832,0.48950832,-0.06232396],
[-0.5534652,-0.15313392,0.5864564,0.44214176,0.26029032,0.27015096,0.6855788,-0.730846,-0.549782,0.696944,-0.6144284,0.677036,-0.6655744,0.23209904,-0.3485052,0.5235182,0.07941482,0.10381674,0.3827052,-0.5010656,-0.32064852,-0.9140312,-0.50797616,0.019921168,-0.60244576],
[-0.551768,0.58879256,-0.05022332,-0.1813088,-0.9606856,-0.20270404,-0.6125248,0.2714666,-0.6745712,0.5784536,0.021114716,0.5096656,0.7119176,0.15208124,-0.34703132,-0.5582304,0.8427266,0.6151926,0.568199,-0.5136298,-0.10584292,-0.12092288,-0.08138368,0.32829936,-0.8601632],
[-0.5509672,-0.51729184,-0.4965224,0.68314984,0.8489304,0.31800132,0.852966,-0.7883696,-0.27918164,0.6049084,-0.15303844,0.18074148,0.29836424,-0.648856,-0.3135152,-0.6748188,0.8049232,-0.2339326,0.4044438,0.3867374,0.9916076,-0.18812432,-0.69444728,0.22601704,0.31167056],
[-0.5437532,0.71994768,0.1760268,-0.7339108,-0.982956,0.10754892,0.25826016,-0.8799528,0.26997572,-0.7606576,-0.704064,-0.36462064,-0.9358676,0.4669208,0.5386612,-0.265406,-0.12160286,-0.6146308,-0.6583526,0.776075,0.9230172,0.9432048,0.14481888,-0.9097816,-0.2969552],
[-0.5408696,0.3310304,-0.9776648,0.26015408,0.67632224,0.408696,0.5762712,-0.15718864,0.04465488,0.8223716,-0.9400368,-0.9512288,0.22831116,-0.7418332,-0.24238788,0.5092304,-0.2436236,0.5242808,-0.7658584,0.8906976,-0.7199532,0.9509176,-0.02554316,0.52701224,-0.39043168],
[-0.5388868,-0.040807688,0.9929256,0.965376,-0.2143672,0.526332,-0.11426488,0.6105344,0.28537908,0.564532,-0.8490096,-0.6157252,-0.8697612,0.9102356,-0.9604788,0.8130066,-0.04717166,0.1664272,0.6973556,-0.2822702,-0.9698984,-0.2573756,0.9041656,-0.65632752,-0.61331976],
[-0.5311888,0.52505384,-0.38831512,0.8871288,0.39312792,-0.4823612,0.8547664,0.34568464,-0.6449144,0.9478864,-0.4586028,0.551252,0.1775768,-0.18954872,-0.8531624,-0.9861746,0.5265622,0.5758846,0.5041318,0.8326504,0.599962,-0.76679488,-0.1645792,-0.077713768,-0.9399568],
[-0.5311448,-0.35036856,0.9347424,-0.72119496,0.09944624,0.23814616,-0.5469472,-0.802338,0.8020692,0.9715316,-0.26093732,0.5857968,0.05364996,-0.7753964,-0.6354732,-0.4063598,-0.9717912,0.9874806,0.7678414,0.3694388,-0.28742488,0.79865416,-0.042173216,0.1423948,-0.71362912],
[-0.5266276,-0.37772168,-0.18341976,0.8338128,-0.1379416,-0.5817528,-0.32259728,-0.5535572,0.5362196,0.7077828,0.760214,0.5512212,-0.002503706,-0.6974616,0.2598578,0.08885406,0.9711724,-0.184556,0.08985756,-0.9524868,-0.4133428,-0.36856032,-0.22637008,0.66378816,-0.12236792],
[-0.5226352,0.949356,0.10377864,-0.26668248,0.47373712,-0.78104,0.06025116,-0.5801572,-0.4740996,0.8933024,0.24923612,0.4465028,0.04034712,0.28276424,-0.06403032,0.7102268,0.5766256,-0.7942946,-0.2045244,-0.3361762,-0.9205264,-0.69896112,-0.31500184,-0.36764816,-0.01225028],
[-0.517906,0.8848024,-0.037864224,0.005349211,0.9650304,0.5246244,-0.6628592,-0.3276426,0.19618144,0.7883268,0.162202,-0.5982964,-0.00898696,-0.34312928,-0.8399664,0.07729196,0.9131224,0.05273802,0.2917996,-0.9476018,0.368945,0.56220184,-0.57205728,0.8630616,-0.02609884],
[-0.514084,0.28212776,0.40532568,-0.42086544,-0.47613464,-0.508174,-0.7123,0.94615,0.8482092,0.8835532,-0.7449404,-0.05417068,0.05127472,0.5851404,0.20204476,-0.4549688,0.7474714,-0.371878,-0.7305142,-0.8514058,-0.9642696,0.79635552,0.05308652,-0.076726472,-0.3296316],
[-0.513512,0.058296688,0.7008784,0.1682628,-0.63222752,-0.4187328,0.32235864,-0.7850828,0.744728,-0.6527184,-0.4669692,0.8458408,0.8467956,-0.6284336,0.4143692,0.03335352,-0.829931,-0.8885102,0.9996094,0.3916548,0.9521152,0.71028408,-0.15027008,0.33486368,0.02747144],
[-0.5094112,-0.42247432,0.8373648,0.19491144,0.865672,-0.15223832,0.6894536,-0.4068884,0.8980652,0.17957836,0.6694324,0.6037192,-0.02351278,-0.12144644,-0.6881988,-0.822338,0.20687,0.348452,-0.6787322,-0.6061196,0.4247008,-0.57392008,0.74319808,0.4362912,-0.8064048],
[-0.505584,-0.9392712,-0.23370808,0.1666944,-0.13383784,-0.711658,0.465342,0.9346648,0.8489948,0.9424852,-0.86313,-0.0439602,-0.27715344,0.9871468,0.4276748,0.9667276,0.6719928,-0.6262356,0.19305676,0.4888542,0.9891088,-0.77903352,-0.3523232,-0.55121928,-0.35047744],
[-0.5004524,-0.9986096,0.108954,-0.41636456,-0.9845896,0.27513376,0.6565604,0.7189544,0.809026,0.6721048,0.22607692,0.21487004,0.38928484,-0.16138836,0.5960224,0.6267534,0.9211918,-0.2533644,-0.14942722,0.303159,0.6075868,-0.63376056,-0.16418312,0.18945992,0.49654344],
[-0.5001076,-0.70424992,-0.1418072,-0.76537304,0.73133456,-0.04057944,-0.4166172,-0.20947004,-0.8255716,0.11641696,0.13450936,-0.3299112,0.8468508,-0.4330068,-0.09406472,0.2913548,-0.2723264,-0.6618184,-0.06515082,0.12808922,0.30550968,-0.69565912,-0.7759828,-0.67714016,0.9848208],
[-0.49273,0.8538,-0.67411968,0.09584216,-0.8348752,-0.023629328,-0.821924,-0.4031184,-0.35718772,0.10827484,-0.9070612,-0.9018684,-0.5578192,0.39781984,0.5663296,0.1398389,-0.5170742,0.497026,0.5257572,-0.2586384,0.9873856,0.57254688,-0.052865536,-0.12676752,0.60448752],
[-0.4925448,-0.74255032,-0.36101272,0.804836,0.42182984,0.03046198,0.6402472,0.27643352,0.12206836,-0.7697408,0.674392,0.8776532,0.23774928,0.7036304,-0.00156983,-0.754448,0.7529522,0.837981,0.823816,-0.6671244,-0.4194896,0.37157912,-0.47186968,-0.9348168,0.019660064],
[-0.4925128,-0.77576616,-0.49149352,0.67516328,0.5059992,-0.5952888,0.9979124,0.1810276,0.06818092,-0.6708124,0.0863102,-0.5083464,0.9504852,0.4030908,0.9319768,-0.7950252,0.05310856,-0.7640942,-0.4503912,0.19711924,0.30062184,0.174582,0.349828,-0.16695008,-0.8661688],
[-0.4919172,-0.38677824,-0.30685864,0.49617208,-0.036836456,0.914476,0.0826878,-0.36139184,-0.4584824,-0.8795656,-0.7781768,-0.885054,0.018051084,-0.16728864,-0.874448,0.3135906,0.8990124,0.9778562,-0.18059582,-0.3042676,-0.4552512,-0.6720704,0.004226314,0.69992736,-0.54824352],
[-0.4843496,0.04209644,0.12976144,0.45125336,-0.72407352,0.13352696,0.7242752,0.4160068,0.9287416,-0.0930854,-0.025354636,0.18205172,0.06778664,0.8869788,-0.8820748,0.04863906,-0.929457,-0.08445322,0.02471696,0.7557498,-0.9187628,0.53113,0.31314856,-0.1731124,-0.9220736],
[-0.481392,0.39470872,-0.15592584,0.942816,0.358378,0.4355816,-0.31863792,0.6480392,-0.4923024,0.14235208,0.6685348,0.15678396,0.5121696,0.0706794,-0.35130864,-0.346491,0.2895434,-0.15177618,0.05507702,0.72786,0.5580064,0.65367592,0.61613232,-0.853928,-0.62641016],
[-0.4811532,0.40590816,-0.72115232,0.8938744,0.9933224,0.6630196,0.4511232,0.6077844,-0.24812772,0.05870368,0.35198708,-0.35677032,-0.37795816,-0.6165548,0.6023296,-0.9719712,0.2213572,0.473723,0.80798,0.7983062,-0.8521204,-0.9174432,0.27237768,0.51633616,-0.79874648],
[-0.4802472,0.70581752,-0.71047512,0.9007072,-0.9386888,0.4274712,-0.0746582,-0.4885544,-0.2683546,0.32411084,-0.30582312,0.5140792,0.6463444,-0.406774,-0.14858076,-0.3767876,0.006322884,-0.639313,-0.0860242,0.009299796,-0.6868036,0.26243688,0.79412496,0.8667344,0.060132216],
[-0.4788332,-0.63056752,-0.60565808,0.26920896,-0.016260304,0.7351272,0.07083176,0.18026732,-0.4314276,-0.9458912,-0.9171736,0.9819492,0.7505668,-0.8056092,-0.29885292,0.16771146,-0.2103978,0.12272184,0.15719728,0.9923368,-0.6910668,-0.2860072,-0.8277016,0.24513648,0.59361712],
[-0.4772224,0.51563872,0.22910248,-0.9639664,-0.31710672,-0.8459972,-0.3170728,-0.9779616,-0.5837444,-0.341599,-0.8944792,-0.714178,-0.39726828,0.2066584,-0.4730116,0.4349918,0.5886426,0.7216674,0.15191654,-0.2497762,-0.6063024,0.53909552,0.27414512,-0.20996048,0.9273472],
[-0.4771052,-0.30326048,-0.9911776,-0.46757768,0.059991688,-0.29483756,-0.5160788,0.9137116,-0.005617092,-0.810574,0.006537664,-0.765156,-0.029861852,-0.010974044,-0.7294308,0.899129,0.14957174,0.5193706,0.3823036,0.668909,-0.13878312,0.5940524,0.39814728,-0.6954432,-0.23185696],
[-0.4692168,0.77143168,0.51856032,0.59202912,-0.6240956,-0.23784648,-0.8894652,0.10662716,0.6803276,0.9134072,-0.38168128,0.8847216,0.4423144,-0.9759532,-0.12268864,0.2775476,0.17771936,0.722263,-0.18074002,-0.4635832,0.29318456,0.8287968,0.9400264,0.42636624,0.36728856],
[-0.4581192,-0.52531664,0.77699928,0.66002288,-0.63538608,0.7485704,0.13965804,-0.4476316,-0.73748,-0.9942064,0.33391616,0.36341656,0.5501416,-0.4297332,0.8850564,-0.7711974,-0.3307606,-0.7778482,0.5587704,0.8930758,0.7553424,-0.10010552,0.6445612,-0.66311056,-0.11349944],
[-0.4568388,0.859672,-0.899884,-0.25204128,0.67481456,0.1384562,-0.14661704,-0.22004288,-0.32527348,-0.04073144,-0.36819516,0.6141356,-0.07271644,0.33882288,0.08668268,-0.6949688,-0.2457904,-0.07043232,0.6633812,6.30E-05,-0.1472948,-0.33845496,0.050272256,0.76161856,-0.9392048],
[-0.4489444,-0.79565328,-0.8329888,-0.18535536,0.9768384,0.31534016,0.2560202,-0.22496236,0.9363452,0.37659496,-0.18325308,-0.259956,0.8129468,-0.8294212,-0.07011028,-0.6671762,-0.765144,-0.13122072,-0.19823258,-0.06080444,0.22871428,-0.56598904,0.69031136,-0.37427344,0.62852992],
[-0.4474396,0.9760032,0.45109928,-0.9233512,0.69256032,-0.4668976,-0.5935584,0.07126884,0.92662,0.597366,0.8424984,0.5073028,0.8685488,0.7603472,0.314434,0.0623593,0.09827816,0.4650466,0.5955126,-0.319721,0.05378612,0.8117664,-0.76715328,0.67057592,-0.67247728],
[-0.447074,-0.72899784,0.017930608,0.40042288,0.19486456,0.35391096,0.986058,-0.005125772,-0.630994,0.04434392,0.10987288,-0.7774064,0.9240796,0.19735324,0.5021244,0.06580194,-0.8744148,0.691933,0.38274,-0.9889476,-0.9603392,-0.59657256,-0.20364096,0.30452024,0.21156328],
[-0.4450096,-0.8400848,0.218672,0.698728,0.029406912,0.6923616,0.8295904,-0.9648296,-0.477302,0.69684,0.4314744,0.15468776,-0.015325216,-0.7165564,-0.91422,-0.972103,-0.5654952,0.7718322,-0.4149686,0.8563918,0.4090632,-0.3176824,-0.56125576,0.28916264,-0.8240704],
[-0.4407344,0.06944524,0.38941328,-0.883584,-0.08793512,0.3567508,-0.32832672,0.7991044,0.355706,-0.9591564,-0.25323552,-0.39393688,-0.4317712,-0.8436632,-0.7458016,-0.8718822,0.201248,-0.8203802,0.1243302,-0.3196256,-0.1074694,0.9552088,-0.869332,0.8438608,-0.77840472],
[-0.4294432,0.8611336,0.8258128,-0.32656336,0.006181058,-0.24875604,-0.432922,-0.662676,-0.04707952,-0.20503896,0.25888468,-0.963512,0.017758792,-0.28174544,-0.05050268,-0.07635376,0.07797114,-0.4443078,0.0966718,-0.3094096,-0.011287012,0.49278656,0.9752176,0.17129608,-0.41523952],
[-0.4294264,-0.8378224,-0.9044584,0.4749588,-0.71597712,0.16749296,0.5693092,0.7536592,-0.85633,0.015537312,-0.30259656,-0.7693268,0.29072388,0.24212304,-0.4887636,0.10548884,0.3519144,0.9854752,0.013503238,-0.0213149,0.5060076,0.9102568,-0.78775104,0.8137728,-0.9888376],
[-0.4252448,-0.3152476,0.78766968,0.938376,0.28022912,0.36303488,-0.5718624,0.7447932,0.16384564,-0.7070956,0.17714012,-0.5313596,-0.15585232,0.7216116,-0.087497,-0.2167826,-0.7912014,-0.7909786,-0.08908076,-0.8069888,-0.5655884,0.17473736,0.32288552,0.76019312,0.47259344],
[-0.4132588,-0.03742676,-0.8495992,-0.01093028,0.8984816,-0.0984244,0.9080276,-0.7659192,0.019743296,0.692954,0.5565732,-0.5948292,0.17028052,-0.08957992,-0.4492996,-0.07740884,-0.891279,-0.4172614,-0.2610956,-0.9373704,0.32387032,-0.9322728,0.8082544,-0.1671004,-0.8133616],
[-0.406402,-0.24858544,-0.8962256,0.43457536,0.9813816,-0.00348489,-0.67691,0.25192036,-0.1995374,0.000912156,0.11627288,0.31243312,-0.6500884,-0.447522,-0.10568304,0.7558526,-0.25072,-0.372199,-0.4247034,0.2295434,-0.6896372,0.1939028,-0.1431824,-0.2525292,-0.870512],
[-0.39919504,-0.8647184,-0.581426,-0.4402812,-0.7972936,-0.031065284,0.09551008,-0.31295244,0.4847904,0.0729368,-0.3737308,-0.5168616,0.0870714,0.7903832,0.6866048,-0.0752892,-0.008223894,-0.627537,0.4776646,0.5970486,-0.04705644,-0.3398824,0.818608,0.889064,-0.30868944],
[-0.39553816,0.75046608,-0.005619231,0.12182856,0.69195448,0.8699972,-0.28979108,0.4388112,0.9031276,-0.5799124,-0.821646,-0.8523292,0.25625984,0.7873064,0.06089092,0.9014334,0.1251122,0.6988056,0.222574,-0.9554542,0.496696,0.362036,0.9886792,-0.995424,0.415212],
[-0.38900908,0.9885704,0.35124568,-0.9720448,0.54900392,-0.7903328,-0.21007496,0.08452676,0.5201888,-0.5811408,-0.22378092,-0.8270832,0.6111452,-0.9432356,0.4079976,-0.568868,-0.6722718,-0.1173161,-0.06942968,0.2265798,-0.8216892,0.70902016,-0.9510456,0.8575664,-0.9341304],
[-0.38094008,-0.9746992,-0.8980248,-0.065259408,0.52933264,0.0101174,0.6546816,-0.7378268,-0.002791055,0.010100052,-0.6218772,0.0459688,0.748298,0.411666,-0.8604732,-0.6825398,0.8719454,0.419421,0.0732678,-0.17776112,-0.10894264,-0.982084,0.9718128,-0.9678448,-0.8730072],
[-0.3804436,-0.24035528,0.18708568,-0.31172816,-0.39483168,0.04528708,-0.26352624,-0.38709944,-0.12563904,0.37518724,-0.018266396,0.09743884,0.15075844,-0.22718724,-0.038945596,0.0279721,0.3099152,-0.13717038,0.0868628,-0.017307058,0.39139628,0.26546872,-0.36706736,0.2716328,-0.045854184],
[-0.37764572,-0.19003624,0.39250296,0.5374372,-0.68419528,-0.8330596,-0.0994058,0.4322356,-0.5059472,-0.9761608,0.34992076,0.8454584,-0.61659,0.26782256,0.33100228,0.3296368,-0.08737688,0.8752598,-0.6523858,-0.940141,0.629566,0.9215056,-0.08483256,0.29643328,0.67894144],
[-0.36920384,-0.73025048,0.21696824,-0.56827128,0.35955048,-0.28905464,0.8971552,-0.9544188,0.7013516,-0.7158952,0.6200364,0.9141908,-0.6323168,-0.36046748,0.0532254,0.626388,0.5316466,0.4287318,0.72803,-0.4754926,-0.5783076,0.8426824,0.3784288,-0.41444464,0.16903808],
[-0.36423952,0.910536,0.10455168,-0.74463456,-0.79402808,-0.22354372,-0.29540924,-0.4550384,-0.34949432,0.4402304,0.10582908,-0.8481812,-0.452196,-0.6774412,-0.797214,0.8886668,-0.319878,-0.7346628,0.16803058,-0.7372344,0.19075408,0.832992,-0.9069448,-0.72095328,-0.001908006],
[-0.3639522,0.21397056,-0.2185032,0.16224736,-0.049038944,0.1434204,0.003365462,-0.12616736,0.25100368,-0.29928368,0.16112432,-0.24298532,0.21128004,-0.12401924,0.31472704,-0.05232178,-0.2003772,-0.3805016,-0.12956894,0.2937596,-0.030371856,0.29144368,-0.26819568,-0.3170836,0.30693096],
[-0.3564962,0.030647312,0.943392,-0.56119904,0.27311976,-0.5392316,0.18354088,0.35665672,-0.6877316,-0.6759188,0.981606,0.32767516,-0.901406,0.352109,0.4307332,0.08101382,-0.4662568,-0.7070056,0.7970966,-0.3704682,-0.34056484,0.2099048,0.047132536,-0.53183752,-0.51256296],
[-0.34929452,0.11971912,-0.66193704,-0.24605024,0.72327008,-0.4539032,-0.897284,0.4283912,0.7728188,0.6894548,-0.5806572,-0.30047964,-0.699096,0.7262424,-0.6321956,-0.3300522,0.9321038,0.4443802,-0.9842946,-0.750679,-0.21548496,-0.36169816,0.8992448,0.36208536,0.15265568],
[-0.34843032,-0.44959784,-0.3523776,0.0682408,0.17289688,0.34302328,-0.6394756,-0.7429732,0.2190414,0.4940352,0.6768608,0.14216892,0.6827372,-0.4806832,-0.6613636,0.4907912,-0.5228942,-0.608275,0.7805388,0.9532426,0.29132788,0.9675168,-0.95864,0.2783264,-0.896148],
[-0.34674832,-0.9735344,0.57923128,0.68423608,-0.27467048,0.15970864,0.18740088,0.6894544,0.4799052,-0.9912672,0.9308912,0.21019604,0.7886416,-0.4731912,-0.7314732,0.5130882,-0.10505682,0.08024388,-0.7099572,0.3822892,-0.21969,0.6038592,-0.9366984,-0.34263448,0.52604208],
[-0.34657268,-0.10644512,0.70035384,-0.18971528,0.8526112,-0.4953884,-0.12701304,0.5985808,0.4644968,-0.18097444,0.09043556,-0.6753624,-0.8565428,-0.9620052,0.4563892,0.2746908,0.9449662,0.6211954,-0.8079586,-0.9990832,0.18267304,-0.19787232,-0.8830328,0.9153104,-0.21554072],
[-0.34295656,-0.35451624,-0.34971904,-0.14454136,-0.8675952,0.9644936,-0.65347,0.69763,-0.4458144,-0.32541904,-0.4353316,-0.30708556,-0.791744,0.8315156,-0.9469616,0.6570196,0.5836888,-0.6807582,0.2510628,-0.6406148,0.4891212,0.47521784,-0.104064,0.57162264,0.9613344],
[-0.33225056,0.21102824,0.21284808,-0.006272635,-0.31469568,-0.22710444,0.27177732,-0.22985748,0.08994788,-0.39697148,0.12679596,-0.000723157,0.25481548,0.20165952,-0.23190756,0.1424827,-0.09663408,0.2336402,-0.3697322,-0.04728374,-0.12211648,-0.22010872,0.37714176,-0.33810128,0.25864288],
[-0.32732088,0.443846,0.4702856,0.09462472,-0.916792,-0.9244884,0.4659484,-0.05416096,0.819684,0.8558308,-0.4201664,-0.3440692,-0.07885908,-0.9854088,-0.30678536,-0.6819138,0.3863054,-0.5738638,0.9728402,0.9815554,0.04980268,0.8587232,0.37803016,0.26019128,-0.77827144],
[-0.32042664,-0.9761584,0.40208408,0.50381448,-0.15759984,0.5486408,-0.7093316,0.4817908,0.1092194,0.008192348,-0.5549964,0.08673344,0.23770224,-0.8226076,-0.592876,0.02670534,0.0328125,-0.9235552,-0.9904772,0.6955802,0.4651484,0.24244072,0.44491096,0.979964,0.578376],
[-0.31748124,-0.29520376,0.39297656,-0.74417712,-0.3929048,-0.27944152,-0.38178096,-0.518614,-0.4445124,-0.25545208,-0.8018352,-0.22296224,-0.18481076,-0.9072656,-0.39239092,0.7680446,-0.9675608,0.7340698,-0.02554522,0.457099,0.2892956,-0.69775456,-0.8945816,0.2041356,0.8453352],
[-0.31334172,-0.1361028,0.73341256,0.14271288,-0.28485336,-0.6313188,0.05549244,0.687442,0.18353784,-0.5702008,0.7615668,0.31620084,0.0804386,0.9036956,0.07609256,0.001638625,0.2164642,0.05024202,-0.9137774,0.04313734,0.19158716,0.47119296,-0.8394704,0.63733672,0.68951328],
[-0.31245728,0.23439144,0.073979872,-0.29983,-0.25180016,0.36005748,-0.2148282,-0.000266221,0.035763736,0.05094792,-0.13459412,-0.1170274,-0.24390584,-0.17416304,0.18637356,-0.15195402,0.05784452,-0.237649,-0.06435558,-0.2939834,0.11536032,0.15616744,0.16648416,0.13904072,0.070153664],
[-0.311682,-0.9179152,0.64719184,-0.36789336,0.3017144,0.4874424,0.7974288,-0.8956148,-0.039597696,-0.8248964,0.6305308,0.36210596,0.5880228,0.38266,0.24033864,-0.7737942,0.010526914,0.5558314,0.7093522,-0.03627364,0.8334164,-0.049719808,-0.73849992,-0.156276,0.73492704],
[-0.31136,0.31006544,0.23093032,0.37542112,0.2021724,0.13149604,0.10820436,-0.28599216,-0.30942392,-0.06457364,-0.19937996,-0.17003396,0.21892928,0.3704814,-0.21845352,-0.1730197,-0.010557242,0.0281424,0.294469,-0.03368482,0.30280424,-0.37793464,-0.12090888,-0.10428296,0.31020928],
[-0.30976536,0.21718888,-0.12992272,-0.33863256,-0.30224368,0.39454616,0.14300516,-0.39053652,-0.34467668,-0.29542696,0.25998376,0.37226956,0.20200932,0.29466988,0.11104392,0.05537792,-0.2465706,-0.291373,-0.3703854,0.2320754,-0.1090656,-0.37945048,-0.17460392,0.30350784,-0.1862816],
[-0.3062938,-0.071474376,0.12423064,-0.5970848,0.18670448,0.39190352,-0.6746788,-0.1279026,0.4648372,0.836506,-0.671958,0.6144372,0.682954,-0.681544,0.8655632,0.6443836,0.7957956,0.5210904,-0.8722242,-0.5011504,-0.7518636,-0.76144104,-0.8679624,0.70076848,-0.34057584],
[-0.3051032,0.31862456,0.8612576,0.49666056,0.21564936,0.4545916,0.17208148,-0.38256556,-0.7043776,0.9570764,0.9642024,0.19808828,-0.703674,0.5533124,-0.6719936,-0.16471746,0.205283,0.5912752,0.7277352,0.8966446,0.8887612,-0.19610984,0.1123,-0.9300352,-0.74684736],
[-0.30281636,0.95624,-0.62687992,0.11982256,-0.51741792,-0.36616052,0.014973336,0.2303348,-0.8887812,-0.09907736,-0.04186212,0.4644044,0.05320472,0.39064456,-0.5314576,0.951342,-0.5912114,-0.19710886,0.6769188,-0.8492992,-0.04054924,-0.67021568,-0.15498384,-0.8386648,-0.26659768],
[-0.30263668,0.34886184,0.12268872,-0.26070928,0.11856232,-0.27585068,-0.2192544,-0.33820972,0.36668448,0.014662344,0.35965396,-0.31331128,-0.031802828,-0.1802102,0.17134752,-0.004411898,0.2017872,-0.3048654,-0.1825538,-0.267132,-0.39549888,0.1703568,0.07159204,-0.024393904,0.21138152],
[-0.28878068,0.24375184,0.26984736,0.44089176,0.9289,-0.21498664,-0.4700384,0.23064404,0.8865084,0.32018548,0.7211316,0.7533044,0.6711208,-0.6915924,0.9520308,0.5408118,-0.6635438,-0.19881848,0.6786428,-0.7030788,-0.34692492,0.46685088,-0.58564904,0.17215664,0.77718896],
[-0.28764908,0.25098024,-0.857,0.75945424,-0.064351368,0.5000984,-0.9520128,0.14190312,-0.9997756,0.9321524,-0.27785532,0.5087892,0.235802,-0.5746736,0.7426344,-0.05530892,0.10274614,0.8157696,0.4972576,-0.4304462,0.778116,-0.79878392,-0.8627208,-0.64007712,0.14921352],
[-0.28464276,0.04148112,-0.31743448,0.37227104,-0.063207168,0.12602576,-0.0985084,-0.23738804,-0.039815112,-0.05555452,-0.18821248,0.03323986,0.014416112,-0.21183064,-0.20171136,-0.248616,0.16811676,-0.06641466,-0.08321178,-0.03474712,-0.24376568,0.036938432,-0.35747136,-0.30963128,-0.23070952],
[-0.28463252,-0.944056,0.36769152,0.2659144,0.9826144,0.5415164,0.5684112,0.36695236,-0.8428444,-0.27216028,0.39933496,-0.23807832,0.023827796,-0.5012152,0.33336972,-0.9654208,-0.5735436,0.6970276,-0.9989124,0.7282122,0.12790448,0.46140072,0.61489496,0.8379312,-0.21661128],
[-0.28293112,-0.3734988,-0.609744,0.5126268,0.6418592,-0.880146,-0.6696604,0.6692732,0.09790444,-0.3341188,-0.23160944,0.23732036,-0.09700312,0.34094504,-0.32244548,-0.19479894,-0.0935501,-0.8013476,-0.4267176,-0.9866722,-0.5194248,0.54986872,-0.67320624,-0.75071536,-0.20425984],
[-0.28215936,0.25843544,-0.22119552,0.08166816,0.32201696,0.20007904,-0.1832016,-0.21954736,0.2280988,0.02622586,0.31836412,-0.25346168,0.26161276,0.0408846,0.19628404,0.05582724,-0.2010396,0.07672756,-0.2398,0.2577854,-0.16011176,0.037914608,-0.34815224,0.12760096,-0.13807872],
[-0.28174616,0.19217512,0.0643794,-0.30981112,0.16988272,-0.013722116,-0.20973792,-0.1999698,-0.12284908,-0.09978116,-0.33015276,0.32421068,-0.27389156,0.037102376,-0.13891732,-0.301263,-0.348435,0.240429,-0.06802004,-0.3857534,0.034014224,0.034634232,-0.2549132,0.21320256,-0.25172808],
[-0.28173668,0.2304656,0.22941912,0.07373184,0.13278888,0.23160856,0.035189164,0.28245052,-0.24910196,0.06679248,0.20769344,-0.17072524,-0.27586644,0.25706072,-0.13912244,-0.210179,-0.1159768,0.3009672,-0.05606324,-0.05576308,-0.18054576,-0.35173688,0.07000832,-0.36946448,0.35962608],
[-0.279113,-0.14703776,0.4139684,0.13537232,-0.1253156,0.6453072,-0.695376,-0.8412924,-0.10484052,-0.469444,-0.5719232,0.8697092,-0.37721116,-0.4623764,-0.613872,0.4120566,-0.1469451,0.2917676,0.13571042,0.9630362,-0.61,-0.67732984,0.7564332,0.37658072,-0.7979764],
[-0.27848944,0.8499168,0.27274464,0.76265912,-0.73301392,-0.023613364,-0.8520928,0.4390712,0.37126632,0.7035604,-0.5959744,0.03201156,-0.18813428,0.613688,-0.5585604,-0.7735524,0.4122672,-0.8254672,-0.09267522,0.06283518,0.2550838,-0.8597336,0.43505904,0.47938648,0.61359408],
[-0.27535944,0.15779368,-0.38714528,-0.13443952,0.38698472,0.15861816,-0.26112112,0.06898696,-0.14204492,0.33770376,-0.19930764,0.11363464,-0.24695776,0.032474752,-0.07901836,0.05578508,0.10481778,0.2357502,-0.02432754,0.3310284,-0.17856288,-0.1875352,-0.14627016,-0.1462804,-0.25828192],
[-0.27406196,0.46258712,-0.09210704,-0.63396136,0.50018,0.7746532,0.16772208,0.5401748,0.39814008,0.5796392,0.2989058,0.5968884,-0.5165136,-0.7256252,0.4469176,-0.18501742,0.4612872,-0.5719264,0.17888172,-0.9936454,0.10967808,0.57256808,0.36058096,-0.95106,0.43166728],
[-0.26533552,-0.3894912,-0.46058224,-0.29216336,-0.63029488,0.8315732,-0.4371068,-0.22831644,-0.6438928,-0.1412144,0.9486976,0.38810468,-0.37120968,-0.27441404,0.5529036,0.6598196,-0.4340458,0.351006,0.3145624,0.691159,-0.9142104,-0.8379664,-0.659286,-0.27873216,-0.2514784],
[-0.26219212,0.16561696,0.064668624,0.067752384,-0.31856472,0.06977832,0.29983952,-0.11492008,0.31991872,0.25086228,0.05737136,0.39719876,-0.039342864,0.29883936,0.25975992,-0.10695618,0.3575026,-0.21626,-0.2219078,0.3925682,-0.31574768,-0.047379768,0.27035032,-0.027594288,0.14486216],
[-0.2604808,0.46405208,0.08133864,-0.39169896,0.9608224,-0.27490552,0.3053426,-0.6035928,0.9437304,0.01411266,0.7132236,0.4848396,0.028462248,-0.8525096,-0.4922412,0.8739744,0.468447,0.9911136,0.3557382,-0.9741876,-0.4850172,0.60492744,0.9151072,-0.8623888,0.59513192],
[-0.2594694,0.21328512,-0.605048,-0.16075976,-0.011235432,0.7107448,-0.6780192,-0.15438856,0.8018596,0.6259664,0.7545748,-0.0625634,-0.55324,0.7050936,-0.31074568,-0.4505738,-0.8616994,-0.3051022,-0.9757578,-0.7219212,-0.9346504,0.64294376,-0.52351368,0.45324624,0.21346824],
[-0.25680416,0.03781828,-0.078263792,-0.1144172,0.002069921,0.17831828,0.36339876,0.35012684,-0.1109742,-0.20992876,-0.20391416,0.02469754,-0.31086452,-0.15322756,0.23094732,-0.07542172,-0.2114932,-0.2604162,0.3778804,-0.1920179,-0.39801148,-0.22889192,-0.1918216,0.37519672,0.08955472],
[-0.25518428,-0.08910696,0.003409125,0.26468752,-0.10386048,-0.23573644,0.32104572,-0.3943672,0.04703356,-0.18421296,0.17975432,0.23597812,-0.0619812,0.09857272,0.33668164,-0.05453592,0.258018,0.2120498,0.36455,0.07418152,-0.0768646,-0.008963272,0.15566208,0.16998512,-0.38728232],
[-0.25280672,0.8778,0.1255872,0.49034944,-0.76812624,-0.5066412,0.36643964,0.7329528,-0.4581888,0.11122676,0.35235824,-0.8840492,0.8295404,-0.6919656,-0.5975204,0.08676564,-0.5242096,0.9543966,0.3097602,0.9138474,0.5986504,-0.21663696,-0.37559968,0.23757304,0.13495672],
[-0.2526702,0.5931484,-0.56382208,0.17629208,0.9345344,-0.4295156,-0.8745592,0.23916668,0.6404376,0.5805064,0.5271684,-0.5001004,-0.7673608,-0.9378568,-0.8790064,0.11143734,0.506615,0.2218242,-0.228746,-0.3763516,0.9536508,-0.29606064,0.38985568,0.7876992,0.33603984],
[-0.25192636,-0.2700812,-0.46896232,0.35927248,0.067412576,0.6910096,-0.4115368,0.6118732,-0.7093824,-0.7524164,0.610098,-0.33057484,-0.620014,-0.562984,-0.7666852,0.7913108,-0.9018368,0.7495496,0.9081976,-0.7089638,-0.13297084,0.51976392,-0.01709356,0.8733712,0.16538344],
[-0.25099968,0.27209952,0.27703728,-0.069799344,-0.08061936,0.05609776,0.16186492,-0.31064904,0.18034568,0.19902304,0.35106908,-0.250502,0.32921724,0.19809208,-0.21519132,0.04436276,0.3711098,0.385298,0.18814126,0.2193188,0.25079756,-0.2085736,-0.042519296,0.28863328,-0.37613168],
[-0.24894804,-0.118468,0.15567824,-0.34921896,0.1643308,0.25279668,0.36768552,0.17995732,0.19514192,0.03340382,0.27728024,-0.26404556,0.30243076,0.36415668,-0.33059112,-0.261658,0.13476896,-0.1458396,0.3006098,-0.07349296,0.23063816,-0.32414064,-0.33177608,0.34170984,0.10984976],
[-0.24235952,-0.047911192,-0.29612648,0.09539608,-0.3210188,-0.033564568,0.1469612,-0.25364824,-0.3383354,-0.33534992,0.010740112,-0.14022636,-0.38826184,-0.3896424,0.22318012,-0.2945268,-0.3782128,0.2455198,-0.2596024,-0.17517956,0.31365888,-0.36101528,0.01162872,-0.11758056,0.11978392],
[-0.23595804,-0.25211704,0.54658,0.9869616,-0.8018592,0.19400056,-0.8828312,0.010056148,-0.32835972,-0.4572476,0.11899768,0.4364132,-0.4231976,-0.10730696,-0.33209088,0.8719718,0.5064194,0.0348556,-0.001896938,0.9355802,-0.7773556,-0.99124,0.16369368,0.65991232,-0.1219156],
[-0.2334474,-0.26203376,-0.29205192,0.058841184,0.20281072,-0.21501228,0.13409076,0.037458412,-0.08148248,-0.20682132,0.05490084,0.15034096,-0.31787164,0.38083076,-0.11994048,-0.03550646,0.0180636,-0.2609968,0.17473766,-0.16417622,0.22882472,-0.12545776,0.08491024,0.22753304,0.08118968],
[-0.22357404,0.32270376,-0.17735776,0.34149328,-0.11474176,0.35778056,-0.27481868,-0.06356092,-0.1387334,-0.0735644,0.38984328,0.22947116,0.036069744,-0.25508412,0.2591058,0.3016906,0.14620388,-0.3029966,0.18002058,-0.2517896,0.31758696,0.3600676,0.25893056,-0.22615544,-0.26911792],
[-0.22051052,0.2237,0.39948928,0.24310648,0.34475192,0.1832466,-0.27775136,0.14920756,-0.10894592,0.24130936,0.0383559,-0.04502768,-0.0728604,-0.19779416,-0.10985424,0.3608262,-0.378915,0.3765968,-0.2272374,-0.04992454,-0.22024496,-0.24331544,0.0646542,0.09637448,0.009961056],
[-0.21819732,0.06299044,0.055574872,0.36532424,0.33907048,-0.09093492,0.14826988,-0.09592316,0.34706228,-0.017440312,0.38386896,0.09271704,-0.022655948,-0.28305208,-0.36542292,0.395898,-0.008507956,-0.1755958,0.3795082,-0.3514816,0.2699102,0.19647632,0.33178448,0.23885304,-0.30221048],
[-0.21425216,0.67233504,-0.6890884,-0.22497624,0.49642728,0.6448784,-0.013968588,0.03644748,-0.7973828,-0.30456184,-0.1444554,-0.9797084,0.8551064,0.034934772,0.4497644,-0.4829022,0.9199126,0.5030532,-0.0958859,-0.612967,-0.2432474,0.62680456,0.19329824,-0.64395512,0.9135808],
[-0.21175072,-0.33273008,0.35385736,0.24759576,0.039328336,0.2566058,-0.09381152,-0.010194256,0.09803428,0.05725724,0.36242564,0.019898392,-0.26305916,0.11926828,0.031014944,0.3503532,-0.2937908,0.07088804,0.2135136,-0.10287602,0.35494508,-0.08157328,0.021534,0.16542736,-0.24586208],
[-0.21105804,0.32889512,-0.813532,0.76670872,-0.58618584,0.25941744,-0.813358,-0.21738608,0.11321336,0.8965576,0.5969132,-0.037354752,0.6612804,0.22877852,0.8943908,0.9323772,0.7165624,-0.1137314,-0.8753668,-0.6499706,0.04036876,-0.1178128,0.06929364,-0.77619864,0.76883144],
[-0.20927212,0.14903712,0.72990176,-0.4392632,0.8413456,-0.5760944,-0.0974366,-0.06002384,-0.6353236,0.7907648,-0.5303632,-0.7311232,-0.9253288,-0.9914704,-0.556602,-0.9794218,-0.6675224,0.6421502,-0.3383582,0.13468964,0.4517584,-0.12705528,0.22918168,0.9982624,0.4403472],
[-0.2077442,-0.14306776,0.39756384,0.19246984,0.03646024,0.27618704,-0.11032728,-0.08558564,-0.17488028,-0.016821564,0.25835992,0.2955842,0.291269,-0.16533748,0.17991924,-0.2584512,0.04684112,-0.3239962,0.2941016,-0.05448168,-0.18564076,0.22069952,0.2446844,0.3191664,-0.21478352],
[-0.20582796,0.012647816,-0.29253168,0.14476192,-0.24797736,0.35497404,-0.12488132,0.22276272,-0.022871644,0.11073788,0.05440136,0.12874752,-0.36323836,0.2484956,-0.257357,0.013793294,-0.06052102,0.1162212,-0.2507938,-0.18445126,-0.1231522,0.39520528,0.2883776,0.054874456,0.22242808],
[-0.19779188,0.063648088,0.079657784,-0.37338832,-0.2501808,-0.1917088,-0.22237944,-0.0799534,-0.09474112,-0.000156892,0.34235628,-0.2073262,0.31954016,-0.20644232,0.24033684,0.16959726,0.265596,0.3117084,0.09907714,-0.07175826,0.28454944,0.27416448,-0.38468112,-0.044886904,0.16300512],
[-0.197138,-0.14745096,0.047821496,-0.3350744,-0.26047696,-0.09523324,0.2126592,-0.16857604,-0.24998648,-0.35065972,-0.2833648,-0.32232596,-0.015793332,0.24830348,0.31917572,-0.07015622,-0.348917,0.3711754,-0.320247,0.13984298,-0.38560256,0.0886528,0.077010176,0.30505312,0.031479],
[-0.19590596,0.044644768,0.37790968,-0.07727236,-0.63586144,0.2916898,-0.1238312,0.5044176,-0.11247308,0.7107328,-0.4685632,-0.4956428,-0.34905232,-0.9678608,0.22582976,0.901231,0.6049634,-0.3104894,0.09230736,-0.5701436,-0.3629234,-0.08586408,-0.155568,0.61851688,0.42816264],
[-0.19510552,0.847736,-0.36045656,0.08917968,-0.31270552,-0.26553724,0.900138,-0.4289452,-0.10321348,0.4976928,0.34966088,-0.10193192,0.16489688,0.18402468,-0.09974312,-0.237931,0.3446864,0.9010856,0.9731562,0.7241702,0.07842576,0.18550648,-0.9002904,0.18318376,0.10365248],
[-0.19190484,-0.43414208,-0.9474808,-0.27610232,0.182166,-0.21494952,0.9883596,-0.6183756,0.7490808,-0.08555984,-0.22020464,-0.311175,0.6334936,0.7686896,0.4088048,0.6933402,0.2995482,0.8755132,0.5786826,-0.474664,0.10271568,0.43377496,-0.33445736,0.48139296,-0.27230224],
[-0.19042508,0.071518048,0.35264272,-0.023326952,-0.21636088,-0.1612846,0.19391084,0.09794932,0.2494904,-0.028920236,0.32470868,0.07795396,-0.27613008,0.262213,0.004587656,0.18529622,-0.11598758,-0.308906,0.2149862,-0.16319228,-0.09473592,-0.2025324,0.052545792,-0.14957032,-0.31617416],
[-0.1855474,-0.027877392,-0.24304976,0.2277004,-0.08302672,-0.1662748,-0.05967976,0.399981,-0.05618392,-0.22001148,-0.2245554,0.21745872,-0.37235188,0.30744156,-0.33008172,-0.3184568,0.2370038,0.09252484,-0.2274544,0.2669948,-0.05176576,0.2369552,-0.075484184,-0.027813424,0.005025806],
[-0.18498264,-0.5636804,0.8590408,-0.1748472,-0.024725008,-0.3380038,0.5507956,-0.7652216,-0.7163812,0.8891216,0.9581756,0.34543616,0.08828384,-0.706762,-0.5525204,-0.16731448,-0.3194222,0.05239972,-0.13401308,-0.5771138,0.8900104,-0.1907984,-0.35859088,-0.39185112,-0.76648776],
[-0.18278928,0.1615516,0.24266952,0.031890432,0.938656,-0.8495608,-0.874324,-0.4734312,0.13124936,-0.5151048,0.8904684,0.36551824,0.8319548,-0.7724156,0.4253012,-0.105071,-0.13857178,0.6553432,0.5295278,0.9364974,0.6763524,0.005677741,0.49271496,-0.722284,0.08730496],
[-0.18257712,-0.777518,0.2790404,-0.65850936,0.58175208,0.134356,-0.4884548,0.8223328,0.37212848,0.6061492,-0.838186,-0.37094328,0.8370408,0.4254196,-0.477352,-0.2628664,0.3891382,0.3612978,-0.0571844,-0.7271772,0.36848448,0.9874664,-0.041850584,-0.8607088,0.4272776],
[-0.18151856,0.18594064,0.043008024,0.09607552,-0.018982208,-0.29964184,0.09472984,0.13793404,0.39279016,0.237258,0.33949596,0.08195412,-0.19753008,-0.07363124,-0.0780556,0.015163218,-0.2951864,0.1962602,-0.386502,0.15434264,0.07795344,-0.066479912,-0.14287752,0.071546992,-0.13742072],
[-0.17770412,-0.3410336,-0.1683284,0.26184232,-0.3722996,0.34225276,-0.28790876,-0.07575616,0.35323216,0.2867354,0.2432548,-0.10587252,0.20712992,0.032782836,0.36291008,-0.08311596,0.3797514,0.229108,-0.18744948,0.15048942,-0.14944464,-0.29648336,0.17993576,-0.3904652,0.18423752],
[-0.17662708,0.921592,0.871916,-0.9638704,-0.8960512,-0.18052364,0.62334,0.402372,0.467572,-0.39699224,-0.5879188,-0.4297028,-0.1817268,0.38126608,-0.8889796,0.04895222,-0.5256624,0.9507672,0.5736844,0.16075236,-0.33246516,-0.30054744,-0.68498408,0.11865968,0.14444576],
[-0.17280416,-0.10139824,-0.52166064,-0.26914736,-0.7380136,0.8036992,0.6911284,0.1247294,0.504974,0.42787,-0.6305884,-0.7570328,-0.19079396,0.5762824,0.13451788,-0.9160678,0.4692508,-0.8407786,0.8452296,0.9943664,-0.01376418,-0.71175632,0.013806152,-0.09710728,0.58461592],
[-0.17127984,-0.24354192,-0.12239,0.57407352,0.28454608,-0.509,0.5503308,-0.31758708,0.759114,0.36622368,0.14494064,-0.4942808,0.8095,-0.4520592,-0.35721132,-0.2519228,0.2632022,-0.3729846,0.9562244,0.312177,0.4353748,0.05711368,0.5597436,-0.19965312,0.21305352],
[-0.16979688,-0.60459888,0.59819528,-0.013373624,-0.18537768,0.7712072,-0.020541424,-0.6625916,-0.08019268,0.05857168,0.002858394,-0.6406328,0.9625144,-0.769644,-0.5311476,0.4741158,0.246197,-0.5761992,0.8951748,0.3105202,0.09744452,0.9921376,0.32425824,-0.27089136,0.024537176],
[-0.16516968,0.078444096,-0.28368376,0.0986664,0.30392768,0.09858376,0.28681992,0.18749172,-0.21427664,-0.11878168,-0.27900712,0.05760624,-0.28286888,-0.15900032,0.34859752,0.3404796,-0.16871702,-0.02522066,-0.08513078,0.0624079,0.39529816,0.03886948,-0.1801064,0.16731312,-0.31924544],
[-0.16476172,-0.70908112,-0.010748936,-0.9607672,-0.43567904,-0.06655308,0.26624104,-0.996718,-0.019227632,0.19655,0.849794,0.8575284,-0.282163,0.6348948,0.6468684,-0.2089488,0.4406372,0.6499286,0.10742072,0.329466,0.33289208,-0.006944509,0.11810152,-0.77697208,0.56725072],
[-0.16404436,-0.65160496,0.7726724,0.28105592,0.08175136,0.4041348,-0.0393407,0.27447884,-0.771178,-0.4397328,0.39638816,0.4327116,0.9277952,-0.9566496,0.7881436,-0.012791568,-0.6591264,0.9727056,0.564735,0.933426,0.9448696,-0.1324212,-0.010410536,-0.4280284,0.9481992],
[-0.1607252,0.79485168,-0.9743224,-0.9175256,0.61506816,-0.5281748,0.38003192,0.7115584,-0.5696816,0.27664376,0.38264572,0.32346744,-0.0594904,0.18456612,-0.5601236,0.1087101,-0.4606546,-0.2966168,0.1406998,-0.817831,-0.7014708,0.33034544,-0.79887464,-0.1904008,0.26711256],
[-0.1606296,0.8481792,0.9646248,-0.2998952,-0.73228872,-0.5750988,-0.923266,0.3730948,0.35554276,0.445978,0.4015452,0.39922016,-0.8822992,0.5300876,0.447116,0.3228266,-0.8892828,0.18374878,0.392798,0.8580786,0.2910658,-0.4353264,0.37960872,-0.63814688,0.9284864],
[-0.1587748,0.058521136,-0.34036808,-0.069091808,0.17435168,0.36859908,-0.27348588,0.32587572,-0.11012056,0.10324264,-0.2279602,0.37471284,0.10726108,-0.10287632,0.30197556,-0.14493276,-0.2216144,-0.15939522,-0.374316,-0.06290284,0.29158032,0.3279892,0.28549608,0.0882668,-0.15044784],
[-0.15606528,0.08817408,0.28997104,-0.14538424,-0.1811696,0.25485084,-0.00945642,0.32091864,-0.2195484,-0.20160476,-0.38231016,-0.1073664,0.36392828,0.38217952,0.18554176,0.1455157,-0.2639836,-0.2139488,0.2598814,-0.3378286,0.30239604,0.066478896,-0.24267632,0.2375244,0.2176992],
[-0.15247372,-0.51380232,-0.050391032,0.8555848,-0.77216152,-0.14389752,0.28333604,-0.8897036,-0.9524716,-0.509582,-0.5887448,-0.6582524,-0.846642,0.9716044,0.7800872,0.19135658,0.9349418,-0.16086268,0.13306372,0.2825182,-0.5557072,0.9491552,-0.40387448,-0.71841344,-0.7188992],
[-0.14898176,0.18604328,-0.73383536,0.19561912,-0.4726484,-0.7512828,-0.6201492,0.010500052,-0.5062128,0.9426484,0.19387116,-0.9626012,0.6373396,-0.9325208,0.9146184,0.4267506,0.952864,-0.10744966,-0.10552092,0.9701236,0.1771486,0.7445764,0.16323096,0.9979848,-0.27988088],
[-0.14737512,-0.38601136,-0.70646032,-0.24371856,0.12476488,0.6579816,0.4536072,-0.3304664,-0.7621744,-0.8605072,-0.559568,0.27500716,0.9751348,-0.5935036,-0.38738008,0.6697708,-0.579419,0.03931198,-0.8197462,-0.8884698,-0.21094128,0.13978824,0.64959376,0.33528112,-0.35851136],
[-0.1420064,0.9681936,0.72412648,-0.078677512,0.08188736,0.64102,0.8790216,-0.3591,0.78943,-0.898798,0.8420064,0.9112304,0.406568,0.8362236,-0.424212,-0.6727612,0.9916722,0.15763254,0.662857,0.3998922,-0.7213232,0.47409208,-0.8737304,-0.552264,-0.47873328],
[-0.14017332,0.12375312,0.11973232,-0.78611416,0.28349576,-0.5584224,-0.182889,0.4783308,0.039366068,-0.13090796,0.4475696,0.026125024,-0.2253456,0.6180264,-0.8996676,0.8525974,-0.6252968,-0.5253268,0.17221052,-0.268524,0.5818336,-0.61525336,-0.63134336,0.686856,-0.9115688],
[-0.13522052,0.9643536,0.44328136,-0.34179624,0.32591008,-0.7695904,0.4511548,0.36637168,-0.18987504,0.984972,0.20248536,0.37658768,0.30831388,-0.19540948,-0.6826908,-0.0920412,-0.6159172,-0.9457418,0.3633194,0.2160968,-0.482416,0.9330112,-0.9078224,-0.40711024,-0.3606968],
[-0.127437,-0.57415376,0.9767592,-0.804336,-0.24233632,-0.07917088,0.4797612,0.9216196,0.5869964,0.03486994,0.7772784,0.12858192,0.006966448,0.10600624,-0.47197,-0.487721,0.08961994,0.550669,0.3898868,-0.338278,0.51454,-0.3690876,-0.6146744,-0.8097536,-0.43510664],
[-0.12092752,0.849032,-0.71327304,0.21881424,0.786596,0.5459996,-0.5263344,0.8521228,0.1950598,0.5923116,-0.06823048,0.34014808,0.899722,-0.15357824,0.526542,-0.7742942,0.5148906,-0.4077256,0.02174822,-0.427311,-0.7469684,-0.31436776,-0.8178264,0.20243256,0.1671756],
[-0.11905584,0.62873424,-0.45503856,0.51874888,-0.9641856,-0.23757372,-0.1735424,-0.7364484,-0.030709176,0.09280972,0.5227144,0.9301132,-0.22145836,-0.9639048,0.26430016,-0.857616,-0.3781702,-0.7415594,0.18009006,-0.358467,-0.6391712,-0.067427952,-0.1309284,-0.67213016,-0.847304],
[-0.11897876,0.37027696,0.2121824,0.13370432,0.040510056,-0.20166932,-0.1668012,-0.141867,0.31083972,-0.36991876,0.24483108,-0.25472248,-0.036687008,0.39038624,-0.30571648,0.09831856,-0.2291496,-0.01238669,0.2555744,-0.02933696,-0.09987644,-0.14290736,-0.2636828,-0.16796352,0.016880128],
[-0.11753896,0.787064,-0.58035792,0.79643712,0.55709176,-0.00797822,-0.208746,-0.5859008,0.11885156,-0.8646992,0.23008024,0.23209648,-0.0195918,0.422116,0.442716,0.9145098,-0.10932638,0.8936812,-0.5838692,0.8180066,0.4799904,0.3634796,-0.57510344,-0.78429616,0.026000824],
[-0.11689668,0.2509276,-0.070568456,0.28179856,-0.13930272,-0.13623436,0.06503224,0.39507756,0.04359412,0.36177588,0.22389024,-0.12766752,0.33411484,-0.32462604,0.26022292,-0.2167004,-0.12321194,0.05623128,0.3815226,-0.2209814,-0.36448592,0.0996512,0.1401364,0.11797488,0.2134868],
[-0.11315964,0.2217128,0.44002208,-0.27810984,-0.18846856,-0.9650164,-0.3065392,0.7980028,0.30532608,-0.36317316,0.02757042,-0.5143504,-0.9149048,0.911546,-0.8251484,-0.8662198,0.9380926,-0.8946144,0.9407574,0.8643004,-0.8673316,0.08487032,-0.58929376,-0.23610704,-0.710782],
[-0.10360468,-0.1500644,-0.16237744,0.11728384,-0.26633976,0.12582708,-0.24835208,-0.28686816,-0.2899088,0.1499032,0.28353872,0.069895,-0.20678688,-0.035094172,-0.20519356,0.18094906,-0.376079,0.0412794,0.1262153,-0.17687664,0.09601908,-0.38371952,-0.23949552,0.12530088,0.074061536],
[-0.09487368,0.9646872,-0.42990584,-0.43605136,-0.13088776,0.6158332,-0.20785956,0.6103576,0.8001784,-0.567154,-0.29055256,-0.4454116,-0.659124,-0.5477528,0.9628276,-0.8858116,-0.6947688,0.25759,0.268571,-0.916536,-0.6958964,0.8749104,-0.57924096,0.9650072,-0.53038552],
[-0.09250868,0.2650692,-0.050881608,-0.012415536,-0.25994672,0.34887412,-0.14434044,0.2555818,-0.2825324,0.30560492,-0.16960756,0.27698336,0.23332744,-0.237866,-0.33728324,-0.18776466,0.09984382,0.3202236,0.17778248,-0.3030076,0.37665716,-0.37628088,0.38629976,0.022791672,0.3404556],
[-0.09059148,-0.43100712,-0.29204464,0.60959416,0.59624736,0.6540712,-0.33332876,-0.7348284,-0.426882,0.26295224,0.9510956,0.2552846,0.669472,0.016605164,-0.6056312,-0.9812836,0.5230824,-0.13070554,-0.9466232,-0.9077742,0.6567364,0.061882088,-0.9178808,0.70048888,0.579478],
[-0.08789604,0.70150432,0.9851704,0.33797104,-0.077144496,0.889118,0.05661224,0.14619312,-0.870594,0.8958688,-0.7730924,-0.7447828,-0.7757072,0.28995712,0.2928882,-0.455651,-0.6593138,-0.415461,-0.3104562,0.6760774,0.6365992,0.63291416,-0.16049304,0.8234384,-0.056915184],
[-0.08569752,-0.2632916,-0.8722128,0.60960912,-0.28865144,-0.704086,0.8299756,0.5492568,0.659226,0.26679768,-0.33379448,0.38680044,-0.37390468,0.18493864,0.09998692,0.455108,-0.02465644,-0.6326296,-0.5993638,0.11933472,0.7947204,0.829568,-0.21211016,-0.47487504,-0.328412],
[-0.08554544,-0.9427696,0.66853832,0.838028,-0.43098192,-0.36921072,-0.4960256,-0.018608968,0.30763908,-0.5504848,0.7376096,-0.598866,-0.993428,0.8153388,-0.15210504,-0.2080624,-0.8600686,0.5636722,-0.7331118,-0.367267,0.5796496,0.56681928,-0.102094,0.9438632,-0.44841904],
[-0.08497392,-0.39920568,-0.034090384,-0.30390288,0.23221728,0.1115104,-0.13808304,0.33245248,-0.06707216,0.0528438,0.10725144,-0.22535376,-0.0468342,-0.16377364,0.13310292,-0.01184271,0.3119688,-0.08620102,0.2345442,0.10421108,-0.20186,0.29538768,-0.11118328,0.37585712,0.13173184],
[-0.0787502,-0.31680968,0.68653568,0.6746732,0.51605792,0.6176272,0.6513772,-0.415108,0.02800788,0.7468044,0.9895236,0.09951264,-0.15392684,0.028152064,-0.8731604,-0.012661944,-0.250177,-0.3643994,-0.6724736,-0.2805494,-0.5347556,0.983472,0.52721888,0.58705304,-0.8634968],
[-0.07742116,-0.000108005,0.20264232,0.17366432,0.8353712,-0.4412904,0.2106774,0.23617344,-0.67699,0.5778964,-0.7698268,0.4414552,0.4117324,0.17868904,0.9910016,-0.9720596,0.246764,0.09405492,-0.08382832,0.7852174,0.86644,-0.9341288,0.12138912,-0.22544,0.54770544],
[-0.07360212,-0.49892688,0.97468,0.39668152,0.6381656,-0.6474916,-0.4399636,-0.21081496,0.28045224,-0.6849712,-0.7714788,0.1205222,0.3580966,0.36200172,0.4309788,0.498431,-0.519131,0.9146338,0.2257974,0.05190116,0.5253872,0.9423344,-0.43495504,-0.69165456,-0.1451484],
[-0.06981348,-0.25626736,-0.42756976,-0.36582264,-0.78795448,-0.468528,0.31934812,0.34000564,0.3014682,-0.09589952,0.33203648,0.7641284,0.25122928,-0.5778432,0.934668,-0.4296504,-0.4117422,0.2777354,0.3872164,0.5554818,0.5637972,-0.8085864,0.59577624,-0.23996984,-0.87364],
[-0.06350868,0.62819936,0.31731384,0.66402208,-0.2761208,0.4852568,-0.8157488,-0.9959104,-0.4347708,-0.6706452,-0.9836724,-0.23276736,-0.36364408,-0.6377988,-0.17626576,0.9166644,-0.3831048,-0.05140458,-0.9541068,-0.2694826,0.644376,0.27623024,0.3670288,0.8240032,-0.52991352],
[-0.0579382,-0.23100704,0.57604504,0.944576,-0.13046792,-0.30876544,-0.7631044,0.13876776,-0.3439668,-0.38410636,-0.0573358,-0.9974492,-0.27922644,-0.8842964,-0.8288524,-0.5814332,-0.9520884,-0.02009012,0.2414934,0.18434352,-0.24406888,-0.2582624,-0.49882096,-0.24926288,-0.34190952],
[-0.05148044,0.19589776,-0.016948104,-0.27660712,-0.37984008,-0.10138396,-0.17906668,-0.23547844,-0.032458008,-0.38513244,0.0535942,0.16260744,-0.21262248,-0.23630784,-0.04814532,-0.009061214,0.10973986,-0.09260414,0.09156328,-0.3800572,0.26972204,0.33671072,0.19646712,-0.010845424,0.09999184],
[-0.05003136,-0.02029056,-0.28732832,-0.072503128,0.3944608,0.09774516,0.37182012,-0.25886572,0.05178164,0.39092332,-0.227605,-0.11996508,-0.07559936,0.37708864,0.15262824,-0.1825259,0.3362374,0.19024668,0.11620132,-0.05010692,-0.281166,-0.021220128,-0.206292,-0.029076376,-0.0910056],
[-0.04624124,0.641152,0.17820472,0.8963152,-0.60075432,0.27486972,-0.17783524,0.979542,-0.8427604,-0.9702744,-0.18544088,0.7612084,-0.7568192,0.39084912,0.4868228,-0.02373282,-0.8641148,0.015216606,-0.317805,-0.9796482,0.5721952,-0.11780464,-0.8370952,0.5817472,-0.5866392],
[-0.039158676,-0.37336016,-0.28370584,-0.20612968,-0.227544,-0.12271924,-0.16696792,0.2579468,-0.07082984,-0.001932322,-0.24098524,-0.18500288,0.28774408,-0.085344,-0.10250196,-0.3729924,0.3919166,0.2634008,-0.2212832,0.2672122,-0.05922616,0.2314956,-0.349806,-0.009518064,0.27573056],
[-0.033041744,-0.65541656,0.30717864,0.74276376,0.1345588,-0.7978448,-0.6317012,-0.5584964,0.7527012,-0.765708,-0.5972268,0.5420876,0.31413308,-0.24811804,-0.05871244,0.291622,0.2657408,0.837245,-0.448887,-0.3405756,0.8224152,-0.3058936,-0.50541496,-0.79317472,-0.72795128],
[-0.03231222,0.95036,0.8028296,0.37781592,-0.42827184,-0.037972852,0.27646976,0.142319,0.18920224,-0.22135928,-0.34963616,0.5830988,0.9781332,0.21854092,0.8408052,-0.761179,-0.6415114,-0.5618,0.5898468,-0.5027876,-0.8731268,0.45193384,-0.76913856,0.059693712,-0.45521704],
[-0.029579204,-0.65984456,0.8239232,-0.65191656,0.850748,-0.5822012,-0.4442292,-0.8339644,0.5025284,0.05831688,0.7105236,0.10490264,0.461228,-0.4665324,0.12711564,-0.4175064,-0.8374386,0.2870572,0.8139956,0.5100586,-0.4830784,-0.78018952,0.2018708,-0.9483432,-0.39313984],
[-0.025849676,-0.20599408,-0.32823536,0.38048984,-0.13675632,0.16023376,0.29762224,0.30764272,-0.07516968,-0.30783604,0.37024544,0.024047028,0.17154,0.3950634,-0.014417296,0.3999122,0.2840624,-0.3239198,-0.19403478,-0.3001122,0.028655076,-0.029909936,0.37197912,0.26493488,-0.358344],
[-0.02288724,-0.13957424,0.21620368,0.023812016,-0.8467496,0.6742064,0.26268584,0.23335248,0.5483236,-0.761328,0.15348196,-0.7459588,-0.9230208,0.28645324,-0.5084764,0.11647918,0.781055,-0.2589396,0.3787166,-0.3564598,0.39209564,-0.27192096,0.47048016,-0.23960648,-0.18584696],
[-0.018261384,-0.1213956,0.008005224,0.15790632,-0.2510628,0.3719932,0.36474728,-0.35148268,-0.1081982,-0.0657126,0.06191156,0.30232604,-0.20327884,0.16070156,-0.35482932,0.2959782,-0.3055214,-0.2997904,0.215883,-0.07968188,-0.17823652,0.30390736,0.25039792,-0.010345528,-0.20351408],
[-0.015871608,-0.24732824,0.24491728,-0.4137092,-0.72460232,0.005893524,-0.14003432,-0.23042108,-0.4744324,0.37829148,0.6115476,0.6226,0.550688,0.1230042,-0.5737228,0.973764,0.2142392,-0.3266958,-0.7394538,0.8052924,-0.39583212,0.18979016,0.72699568,-0.76336872,-0.8387304],
[-0.011779968,-0.5639384,0.71341736,-0.007095397,-0.42070584,-0.35309616,-0.4629232,0.31721604,0.8096024,0.6023992,-0.9341508,0.9169556,0.9865228,0.38142232,0.07072296,-0.8546764,-0.3012708,-0.449503,-0.6678058,-0.5057264,-0.4057104,-0.16871528,0.55531864,-0.11600384,-0.24292048],
[-0.004094104,-0.21274304,0.17413648,0.58600448,0.47767128,-0.8370772,-0.4639412,0.5369044,0.6492664,-0.4279928,-0.8146776,0.841708,0.5177728,0.06184064,-0.32424644,-0.8242896,-0.3933084,-0.2430852,0.4551622,-0.2084672,-0.8640692,0.50927824,-0.1697996,-0.60640944,-0.8852112],
[0.003048136,0.21032008,0.38832872,-0.38161824,-0.8302344,0.6123792,-0.2954794,-0.8552476,-0.30692208,0.8569436,-0.489626,0.5386572,-0.614456,-0.13222112,-0.020026436,0.8590158,0.781548,-0.02936088,-0.7596974,-0.6587568,-0.8733244,-0.29324944,0.9765816,0.2866332,-0.04623972],
[0.00855144,0.04949448,0.2448128,0.35774784,0.121002,-0.33738976,0.30358316,-0.06176048,0.36617184,0.3065716,-0.05703204,0.3515576,0.37289092,-0.2627102,0.29780176,-0.17089666,0.11514842,-0.19279522,-0.12039512,-0.1960668,-0.34010044,-0.32569176,0.3819352,-0.24417496,0.38460552],
[0.01774548,0.9357296,-0.811212,0.44921408,-0.10627416,0.9322908,-0.977506,-0.6376924,0.6806376,0.12556024,0.31432788,-0.6349912,-0.7553624,0.706994,-0.6275644,0.2704318,-0.6029676,0.4496152,-0.8963556,-0.9607236,0.7896764,-0.58695632,0.054108528,-0.08178944,-0.8222784],
[0.0286809,-0.56265552,0.69713968,-0.061009504,-0.8733416,0.9983768,0.022685324,0.30523012,-0.07063436,0.3594252,-0.7848084,-0.6702664,-0.4446996,-0.002623558,-0.8538028,0.06389342,-0.2023238,-0.4413354,0.818707,0.2207098,-0.26120464,-0.8177376,-0.08078896,-0.046295664,-0.9006536],
[0.029604172,0.24546336,0.16576608,-0.08718112,-0.24448272,0.28237512,-0.36518512,-0.030324404,0.00730868,0.12032244,-0.28878696,0.31362828,-0.33070772,-0.38574356,-0.05400932,-0.2387986,0.01497239,0.2574658,0.1067252,-0.335106,-0.25059904,0.37291088,-0.18466648,-0.28729664,-0.26590776],
[0.030310224,0.9172968,-0.8414776,0.6951452,0.43787816,0.06213208,-0.3667768,0.9769992,-0.9192448,-0.4282364,-0.17826568,-0.019969644,0.7819532,-0.97944,0.7930804,-0.552616,-0.5595884,-0.6472816,-0.486738,0.9735008,-0.4533128,0.46444416,0.1824048,-0.9896272,0.36232184],
[0.031274352,-0.1849092,0.8991448,-0.29473448,-0.9990784,0.59353,-0.01693018,-0.2628208,-0.8445612,0.9979976,0.86101,0.33647972,0.7764104,-0.79409,-0.8008536,-0.9977002,0.7605006,0.7044062,-0.3897856,0.9053344,-0.0945986,0.61400912,0.044923344,-0.78885944,-0.60350536],
[0.033540012,0.9228792,0.60977936,0.576568,-0.75024592,0.18618156,0.21217924,0.422904,0.702964,0.4086244,0.5190264,-0.004983032,-0.6991284,0.5582884,0.8330996,-0.04658914,-0.827279,0.15857236,0.7431674,0.02906884,-0.30655444,0.74129816,-0.22139936,0.910368,0.05242912],
[0.05364796,-0.72562248,-0.10259744,0.20125744,-0.40473648,-0.7209696,0.8366068,0.527864,0.4370456,-0.6391896,0.1194684,0.80524,-0.0654162,-0.4192752,-0.7007472,0.821219,-0.975382,-0.3188882,-0.9089218,-0.10825854,-0.29424652,-0.66788816,-0.91276,-0.034155808,-0.63408864],
[0.05377176,-0.02582612,-0.27920816,-0.2378972,0.29459368,-0.26903112,0.14081168,-0.24186684,-0.13072088,-0.25722448,0.22649828,0.23183332,0.2820036,0.14248408,0.039070996,-0.05611298,-0.18679004,0.2593072,0.2706964,0.02085142,0.2530998,0.26696968,-0.29961088,-0.32910496,0.011826072],
[0.0544348,-0.8263728,-0.79125232,-0.2355808,0.671994,0.2642318,0.826416,0.65738,-0.627702,-0.21083572,-0.9911488,-0.947774,0.423218,0.8773156,0.2375284,-0.4915022,0.6170952,0.9919102,0.9960544,0.5491064,0.5521196,0.51456232,-0.12157008,-0.3957284,-0.11745368],
[0.0545224,0.07428532,-0.56195992,-0.3814896,-0.59203432,0.25482716,-0.6487696,-0.19417588,0.3916264,0.407792,-0.7084112,0.35889804,-0.4387104,0.04292772,0.7868276,-0.07257586,-0.264602,-0.9395136,-0.8049516,0.01806124,-0.4709652,0.22176456,-0.71528064,0.74319608,-0.8490856],
[0.0584042,0.39813464,0.9111936,-0.15215592,-0.79066168,-0.004172236,0.7332888,-0.604832,0.792826,0.29209104,0.16078768,0.5953232,-0.8066604,0.7325032,0.9148332,-0.5723718,0.5750506,-0.9847076,0.8704364,-0.9159616,-0.859706,-0.8606544,0.9093096,0.15003368,0.43639728],
[0.05889864,-0.49677616,-0.6058988,-0.75063376,-0.3045512,0.5688536,0.7316744,0.9467532,0.5405176,0.6745412,0.81183,-0.6266456,-0.7809808,-0.020997344,-0.363165,-0.05858284,0.3862084,0.7742456,0.8626214,0.2372274,0.01043208,0.64757576,0.08227952,-0.53561192,-0.48058184],
[0.06016664,0.37788408,-0.09393448,-0.003435,-0.08645664,-0.020066324,0.057687,-0.21095652,0.33676872,0.22688052,-0.27244192,0.1448268,-0.31513556,-0.11336088,0.37734984,6.32E-05,-0.10891276,0.3505862,0.04802368,-0.15506636,0.2073268,0.10908656,-0.24544072,0.21338768,-0.19085008],
[0.06032308,-0.51333936,0.32216048,0.8739936,-0.37112248,0.93103,0.4256544,0.6252728,-0.9382872,-0.8731544,-0.24362144,0.8979096,0.21029944,0.5340436,0.7752452,-0.3979462,-0.17413872,0.006229346,-0.9998594,-0.5138988,0.4837196,0.13518192,0.873496,0.2026928,-0.14364392],
[0.06376048,0.12211448,0.34575264,-0.10213152,-0.046375216,-0.19114228,-0.07143976,-0.10083452,0.19526156,0.39971636,-0.07700552,-0.15912204,-0.22107696,0.1575332,-0.06105672,0.04013536,-0.10090756,0.3944994,0.14914278,0.2115616,0.39027912,-0.16147648,0.28938568,-0.39164912,0.21498728],
[0.06813604,-0.017531896,0.28552648,-0.23478952,0.02421852,-0.05165052,0.39644892,-0.34949548,-0.21350432,-0.22959092,0.3350298,0.19779704,-0.2188258,0.22446728,-0.1795448,-0.3188586,0.09789738,0.12152466,-0.14764884,-0.0618788,0.11109576,0.21469032,-0.09507728,-0.24503936,-0.23521328],
[0.07155928,-0.057678184,-0.03833308,0.09159632,-0.36471496,0.00792398,-0.02582582,0.39405808,0.21089244,-0.33333308,-0.11364564,0.19452432,0.2360846,0.13255796,0.3399222,-0.313826,0.09326102,-0.3634296,-0.18111948,0.14376012,-0.19003548,0.20908544,-0.31914144,-0.008549808,0.28063184],
[0.0721582,-0.04138172,-0.54295552,0.9792392,0.9941008,-0.26373316,0.8606604,0.610654,-0.014370796,-0.4288976,-0.1677232,-0.7593324,0.5916976,0.6743572,0.6171176,0.7596772,0.2639394,0.15817754,0.08816004,-0.18933522,0.817716,0.9471152,-0.52290824,-0.9169528,0.45290616],
[0.07350796,0.15294528,-0.23337736,0.31399976,0.161714,0.29303996,-0.12776928,0.04124736,0.17148712,-0.18409856,0.38413852,-0.27068616,0.29472128,-0.13514612,-0.26096676,0.15553704,-0.010227186,0.19448274,-0.019453546,0.05163248,-0.07136924,-0.37353296,0.18980024,-0.14668744,0.10350768],
[0.074384,-0.5315328,0.077700016,-0.23192048,-0.23226056,0.6160464,0.8172936,0.3785022,0.019326512,0.6999468,-0.5660948,-0.0790338,0.187862,0.32542408,0.7314448,-0.2907006,0.6972486,0.671663,0.15367698,0.7305784,-0.22669996,0.1661512,0.5783856,0.70975472,0.58484496],
[0.07897328,0.041212232,0.3434068,0.33607096,0.061934744,-0.12691276,-0.13764684,0.18797248,-0.14190008,0.032364032,-0.17595892,0.09530664,-0.09260576,0.24169656,0.05884048,-0.14622648,-0.06822938,0.008148702,0.2994498,-0.17682438,-0.17636548,-0.34325352,0.38978736,-0.051928656,-0.0823828],
[0.08155456,-0.09751536,-0.3853832,-0.2004196,-0.08554848,-0.010842744,-0.11004908,-0.39258128,0.035443184,-0.1417462,0.20882872,0.025056476,0.078965,-0.13398988,-0.13082764,0.05415428,-0.2088494,0.08173474,0.08798012,0.3777608,-0.13104364,0.20251032,-0.36452,0.212024,-0.2460848],
[0.08271312,0.97854,-0.36123072,0.42002176,0.23767952,-0.9398336,-0.29964068,0.13754688,0.6820888,-0.11641104,-0.17226212,0.33122616,0.4905464,-0.9280548,-0.634012,-0.5869364,0.0751404,0.12315704,0.7833276,-0.8393736,-0.26711784,0.8336184,0.47820176,-0.34192976,-0.0344614],
[0.08500444,-0.23598544,-0.20550272,-0.08211696,0.23593344,-0.25852224,0.04195912,0.09974664,-0.23804784,-0.3297454,-0.15057828,0.16289044,0.36409576,0.34889884,0.34810672,0.02420464,0.09700994,-0.3098208,-0.3361868,0.3193936,0.19685228,-0.19023536,-0.1131716,0.2182824,-0.09623176],
[0.08970716,-0.75483976,-0.188232,0.69289472,-0.26947136,0.22146532,-0.539478,0.5129184,0.22578316,-0.25484008,-0.8429156,-0.2321628,-0.4191652,0.947682,-0.4789184,0.613087,0.9174904,-0.3813282,-0.7653962,-0.9215414,-0.6881856,-0.35995416,-0.20377576,-0.66048232,-0.51340208],
[0.09105696,-0.29001616,0.68338312,0.17421144,0.8931584,-0.38279172,0.6818712,-0.3878716,-0.12899536,-0.9673112,0.05461228,0.38158684,-0.4250164,0.32917056,-0.897446,-0.759752,-0.0046318,0.6339036,-0.8747984,0.5487938,-0.06539948,-0.2959056,-0.63204488,-0.35385608,0.9339056],
[0.09110212,0.2220844,-0.10706808,-0.12993424,-0.04795404,-0.29843688,0.11111452,-0.29969252,0.04575864,0.35426164,-0.014103524,0.015950748,-0.02958838,0.031229388,-0.23294976,0.04555296,-0.3037418,-0.10876766,0.004816978,0.3381224,0.001246273,0.14515136,0.16914344,0.14709512,-0.24867608],
[0.0920278,-0.69580008,0.5297956,-0.06285,-0.62719448,-0.9708272,0.4387152,0.4929764,0.7118432,0.8330084,0.9223364,-0.8276408,-0.6176788,-0.5447636,-0.5835828,0.16910508,0.2606576,0.15018088,0.5630454,-0.8318828,-0.895636,0.40495096,-0.6183412,-0.16023208,-0.971028],
[0.09220808,0.31457656,0.06584116,0.054888328,-0.21238992,-0.028307388,0.22368284,-0.34395264,-0.34011324,0.301741,0.26268256,0.28064904,0.19677204,-0.36654756,-0.16837636,0.2369768,-0.15962968,0.07324446,-0.2749852,0.3550452,0.250116,-0.001284066,-0.23031336,0.30362168,-0.15753488],
[0.09689896,-0.52839,0.8109744,0.2670928,-0.9252672,-0.7465216,0.09047844,-0.5114288,-0.5905692,0.926514,-0.12816736,-0.06080492,0.9810588,-0.86347,0.9633312,0.7766334,-0.229741,-0.0687109,-0.0381497,0.02770088,0.12302848,-0.5468688,0.047994544,0.65363928,-0.32387048],
[0.09818244,0.79481968,-0.036840336,0.53311152,-0.31169104,-0.22165192,0.9860652,0.4293404,-0.433556,0.264994,-0.8037312,-0.04924912,-0.680158,-0.850212,-0.25874992,0.2419288,0.628714,-0.5270636,-0.6607708,-0.6595028,0.9805144,0.9637568,-0.52434584,-0.45752488,0.23863688],
[0.10060548,-0.44305648,0.6201572,0.41582032,0.52836848,0.34119176,0.8190356,-0.39076696,-0.34989804,-0.4843928,-0.8123924,-0.9986656,0.9114572,-0.949002,-0.5882524,-0.507077,0.0529455,-0.7048556,0.467493,0.2421938,-0.9804292,-0.048643272,0.12084552,0.016833592,0.49806432],
[0.1029744,0.009176384,0.1593244,-0.24558824,0.17533512,-0.1879884,0.33648464,-0.17339456,0.0490236,0.3794904,0.06322528,0.019810216,-0.09663376,0.3774994,0.04235428,0.3936348,-0.13138746,-0.333233,0.06651114,-0.3444608,0.028546952,-0.29036104,0.08956192,0.04623512,-0.012740792],
[0.10314892,-0.30821016,0.27515632,0.050052656,0.00921264,0.18796076,0.36380148,0.18532928,-0.14608272,-0.19802488,0.15324592,-0.10412644,0.1633828,-0.05285376,-0.004541852,-0.2691694,0.05668366,0.2058788,0.06580264,-0.3684524,0.35027748,0.25849144,-0.17062432,0.38845912,0.11708552],
[0.1080072,-0.38341096,0.29287592,-0.14816432,0.2374356,0.34619924,0.13963716,0.36252648,0.309846,-0.30472,0.38065944,0.07334292,0.25021696,0.23124044,-0.14005484,-0.199257,0.11365404,0.1259766,-0.000216332,0.16939874,-0.020392824,0.11162672,-0.29315344,0.063494248,0.31967104],
[0.11311456,0.68197544,0.53192024,0.38662008,0.33617,-0.6750904,0.7853452,-0.7413404,-0.4099284,0.9023048,0.9942896,-0.12100328,-0.4524216,0.6091128,0.06839416,0.5017004,0.9509634,0.2017328,-0.1921136,0.4421174,0.7549092,0.07603628,-0.7325032,0.8607752,0.3188316],
[0.11565428,0.27825552,-0.39658944,-0.10556824,0.33767208,0.1747874,0.11900296,-0.1567866,-0.029818544,0.086594,0.30032684,-0.12040144,0.19815748,0.3987824,0.31616496,0.2922896,0.2687432,0.17705646,0.3267354,-0.13134776,-0.29624432,-0.15627552,0.031926608,-0.15658416,0.16273984],
[0.1158062,0.21086144,0.3979456,-0.19744816,-0.061609464,0.09018472,0.30395352,0.23577188,0.05156336,-0.05285132,0.14745816,-0.24060424,-0.1783172,0.15628972,-0.11242212,-0.2273016,-0.3527154,0.07766464,0.02318554,-0.361054,0.028239828,0.29773032,0.162916,-0.16215072,0.23220864],
[0.117359,-0.11674552,-0.47353096,0.040721064,-0.6595736,0.9354032,0.05873472,0.023874944,0.02181486,0.018826884,-0.09425348,0.7135624,-0.4894436,-0.19693136,0.4160032,0.5315452,0.808442,-0.5672432,0.7360592,0.5791292,-0.71592,-0.3707164,0.61052688,0.960048,0.17754016],
[0.11744132,-0.50675632,0.12595416,0.9224384,-0.97022,0.33181804,-0.6788528,0.882248,-0.45012,-0.7954408,-0.15876636,-0.6788104,0.4868252,-0.6221332,-0.18377872,-0.5331082,0.9619202,-0.666095,0.22314,0.02015946,0.9625656,0.2028188,0.71703136,-0.9204408,-0.022708528],
[0.1184708,0.24493448,0.010580888,-0.2702972,0.26939672,0.9730212,-0.4103276,0.4956632,-0.7544372,0.28051104,0.4743484,-0.3159834,-0.016236064,0.0556828,0.8601744,0.2861728,-0.07036956,0.15584766,0.7664428,-0.12572402,0.8731784,-0.50918336,0.53121032,-0.66367776,-0.9199024],
[0.11991356,-0.38563816,-0.04418016,-0.2591552,-0.17766072,-0.11363644,-0.2163242,-0.16387784,0.3909392,0.360657,0.33450952,0.28332172,-0.16847564,0.36162824,0.3094096,0.2081822,-0.1561204,-0.08478264,0.392931,-0.0383229,-0.16821028,-0.32034032,0.21163888,-0.34276248,-0.25396136],
[0.12252732,0.328782,-0.37075728,0.018565496,0.259348,-0.32326876,-0.26745268,0.3034632,0.3669752,-0.16258896,-0.13190924,0.39760144,0.08410652,0.33827116,0.34071068,-0.09743996,0.3756474,0.19831672,0.02525626,0.2523824,0.1204728,-0.1422392,-0.3119268,0.26380416,0.32289552],
[0.12583224,0.16939984,0.056136,-0.4927148,0.9939888,-0.9694416,0.6245772,-0.26107952,-0.47613,0.7990672,0.4367176,-0.7618152,0.27712036,-0.9090492,-0.9310776,-0.2817106,0.9033254,-0.3580492,-0.8562436,0.9045932,0.5290252,0.26981232,-0.11172264,-0.428818,0.62172776],
[0.1266842,-0.35576056,0.33205664,0.9064544,-0.79308352,0.59053,0.7689212,0.891904,-0.0853512,0.6075004,0.5556296,0.6318928,0.7694132,0.38273916,0.054138,-0.4503804,0.8706438,0.6050968,-0.9386704,0.812894,-0.4408332,0.01646668,0.58984656,-0.41314864,0.28515904],
[0.12833856,-0.35762096,0.015473656,-0.1060348,0.69401048,0.907398,0.32129988,-0.6067208,0.09179196,0.15117032,-0.021097112,0.04339784,0.9259736,0.39348156,0.23544532,0.5687798,-0.5871238,-0.14355386,-0.6042724,0.808196,0.05701428,0.62087216,-0.48676048,-0.28994752,0.15383784],
[0.13010172,-0.13262864,-0.41622368,0.28012264,0.57041432,-0.770348,-0.8679968,-0.306119,-0.31713128,-0.905866,-0.9210744,0.5628864,-0.031021144,-0.6365928,0.19093936,-0.4000542,-0.8188294,0.4764056,-0.8638108,-0.5316352,0.37639124,0.8256368,0.31949944,-0.39599544,-0.15232512],
[0.13651716,0.814164,0.903776,-0.19498976,0.26202088,0.08114308,-0.9099912,0.7265172,0.6571056,0.8223848,-0.7562488,0.429614,-0.758866,0.9589,0.30485384,-0.2289434,0.18754282,-0.8204528,-0.16969662,0.2075188,0.34428828,0.32928272,0.902276,0.50734144,0.005324701],
[0.14152144,0.1508028,-0.6185596,-0.8722472,0.17429424,-0.28290876,-0.33029912,-0.6672552,-0.783798,-0.015895936,0.037242212,0.4592632,0.4113632,0.4921928,-0.1775254,-0.2639864,0.5207998,-0.6138134,-0.5327134,-0.6790862,-0.459432,-0.52424344,0.62775104,0.48025464,-0.46496344],
[0.14373732,0.12028216,-0.16584176,0.9572192,-0.37812968,0.8536704,0.11907972,-0.29398828,-0.8562604,0.9443016,0.13558416,-0.81664,0.407302,-0.9632532,0.7671052,0.0574238,0.6032886,0.8188064,-0.9464804,0.4084768,0.5178448,0.9101888,-0.67765072,-0.51738856,-0.51252288],
[0.14519708,0.56825408,-0.73078144,-0.007578869,-0.70049584,0.26948076,0.6751044,-0.19638704,-0.8789732,0.8150104,-0.8661392,0.4859248,0.25080836,0.24848396,-0.0622902,-0.9940772,0.803757,0.7574676,-0.29106,-0.09725838,-0.704656,0.08597472,-0.14789976,-0.5897528,-0.5132348],
[0.15003436,0.03296252,0.3960068,-0.35573144,0.35232992,-0.12244752,-0.35831824,0.09001492,-0.07812272,-0.29387324,0.15550804,0.19838256,-0.05669088,-0.39081656,0.021475232,0.2346932,-0.214401,0.3729092,-0.2179754,-0.09336184,0.2965188,0.049098,-0.008841432,0.076709584,0.31937056],
[0.152773,0.874964,0.14952624,-0.33605696,-0.36782936,-0.23490272,-0.01561014,-0.4535184,-0.18562976,0.480316,-0.9397084,0.29838256,0.441716,0.13930036,-0.1186058,-0.8792182,0.5924476,-0.293972,0.866798,-0.900891,0.26091716,-0.9688248,-0.48420584,-0.33876336,-0.09219512],
[0.15753984,-0.1881836,-0.71329648,-0.7021292,-0.18961,-0.9850448,0.37215004,0.0661602,0.05824544,0.06204456,0.5423752,-0.710054,0.16985712,0.6675368,0.8975004,0.3131202,-0.201708,-0.8274188,0.06553144,-0.10761296,0.5800044,-0.4046632,0.7712468,-0.9889064,-0.776844],
[0.15862516,0.69256496,0.77019376,-0.33216792,0.2820676,-0.8570684,-0.3056922,0.8258388,0.31919076,0.6193496,0.7051076,0.5358708,0.7958452,-0.7064464,-0.16734608,-0.7866222,-0.2184346,0.04336088,0.0812724,-0.7572574,0.8933256,0.47671536,0.8969608,-0.14207152,-0.0899124],
[0.16369608,-0.52895184,0.409592,-0.340418,-0.6170332,-0.4141336,0.7971312,-0.4499376,-0.4788556,-0.6632128,0.39820736,-0.24571348,0.8235664,0.6481064,0.7995508,0.005416158,0.03675246,0.14546786,0.6037974,-0.2759004,0.8296408,-0.8446472,-0.16201736,-0.31945416,0.9316536],
[0.17174468,0.62619936,0.8266032,-0.16883216,-0.26076088,-0.07590472,-0.9779124,-0.22196704,-0.24562792,0.9160284,-0.50427,0.7372024,-0.29704092,0.775994,0.06474376,-0.6016602,0.03457324,-0.606718,0.3942092,-0.1040242,0.4184164,0.3064108,-0.54441176,0.9316304,-0.095182],
[0.1728516,-0.2035132,-0.10376208,-0.2930404,0.30448032,0.002191444,0.38362268,-0.15592544,-0.23286536,-0.2415324,0.3293542,-0.181637,0.32321936,0.007093424,0.09052364,-0.10787728,-0.2921674,0.15764114,0.3618296,-0.1778714,-0.22435896,0.19306192,0.23027064,0.24586656,-0.27825952],
[0.17388716,0.34161296,-0.19342784,-0.1551672,-0.1042044,0.37305012,0.28050092,-0.18256344,-0.06871164,0.25822048,-0.25273748,0.15782356,-0.35485952,0.0013732,-0.13271844,-0.17115396,-0.17859832,0.12995636,0.2715732,0.06057104,-0.11486564,-0.13622232,-0.048031624,0.12609184,0.09554856],
[0.17726948,-0.9901144,0.056537064,0.9797808,-0.045304776,-0.9020568,0.38604584,-0.7259888,-0.666124,-0.8509976,-0.19795272,0.840622,-0.10471748,0.23133056,-0.14443456,0.6379718,-0.6336132,-0.7145558,0.02194998,-0.04587384,0.90757,0.19953088,-0.542772,0.1621568,-0.54064624],
[0.17881376,-0.8084232,-0.52106832,0.12152776,-0.9122504,0.6374928,-0.00433618,-0.4356996,-0.19745484,-0.8201056,-0.039025008,0.4978896,-0.5738812,0.4095768,-0.012415172,0.8380864,-0.6650638,0.7405472,0.4622952,0.7926294,0.29411264,-0.60639208,0.15737272,-0.66526632,0.36613144],
[0.18423888,0.25660328,-0.73880168,-0.9032176,0.77289672,0.37929728,0.6728704,-0.709018,-0.38561388,-0.4365376,0.98581,0.6730276,-0.8300956,-0.5918652,-0.34191216,-0.4353318,0.4136504,0.2489304,-0.56562,-0.2989244,0.24322556,-0.34215856,0.24800048,-0.000309087,-0.37768752],
[0.18647776,0.039544456,-0.015858328,0.05295468,-0.26792688,0.21513012,-0.26800052,-0.2750444,-0.011190928,-0.0937504,-0.30469732,0.15553188,-0.04917688,-0.2468186,0.04227892,0.3981272,0.3545084,0.19838456,-0.2482102,-0.17372708,0.07142616,-0.2398528,-0.23678408,0.074475168,-0.17951824],
[0.1883802,0.7116708,-0.34791464,-0.82294,-0.39798592,0.01342296,-0.528994,-0.9392508,-0.14051476,0.4872404,-0.748586,-0.7825536,-0.20321776,-0.1215984,-0.8322968,0.8900516,0.03217062,0.3757792,-0.2707922,-0.5842366,-0.8627296,0.71483352,0.8626968,0.24644744,-0.15846056],
[0.19330708,0.23662872,-0.1008252,0.074062464,-0.72685016,0.7521268,0.6228176,-0.4371224,0.970092,-0.002905618,0.28124972,0.22482756,-0.24958088,0.8936292,0.05168884,0.7675998,-0.6211376,0.15135438,0.3843872,-0.6990594,0.943574,-0.34323216,-0.30878552,-0.967,-0.8567112],
[0.1944968,-0.58572072,-0.05375676,-0.17124808,-0.37127536,-0.41714,-0.6705768,-0.9872472,0.515908,0.6535708,0.29070488,0.38583708,-0.9441536,0.824774,0.23603576,0.02057618,0.828108,0.15117856,0.9417496,-0.13329488,-0.5609684,-0.48392928,-0.08515096,0.60182448,0.45298216],
[0.19764816,0.70391896,0.8219688,0.6131796,0.54381256,0.4175996,0.3755204,0.3383722,0.7464948,0.11306764,0.6668168,0.8128556,-0.23823568,-0.7231788,-0.7569008,-0.5619322,-0.2199092,0.3740092,0.9500784,-0.6451296,-0.04475744,0.023148616,0.47774792,-0.018348608,0.48695328],
[0.20023672,0.68144456,0.4180672,0.4794412,0.86024,-0.09345924,0.9865216,0.00447986,-0.29863412,-0.8443432,-0.8498072,-0.37092032,0.18762524,-0.14866304,-0.9414276,-0.901675,-0.3524866,-0.678946,0.241856,0.6401366,-0.8663704,0.016626016,-0.22800032,-0.62206936,-0.4146328],
[0.20069128,0.2492892,-0.17489768,-0.31121912,-0.007181914,0.07880052,-0.3436184,0.14595636,-0.25506456,-0.26982624,-0.14143364,0.16645244,-0.27439592,-0.18125312,-0.15047896,-0.2650272,-0.3688106,-0.05491622,0.14022594,-0.2459934,-0.1548928,-0.24928896,0.21603,-0.16035744,-0.09493384],
[0.20969468,0.8793688,0.20072688,-0.6068016,-0.60545888,0.6283064,0.23428592,0.4001824,-0.3237856,-0.34589164,-0.4379392,0.922414,0.7077704,-0.5322816,0.23147352,0.7759154,-0.2061426,-0.5749748,-0.2007604,0.2719152,0.919068,0.39795896,-0.22437408,0.64963816,0.34330448],
[0.21047276,0.35211456,-0.405094,-0.8023992,0.72191256,0.6804848,0.6485612,0.517062,0.8310204,0.7892316,0.28802544,-0.8186296,-0.9088772,-0.6728444,-0.9408804,-0.3475466,-0.12209218,-0.3028574,0.2629894,-0.09214428,-0.920056,0.6571172,-0.31560336,0.54005104,-0.39064688],
[0.21095608,-0.26027408,-0.1498852,-0.31533064,-0.08450144,0.34900176,0.22434808,0.36626864,0.22478152,0.016138432,-0.20745624,-0.006700684,-0.25677728,0.09739876,-0.16051244,0.221181,-0.10208368,0.07153524,0.2254428,0.16761538,0.060666,0.3949896,0.29643528,0.39338784,-0.006165498],
[0.21290728,0.791004,0.9806224,-0.4221432,-0.73206776,0.35253492,0.3788036,0.9609744,-0.8675136,0.8129,-0.4774112,-0.672552,-0.04563844,-0.669956,0.7639232,-0.7404584,-0.7828472,0.8721672,-0.17637392,-0.627329,-0.12454716,0.2427016,0.09939272,0.39830024,0.31533144],
[0.21435444,0.48850384,-0.26032288,-0.41687712,-0.28545688,0.8456088,-0.5690284,-0.15248116,-0.09797684,0.05261488,-0.9537992,0.4292836,-0.10102204,0.830836,0.9760052,-0.05015692,-0.2214772,0.599732,0.4654138,-0.64035,0.012274404,-0.09948752,-0.755096,-0.17724664,0.11269856],
[0.22423024,-0.1137372,-0.36017328,0.39028544,-0.37054992,-0.07568856,-0.32604004,0.04110528,0.033860396,0.35424084,-0.12945304,-0.37863352,0.06134408,0.16254904,-0.36322712,0.3143144,-0.2355338,0.19042438,0.1047138,-0.08947806,0.280414,-0.28276216,-0.2422256,-0.28491712,-0.14613896],
[0.2391944,-0.38167864,-0.649308,-0.056899648,-0.3797736,-0.08931176,-0.10248888,-0.5035764,0.2826462,-0.7741212,-0.6311936,0.34044292,-0.489462,0.7883904,-0.013222536,0.4785092,-0.3065098,-0.8699666,0.27921,0.11171762,0.7114584,-0.11197136,-0.29767792,0.74131352,0.41104304],
[0.2399476,-0.06766556,-0.24765488,0.33420584,-0.11045592,0.1165744,-0.07527604,0.34734892,-0.02958776,0.29614412,0.19669872,-0.11543048,0.34171068,-0.23383348,-0.33533272,0.3455116,-0.05067296,0.3482102,0.09093642,-0.14324496,-0.3318188,-0.1617852,-0.054183592,-0.12362864,0.001303573],
[0.24300432,0.34761256,-0.14649512,-0.050478856,0.038685744,0.08932312,-0.1883044,0.27569672,0.17502312,0.35743924,0.26945676,-0.029148404,0.0885068,-0.06034984,0.08248048,-0.3774424,0.05898988,-0.2757268,-0.14232402,-0.3482044,0.22208716,-0.39111208,0.31690384,-0.2083532,0.25323608],
[0.24391296,-0.4642836,-0.76239208,0.23663632,-0.6761904,0.254722,-0.3754674,0.7512848,0.4887432,0.007091952,0.5502876,0.900584,0.5787864,-0.18768052,-0.2890364,0.4041988,0.4516136,0.898487,-0.12191002,-0.4026198,0.6512304,-0.978908,-0.7509456,0.073697048,0.09251632],
[0.2443016,0.8405624,-0.44431624,-0.8101768,-0.4555156,-0.24949072,-0.934738,0.52197,-0.38489292,-0.26507392,0.9650548,0.638588,0.17109884,-0.8097092,0.45685,-0.6375132,-0.18818532,0.9831504,-0.7018104,-0.07931134,-0.23936176,-0.68529024,-0.076323296,0.09692,0.8131168],
[0.2456106,-0.23985856,0.06645632,-0.25471288,-0.29184256,-0.30484176,0.18246124,0.10893692,0.2817952,0.011166428,-0.08282436,0.01102934,-0.009305696,0.09057376,-0.2259848,0.324949,-0.013788448,0.144861,-0.06051556,0.372832,0.35381532,-0.35468048,0.19687904,-0.350996,0.2835768],
[0.24723632,0.29713584,0.36561256,-0.1303056,-0.10040208,-0.19488516,0.22164072,0.21159684,-0.32683852,0.07106748,0.019096476,-0.26663956,0.16303332,0.30873512,0.3611894,-0.13967338,-0.2115534,0.3864706,-0.3875376,-0.0593077,-0.2469982,0.35038216,0.39604544,-0.031609024,-0.023183816],
[0.2529942,0.27819888,0.35742808,0.28348816,-0.17967168,0.06190804,0.25755912,0.06437396,-0.21105876,0.11645508,0.22631416,-0.23201428,-0.24927544,0.1980788,-0.205449,-0.2205872,0.10422914,-0.07315972,-0.06254996,-0.13421614,-0.12724392,-0.043108624,0.08099696,-0.30652872,0.16560504],
[0.25369972,0.10044992,-0.37331144,-0.21381312,-0.35935864,-0.11347356,0.18156912,-0.0401208,0.3657646,-0.030185288,-0.14907712,0.035592416,-0.09036864,0.0869136,-0.19257764,0.05751312,-0.000480662,-0.15145712,0.3194716,-0.3962576,-0.21446436,-0.10097256,0.35860704,0.060628536,0.016698824],
[0.25471368,0.1784632,-0.12084512,-0.36012944,-0.54867664,0.519376,0.6513,0.027115368,-0.6268392,0.22494652,-0.50847,-0.7871144,-0.17263988,-0.26989112,-0.6742932,0.19419394,0.9479082,-0.2346502,0.3599534,0.2850394,0.8876992,0.65397432,-0.40693512,-0.59016608,-0.61518736],
[0.25974476,0.56372104,0.1537784,0.2220624,0.44222728,-0.6582024,-0.380433,0.5643224,0.4275572,0.11818708,0.37398096,0.33312476,0.5434644,-0.032414212,0.23880388,-0.6381332,-0.920748,0.3140724,-0.3805474,-0.7568834,-0.8790588,-0.59036496,0.48166672,0.47427968,0.6650224],
[0.26195152,0.36903504,-0.4484228,-0.36340456,0.46565768,0.4502616,0.7175128,-0.34816856,-0.12355224,0.6521428,0.8876084,0.459702,-0.6288484,0.34633804,-0.5699312,-0.1157082,-0.483214,-0.7249296,0.3391742,-0.05862156,0.833096,0.901148,0.75989568,-0.55898448,0.049974408],
[0.26607172,0.19999664,0.09134224,0.037050208,-0.1562332,-0.017837184,-0.2749492,-0.0482218,0.36480536,0.0998716,0.25082964,-0.16238848,-0.38199248,-0.18916988,0.022029576,0.2437602,-0.12709868,0.11027128,0.0658134,0.2439494,-0.28698836,-0.23490048,0.024056112,-0.38408928,-0.29706432],
[0.26791116,0.8371456,0.10187496,0.59487144,-0.71061544,-0.7746236,0.11290728,0.6629668,0.24722836,-0.4326116,0.5853436,-0.033197772,-0.8700968,0.9224384,-0.007759864,-0.18812054,-0.4477082,-0.6794698,0.818467,0.7975836,-0.5048816,0.11553024,-0.026103904,-0.305986,-0.007594143],
[0.268991,-0.26788816,-0.76662384,-0.5133352,0.58310712,-0.7121968,-0.33784492,-0.7861184,0.8716096,-0.9493808,-0.9583252,0.5026748,-0.767794,-0.2798836,0.33210724,0.2066772,-0.8564306,-0.4861054,0.2756176,-0.8032512,-0.8569592,0.9657672,0.51169904,0.23836072,0.5599032],
[0.27093208,0.18252376,-0.35075664,-0.2900252,-0.12010608,-0.33617672,0.07662124,-0.003975387,-0.13345328,0.3939878,-0.38925232,-0.38219784,-0.026853852,-0.013853912,-0.13043076,0.2432256,-0.2784202,0.2675848,-0.2936942,-0.2061806,0.11168068,0.19470216,0.26644384,-0.02398164,-0.28251464],
[0.27324548,-0.78816968,0.2402976,0.54758432,-0.70348528,-0.13531328,-0.7955432,-0.7114468,-0.25700888,0.39089268,0.5961128,-0.3766022,-0.6870684,-0.6509752,0.20268948,0.10494608,-0.18530622,0.019983356,-0.14787444,0.365434,0.3319118,-0.69360296,-0.8487488,-0.50657432,0.1733228],
[0.27672724,-0.60616808,0.8299992,0.5791976,-0.8360432,-0.6774768,0.5249908,-0.8725984,0.15862232,-0.35615968,-0.9354808,0.4422996,0.06000544,0.8245568,-0.3072818,-0.5526758,0.621176,0.1599117,-0.19996796,0.2254632,0.34667008,0.30731376,0.69132176,-0.9304704,-0.50795704],
[0.2803042,0.56731488,0.005570091,0.076819488,0.34805432,0.477462,0.3549334,0.07682836,0.9692856,-0.005955636,0.717808,-0.8720548,0.030988,-0.2111758,-0.1347628,0.755631,-0.9183856,0.2579558,-0.7145682,0.776801,0.10408404,0.9446008,0.76336632,0.25550456,0.5938304],
[0.28162952,0.65439824,-0.74118384,0.44829472,0.8623392,-0.35372948,-0.585572,-0.08099012,-0.4345452,0.3333042,0.09934236,-0.148821,-0.26697084,0.8639764,0.6345472,-0.7888702,0.2594076,0.6984284,-0.4450076,-0.4424606,-0.7853196,0.9416656,0.44063288,0.076092088,0.9940376],
[0.28518412,-0.56096848,-0.26927808,-0.45860912,0.47983072,0.6731828,-0.4082204,-0.25084632,-0.25529696,0.19149748,-0.28028152,-0.8873032,0.5753388,0.9532576,0.5328256,-0.724228,0.722663,0.1306528,-0.16687274,0.3257516,-0.8896224,0.28334304,0.29992624,0.53850304,0.60401576],
[0.29500016,-0.9953744,0.36311784,-0.11304312,-0.9617696,-0.19196484,-0.7496784,-0.156686,-0.39775328,0.4824796,0.39881408,0.08677004,0.7389148,-0.6164836,0.9085092,-0.71356,-0.8706518,0.612498,0.332717,-0.19885078,0.5493384,0.5720916,0.29384696,0.9668744,0.79760224],
[0.2988982,0.31932336,0.73357712,0.5457956,0.29782232,0.36639096,-0.38807692,-0.7819436,-0.06522196,-0.772322,0.745738,-0.6012864,-0.0767406,0.499022,-0.23836316,0.3616788,-0.4190914,-0.1829769,0.7061902,-0.10219912,-0.317108,-0.9279792,0.19736648,0.11314336,-0.67648752],
[0.30261176,0.23071272,-0.47275432,-0.820632,-0.41657848,-0.5843252,-0.6858208,-0.27006908,-0.388776,0.5861616,-0.7488208,0.5313368,-0.726372,0.1675888,-0.27143024,0.3646926,-0.11325152,-0.4738232,-0.1850557,-0.4760996,0.2653246,0.5287596,-0.7708056,-0.5587592,-0.39856416],
[0.3032182,0.28029368,-0.012240088,0.18359992,0.3769556,-0.06520484,0.35642972,0.045813,-0.05489264,-0.29899624,0.25487724,-0.008185824,0.07742792,0.27591552,-0.011728852,-0.05979746,0.37921,0.2221826,0.2493574,0.06915056,0.28065536,9.28E-05,-0.22044696,-0.20027864,-0.31245176],
[0.30515524,0.65500208,-0.9391136,-0.65290096,0.78915968,-0.49878,0.7829132,-0.6018008,-0.9579528,0.33520236,-0.37759796,0.26664224,0.032928056,-0.4918372,0.016823172,0.7068984,-0.526233,0.7463906,-0.8264564,-0.9706854,-0.7767244,-0.8615016,-0.9679888,-0.53619976,0.54459136],
[0.30633372,-0.67768296,-0.9408424,-0.73523288,-0.8655312,-0.34307644,-0.6854804,-0.5653524,-0.23038912,0.9392368,0.5047208,0.36689352,0.006605888,0.9617492,-0.5779328,0.7819976,-0.3366994,0.8946144,0.4668594,-0.3280236,0.33796392,0.9870368,0.8264896,-0.9821864,-0.433964],
[0.31189632,0.45563896,-0.65881392,0.60324464,-0.09080032,-0.14857208,-0.999822,-0.9515164,-0.217767,-0.33254948,-0.8859732,-0.10864036,-0.9901212,0.9185776,-0.05747136,0.75466,0.4217686,-0.5184608,0.007529044,0.5829878,-0.6479648,0.67647192,-0.8923232,0.34879264,-0.19867864],
[0.31354556,0.4649572,0.17102696,-0.786998,0.56626512,-0.5280516,-0.5472916,0.07945824,-0.6812364,-0.6413424,-0.31015952,0.07737456,0.8697152,0.04761672,0.13565488,0.3878946,0.12011298,0.8546978,-0.4880116,0.814133,-0.4967064,-0.35271064,0.35803056,-0.9034288,-0.028032048],
[0.31499248,-0.19277456,-0.26560408,-0.13523168,0.14273448,0.034228104,-0.17781884,0.34080972,-0.05879148,0.08181576,-0.23384952,-0.23538552,-0.27816176,-0.00945736,-0.16251708,0.13619086,0.19877498,-0.2823344,-0.09753496,-0.3422254,0.0746756,-0.1377148,-0.19059832,-0.3501292,-0.3860456],
[0.31849,0.59400776,-0.8058088,-0.3422616,-0.56261952,-0.39418668,0.22861616,0.086857,0.8691092,0.5519836,0.9090028,0.6886932,-0.4470884,-0.14393216,0.24947832,-0.733219,-0.628255,0.7950824,-0.534485,-0.9489572,0.9627428,-0.58293176,0.10750744,0.019770208,-0.8597792],
[0.32617488,-0.12134816,-0.09296944,0.39771832,0.034386448,-0.38058332,0.19332576,0.20444724,0.17758284,-0.05344432,0.012693936,-0.001000235,0.12707796,0.38341916,0.39757016,-0.0344785,-0.2253878,0.07077134,0.03216314,-0.02672162,0.17420744,0.25226896,-0.2023328,0.3126904,0.23371],
[0.3264712,0.32549688,-0.000665771,0.11169728,-0.24215408,0.2404672,0.11610344,0.10576044,-0.30733564,0.07875052,0.30867368,-0.3207846,0.1170724,-0.30284332,0.23117164,0.0528881,-0.10629918,-0.2579402,-0.11762468,-0.02330926,-0.1846424,0.015431128,-0.34284184,0.21207752,0.18826528],
[0.32879668,-0.28357816,-0.29761232,-0.24192352,-0.36829984,0.3101946,0.24014084,0.10514364,0.06201612,0.18394588,0.10971252,0.31961816,0.0488948,0.3804616,0.35112172,0.3716858,-0.331687,-0.3801656,0.36029,0.2549964,-0.15063708,-0.013444512,-0.38040608,0.24539832,-0.35114128],
[0.34121872,-0.8047128,-0.1229,-0.30272616,-0.25955752,0.13487284,-0.6827008,-0.9891328,-0.26995992,0.9151692,-0.4835028,0.4184548,-0.29900712,-0.9094072,0.9954924,0.689695,0.5681034,0.9557572,0.2545008,0.3763628,-0.2410798,0.58303448,-0.30650088,0.36501936,0.055344624],
[0.34242776,0.21854248,-0.361978,-0.18787024,0.35097704,-0.16472544,0.3968254,0.10367356,0.09914844,0.15191564,0.1744168,0.1998218,0.3758154,-0.0719168,-0.2676162,0.05394262,-0.0540319,0.05388898,-0.2641118,-0.3718776,-0.13466728,0.38887744,0.245842,-0.2629524,0.08408768],
[0.34403116,0.9920624,-0.054767256,-0.74455304,-0.45105832,0.6044044,-0.9134004,-0.31188448,-0.8370532,0.24442188,-0.7002164,0.6001548,0.04834236,-0.006942572,0.08153252,-0.463625,-0.9006014,-0.8666534,-0.8040442,0.3404138,0.8290352,0.8662392,-0.6033432,-0.9142744,0.77265056],
[0.34810724,0.23075624,-0.17372744,-0.378102,0.26838952,-0.24569364,-0.1202234,0.35010212,-0.257538,-0.06027984,0.32852904,-0.34250596,-0.17216116,0.2738672,-0.16890076,-0.2414548,-0.224565,0.2543846,-0.2718302,-0.312138,0.39495408,0.38604776,0.27505408,-0.09014016,-0.004239514],
[0.35078076,0.65672736,0.40481808,-0.8423672,-0.2689772,0.01450914,-0.3706626,-0.7256892,-0.4019716,-0.32051596,-0.4685644,-0.5642176,-0.6623744,-0.34041316,0.4879104,0.2383454,-0.8510594,0.17134822,-0.8339568,-0.6839276,-0.01727014,-0.66601768,0.65651824,-0.79738864,-0.36384904],
[0.35263076,-0.018972568,-0.11384872,0.32792688,-0.3562948,0.017549716,-0.33943676,-0.3461392,-0.34479536,0.22382728,0.14221696,0.23584256,0.34705808,-0.33800152,0.0476562,-0.15112756,-0.3373478,0.16793308,0.356106,-0.0879262,0.09587824,0.16826352,-0.1845892,0.3392148,0.001636062],
[0.3532482,0.10932312,-0.23650904,0.2681752,-0.8545688,-0.6839164,-0.2971576,0.6855916,0.5233412,0.86044,0.5387944,-0.33432512,0.653438,0.9663516,0.6514272,-0.3996798,-0.4517324,0.2469632,-0.7175074,-0.400693,0.3840498,-0.16577296,0.58475656,-0.63731072,-0.61965376],
[0.35793864,-0.38636336,0.055205208,-0.11054024,0.26162008,-0.21258284,0.09982216,-0.34313144,-0.37734516,-0.0528336,-0.13686132,0.1663138,0.21867132,-0.2981692,-0.13726208,-0.07838122,-0.03271068,-0.394402,-0.13204562,-0.2704818,0.23414196,-0.12846992,-0.30436888,-0.36851224,-0.19559632],
[0.37352492,0.77768472,-0.46996344,0.36444232,-0.69081232,0.13502352,0.6909852,-0.4619456,-0.4567344,-0.7979064,0.8676668,0.25900336,0.89202,-0.8739808,0.20322236,-0.8866338,-0.7800056,0.9000434,-0.09824524,0.4663664,-0.6072748,-0.871788,0.54045256,0.76891176,-0.9474216],
[0.37406392,0.9374416,-0.43368728,0.53217416,0.43143704,-0.1404998,0.6053084,-0.617176,-0.75065,0.8703088,-0.28612456,-0.10848604,0.7799352,-0.4944192,0.8409192,0.7827672,0.6786398,0.07224348,-0.7465698,-0.2679082,-0.03188784,0.12621864,-0.28740344,0.46565104,0.8627656],
[0.38693916,0.14655392,0.11296896,-0.38884496,-0.3766232,0.3777068,0.30469252,0.1946444,-0.23473632,-0.007345156,0.2705196,0.13392252,0.3767228,0.27171704,-0.06301628,-0.2998638,0.3423328,0.2438432,0.00200048,0.3284634,-0.037550876,0.36662144,0.26515832,0.065783176,0.39395288],
[0.392778,-0.09877784,0.23932624,0.28130576,-0.21690512,0.36347204,-0.17290392,0.37495808,-0.09358192,0.09889144,-0.35238484,-0.17584516,-0.20101332,-0.28898876,-0.37323156,0.3678932,-0.18398804,-0.04879066,-0.17909436,0.1205876,0.07749768,-0.30272104,-0.13632632,0.36554968,0.28441048],
[0.39760728,0.28430552,-0.5306188,-0.13084528,0.34322464,0.5359776,0.397787,0.9035044,-0.14200852,-0.5987552,-0.26227232,-0.35919964,-0.28535268,0.275905,0.4855772,0.04452094,0.8060642,0.385885,0.18463234,-0.9881322,0.51148,-0.5344336,0.9301096,-0.18244568,-0.8997576],
[0.4038912,0.58475664,-0.32636344,0.028161984,-0.015134056,0.17237964,-0.6222924,-0.5607664,-0.9001888,0.5753872,-0.004846544,-0.860504,-0.006186456,0.8915796,-0.6259004,-0.7018716,-0.9103748,-0.1129407,-0.223458,0.13748088,0.867136,0.65694128,0.28080088,0.60957728,-0.2925192],
[0.4046868,0.011282336,-0.4553724,0.45608296,-0.056855984,-0.9838812,0.24068676,0.43419,-0.7028496,0.6737936,0.2990274,0.1308706,-0.775424,0.7296852,0.6113624,-0.3050664,-0.15720806,-0.5170098,-0.4916068,-0.14821332,-0.16179468,-0.75720904,-0.41107336,0.72536128,-0.157272],
[0.4073076,0.8580776,0.47581096,0.68763552,-0.19192488,0.7447372,0.7483436,-0.7170996,0.49167,-0.21023816,0.4463768,0.8653448,-0.4119456,-0.039020424,0.30632144,-0.12143382,-0.17428412,-0.5532662,0.017728964,0.01077888,-0.292326,-0.49012648,0.60692024,-0.319998,0.802668],
[0.4073604,0.068050192,0.9306368,-0.14986784,-0.046547072,-0.4348196,-0.7471696,0.9500656,0.5012696,-0.5754444,0.4281764,0.4454376,0.25163964,0.4167852,0.9108676,0.530055,-0.07213964,0.004424372,0.929367,0.5764368,-0.882596,-0.5672028,0.14460536,0.66566112,0.066488928],
[0.4075768,-0.14955496,0.33221352,-0.34269424,0.242232,0.6977324,-0.39664764,-0.012208212,0.94134,0.9444884,0.7434004,0.7636856,0.9802832,-0.29358384,-0.77458,-0.4349862,-0.07944756,0.635629,0.3520968,0.5664138,0.030217064,0.09153104,0.39475888,0.09984728,0.48059584],
[0.4096232,0.64135384,-0.9149904,-0.78859816,-0.08937496,-0.913998,-0.610502,-0.34671476,-0.7665148,0.621008,-0.1937622,-0.23554048,0.434376,0.09181152,-0.4512648,-0.994749,-0.8874778,-0.444513,0.15055078,0.2216104,0.4158088,0.08722928,0.70324128,0.2070596,0.37700784],
[0.415336,0.9414928,0.9314624,0.8547256,0.8684288,-0.8198112,0.12948152,0.4658304,0.98947,-0.2510854,0.33969284,0.5001316,0.31777304,-0.14803492,-0.9944228,-0.6994872,0.4905326,-0.3780712,0.309355,-0.1229657,-0.4453696,0.8137344,-0.51295328,0.74858712,0.44789456],
[0.4169804,0.9891576,-0.08483616,0.8223216,0.16861968,-0.9679296,0.12132344,-0.6970636,-0.34830272,-0.7128688,0.3049264,-0.10029764,-0.4631336,0.659484,-0.4384744,-0.6282978,0.3611046,0.6995054,-0.8234756,0.16001088,0.36975492,-0.8241304,0.019384696,0.64285232,-0.31501808],
[0.4175988,0.8062032,-0.968344,-0.53526752,0.045551192,-0.819416,-0.6075888,-0.5401928,0.4089708,-0.5679872,0.5680532,-0.11758052,-0.3911416,0.33400716,0.2395554,-0.17511004,0.610368,-0.7281676,-0.2601814,-0.9677214,-0.29280668,-0.49988456,-0.46585736,-0.65688064,0.17919344],
[0.4453848,0.29552704,-0.24995632,-0.9591376,-0.4014396,0.3021394,-0.0590172,0.1803872,0.949714,0.4765444,-0.9705348,0.7287308,-0.1500018,0.8042304,-0.0604278,0.09414404,-0.01739187,0.31393,-0.8941346,0.6366732,-0.4550092,-0.39990488,0.60234864,-0.046793464,0.18319576],
[0.4546936,-0.49744976,-0.940496,0.18468512,0.23124336,-0.9621244,-0.5942628,-0.4799588,-0.37640436,0.4236112,0.6139864,-0.8878292,-0.9908128,-0.7558296,0.6859448,0.4370684,0.5314974,-0.7674188,-0.7883894,-0.3362062,0.6084724,0.34085664,-0.2618892,0.73646584,-0.21954496],
[0.456656,0.040781816,-0.14112872,0.26685424,-0.028994536,0.35258152,0.36778624,0.26045952,-0.8803008,-0.37879888,0.8232548,-0.07703636,0.6988644,-0.7977844,0.023779868,-0.6130632,-0.6012272,0.4564316,-0.4536586,0.02303096,-0.5424868,0.52833192,-0.76163728,0.32312992,0.9235896],
[0.4608368,0.4506452,-0.78291184,0.57171528,-0.13461728,0.02056956,-0.19214652,0.8813728,0.8071924,-0.16845556,0.4386476,-0.17688056,0.4562088,-0.8097768,0.3268962,-0.9686106,0.4807184,0.7251374,-0.0328282,0.4046538,-0.31417144,-0.8928704,0.33667504,0.256118,-0.20931568],
[0.466238,-0.012195024,-0.08077112,0.54315536,-0.09809072,-0.2615858,0.21300012,-0.8958868,0.36799756,-0.883264,-0.001679957,-0.26901844,-0.35469808,0.9686208,0.39115384,-0.726865,0.2335988,-0.4227438,-0.6362594,-0.571226,0.8254352,-0.69279888,-0.16264408,-0.57718576,0.55672392],
[0.4663496,-0.13695472,0.09657032,0.61732864,0.818912,-0.688404,0.26899144,-0.4927588,0.1651356,-0.34221848,0.07459472,-0.941746,0.8460432,-0.5386696,0.36946628,-0.3296928,0.9928792,-0.08648724,0.5995608,0.8484096,-0.957554,0.9423864,-0.62396776,-0.8745488,-0.8880888],
[0.4673784,0.49466872,-0.06498084,-0.3789716,-0.32200296,0.4785576,-0.21525012,0.38363596,-0.6469072,0.5069812,-0.22552988,0.987148,0.6755556,0.401202,0.25119076,0.9678014,0.7328208,-0.2146882,-0.2813156,0.7993468,0.509292,0.36437408,-0.49048232,-0.11396632,-0.15038992],
[0.4701396,-0.37203624,0.67900968,0.39202016,-0.29656488,0.2028432,0.793068,0.32208636,0.9216792,0.36120276,0.6799404,-0.464356,0.2210802,0.6545,0.826468,0.5303682,0.6690712,-0.011978014,0.7708582,-0.1351598,-0.881316,-0.31508632,-0.12223352,-0.53794832,-0.51600432],
[0.4728484,0.7918512,0.9198752,0.44362832,-0.16082536,0.21230508,0.8705444,0.5917976,0.7737132,-0.83075,-0.6343104,-0.09010672,0.4535736,0.10610408,0.008079864,0.8535194,-0.7562464,-0.16381044,-0.6929408,-0.1614982,0.23682176,-0.32307432,0.66052448,-0.32017152,0.78598896],
[0.4847072,0.8285384,0.21897344,0.24275304,0.8597088,0.8358668,-0.9993604,-0.5436376,0.9629176,0.4402168,0.5544872,0.30301256,-0.20131112,0.7654876,0.857852,0.587711,0.3045238,0.567737,-0.7124012,-0.2782448,-0.32071688,0.68838352,0.38502368,-0.9117272,0.56757024],
[0.4872324,-0.42772912,0.4366648,0.08827768,-0.68849328,0.7088592,-0.913614,-0.0066304,0.4986592,0.34469528,0.37460736,-0.8123404,-0.20604832,0.5228696,-0.7610968,0.6054552,-0.5132484,0.14414262,0.6446636,0.4397086,-0.425792,0.922472,-0.7947952,0.23838576,0.8584224],
[0.491278,0.66318776,0.31251208,0.50243544,-0.9191632,0.7063304,0.6078472,0.33744152,-0.013076884,-0.4521284,0.37543416,0.5799208,0.03562318,-0.1329168,0.8040544,-0.975839,-0.683744,0.4644198,0.5718846,-0.00552066,0.17240352,-0.72408384,-0.7660252,0.75783528,0.24306328],
[0.4953484,0.9391688,-0.46975832,0.49427192,0.16275496,-0.492458,0.29019584,0.800682,0.5143016,-0.8715104,0.917186,-0.19049536,-0.449064,-0.20819308,-0.7584584,0.6409314,-0.5515408,-0.12363626,0.9406588,0.8821204,-0.8721968,-0.8839864,-0.9616952,0.64270704,-0.41517928],
[0.498344,0.09860952,0.30202384,-0.33368,0.31049064,0.6919848,-0.022484624,0.0603996,0.05775532,-0.8541924,-0.8571144,0.4224396,-0.8122356,-0.9715096,-0.4458964,0.11145284,-0.5606382,-0.776345,-0.8837164,-0.1866907,-0.8593908,-0.72976408,-0.46247144,-0.15205216,0.7366704],
[0.5099664,0.6664176,0.54323984,0.29345192,0.1904544,-0.459388,0.8333232,0.6635828,0.8025636,-0.657034,-0.37553732,-0.1764474,-0.38969056,-0.0525228,0.7958732,-0.6336226,0.275642,0.453881,-0.2015844,-0.4851638,0.29973832,-0.78498496,0.0793104,-0.25675632,0.8854976],
[0.5136528,-0.29633896,0.37685768,-0.57675184,0.40736528,0.13406832,0.71738,-0.5065896,-0.16402688,-0.29422348,-0.22272348,-0.35800084,-0.10727692,-0.862118,0.4450892,0.4238092,-0.000631043,0.8604184,-0.2666554,0.9217532,0.4846752,-0.69085,-0.15836064,-0.4600584,0.115518],
[0.515384,-0.17063008,-0.5495104,0.4792444,0.5334256,-0.8936532,-0.15196208,0.845034,0.26469964,0.3818446,0.12934204,0.13877156,0.36935384,0.447072,0.9039384,-0.0475487,0.1400815,0.2197608,0.2352696,0.09933058,0.16639376,0.48229088,-0.64022512,-0.31106384,-0.29607288],
[0.51843,-0.8202416,-0.8248216,-0.15950768,-0.49047928,0.6412312,0.05954392,-0.5341512,0.5590572,-0.9292504,-0.6658664,-0.5427712,-0.06148328,0.8517032,-0.006489816,0.9143134,-0.5172626,-0.5615004,-0.2288672,0.8806082,-0.4053616,0.16228416,0.51240912,-0.8058632,0.26654456],
[0.520464,0.34833968,0.043960264,-0.71181848,0.64110688,-0.2502624,-0.6850952,0.27451264,0.23287152,0.8394224,-0.4165316,0.842108,0.25716292,-0.102389,0.5852796,0.16551608,0.799587,-0.5477548,0.9441422,0.7112864,-0.9666728,0.48222616,0.49866848,-0.69227104,-0.61357112],
[0.5246972,-0.65958216,0.33127184,0.27274472,0.12405376,0.8681568,-0.4568784,-0.9640756,0.004247188,-0.12449712,0.7946584,-0.7444644,-0.986004,-0.4189668,-0.029255064,0.9177868,-0.000694903,0.09089868,0.2707638,0.2522654,-0.22724832,-0.17886536,0.11648016,0.07021496,0.21442848],
[0.5342224,0.77321016,0.14596104,-0.33061448,-0.6601132,0.1580562,0.11384036,-0.33778856,0.24094948,0.29167896,-0.36137968,0.5523516,0.025289444,-0.7094332,0.38700576,-0.284096,0.7111954,-0.377675,-0.9599974,0.3990788,0.28540808,-0.71231808,0.28142072,0.16636736,-0.05992],
[0.5377508,0.71700616,0.8284072,0.059111704,-0.32058376,-0.8673456,0.00285448,0.9599088,0.7883,0.7347108,-0.4485668,0.16163144,0.881966,-0.7107924,0.7522004,0.2312966,0.700125,-0.7392202,-0.4459858,0.485851,-0.26686816,0.3846472,0.1138956,0.64238136,0.7432756],
[0.540234,-0.057314448,0.9218632,0.67684872,-0.30957496,0.35189792,0.7013704,-0.36661404,0.04703436,-0.4358568,0.0655782,-0.5730692,-0.651084,-0.6938496,0.26423736,-0.909106,0.4177482,0.4422892,0.4526164,-0.738462,-0.5106196,0.23663216,-0.70351952,-0.009739624,0.052027472],
[0.5406252,-0.8565408,0.8774336,0.08483912,0.77419408,0.8409848,0.35084544,0.31810484,-0.8271908,0.989354,0.18358424,0.4936344,-0.04880148,-0.6227768,0.08870912,0.7319528,-0.5266528,-0.9836988,-0.04371406,0.6713864,-0.17456372,-0.77603168,-0.44259792,0.55285128,-0.44842416],
[0.5440712,-0.75195664,0.98334,-0.55498552,-0.17166216,-0.2504646,-0.2788152,-0.34018108,-0.4080148,0.5271664,0.574932,-0.27609236,0.8820292,0.4635232,0.9125608,-0.6925198,-0.9381498,0.19167424,-0.751718,-0.9955656,-0.6281608,-0.35795616,-0.47950096,-0.61292856,-0.1596312],
[0.547782,-0.56321768,0.27288752,-0.16034616,-0.53306832,-0.9611312,-0.5451776,-0.8298428,-0.028932188,0.036503588,0.037136576,-0.7357488,-0.6304716,-0.13993188,0.31720772,-0.7791054,0.7249068,-0.852931,-0.5782826,-0.5853176,-0.5642276,0.46014928,0.6687424,-0.54530984,0.8508504],
[0.548614,-0.13940936,-0.23816224,0.50334184,0.25610656,0.25494684,0.86912,0.8505316,0.34271548,0.14441852,-0.439008,-0.4333628,-0.5428896,-0.7899224,-0.13344876,0.4961274,-0.8598946,-0.7522312,0.9359212,0.8997806,0.458326,0.15140544,0.79005368,-0.9921912,-0.09891984],
[0.5490388,-0.9268376,0.13824144,0.9973736,0.51253408,-0.7262624,-0.22190176,-0.03278576,-0.683872,0.9131932,0.015233104,0.23675664,0.3580214,-0.7412516,0.8264384,-0.9118148,0.17563588,0.3971582,0.05138216,0.3377576,0.8408364,0.19601712,0.4916424,0.54591552,-0.56588512],
[0.5546784,0.8885848,-0.19248536,0.996772,0.17070296,-0.06414012,-0.6600364,0.7921736,0.7224648,-0.5051676,-0.034638872,0.13554792,-0.9578564,-0.8032712,-0.8462372,0.595907,0.9285752,-0.8533312,0.3368146,-0.04777306,-0.8999304,-0.44057768,0.42084968,0.43816288,-0.4638148],
[0.5570924,0.4812804,0.66428576,-0.29602536,0.0978416,0.34672704,-0.31582068,0.008261684,0.1039452,-0.6640544,0.5326344,-0.426192,0.4414912,0.1181192,-0.8830436,-0.733937,-0.4966198,0.3303234,-0.826826,0.304455,-0.875316,0.59343784,0.16036064,-0.16991504,-0.3946],
[0.5606512,-0.59407056,0.73706592,-0.8247416,0.27111632,0.1390452,-0.13652176,0.1374502,-0.9781852,-0.50656,-0.21492912,0.34538968,-0.22735392,0.8645912,-0.10383596,-0.4351388,0.7876772,0.2532522,-0.505212,0.8848666,0.857504,0.8605952,-0.8686328,-0.37417648,0.963748],
[0.5608444,0.069613696,0.001290983,0.18730704,-0.078434616,0.017131516,-0.2519634,-0.6244836,0.9522916,-0.21141192,0.932704,-0.5992304,0.6669484,0.76265,-0.7968012,0.4415168,-0.2316622,-0.06269182,0.08448212,-0.04713608,-0.18732172,0.12992992,0.7097056,0.47257704,0.21567608],
[0.5627156,-0.9169856,-0.9352872,0.62294768,-0.079355768,0.7664,-0.4268464,0.29326984,0.793306,0.5999612,0.93991,0.6878356,0.8944012,0.38156668,0.036761512,0.3848688,0.9480814,-0.7972534,-0.3452382,-0.9694962,0.403604,-0.7979952,-0.63931744,-0.022037472,0.7898344],
[0.5795332,-0.20284912,0.8157432,0.05980932,0.40112616,-0.9804364,-0.4368764,0.1216722,0.35182624,0.5701448,0.19906528,-0.9046052,0.027935604,0.30675564,-0.7792408,0.3522372,-0.14307314,0.5075578,-0.583625,-0.1936203,0.6512716,-0.35799552,-0.9535568,-0.057115832,0.9389968],
[0.5811752,-0.9329672,-0.13802784,-0.8866064,-0.20689432,-0.5993448,-0.59907,0.27427132,0.08934128,-0.3801438,0.09073388,0.6264768,-0.38717596,0.18333336,0.8602408,0.8181466,-0.7453974,0.9495638,-0.8358116,-0.5594678,-0.6930612,0.3860716,0.58454248,-0.49648272,-0.8428816],
[0.58389,-0.40891056,-0.35025104,0.60956768,0.33567312,-0.09359672,0.5143168,0.584096,-0.5119456,-0.4559576,0.9341848,0.15755676,0.6454348,-0.9314584,0.4155232,-0.9780918,-0.816601,0.4329118,0.2536176,0.09201942,0.16756432,-0.010887368,0.39028616,0.15002064,-0.69121936],
[0.5864948,-0.15804712,-0.51268184,0.43537056,-0.76814544,0.6674068,0.418784,-0.18407296,-0.66448,0.6598676,-0.25083456,-0.635266,0.7453468,0.06710092,0.30752976,0.507808,0.2071762,0.570305,0.19987248,-0.5290776,0.4476376,0.49586224,-0.24482248,0.24036216,-0.79470928],
[0.5871168,0.79011856,-0.000566275,0.17316432,0.70581272,-0.610964,0.35173932,-0.8854712,0.5786348,0.27556604,-0.9555096,-0.10212012,0.7298988,0.22042036,-0.31553548,0.4390548,-0.06316356,-0.7254304,-0.16800134,0.432064,0.36290076,-0.9181216,0.27016768,-0.57968792,-0.7271056],
[0.588362,-0.54843712,-0.79801696,0.09177488,-0.08714344,0.8519968,-0.6556736,0.5947804,-0.14084924,0.374574,-0.9538368,0.651262,0.9292724,-0.70971,-0.4513628,-0.6382754,0.9952398,0.4640724,-0.08868116,-0.2181866,-0.4926796,0.99556,0.69782752,-0.064302672,-0.3218148],
[0.5910848,-0.7169736,0.48156856,0.23190512,0.4447308,-0.38422628,-0.32611108,-0.9837884,-0.9830892,-0.453918,-0.8145576,0.5406824,0.81992,-0.33985752,0.2337502,-0.2914798,0.619252,0.919946,-0.948349,-0.5373546,0.06963156,-0.69386192,0.8035528,-0.8794152,0.64522704],
[0.600904,-0.47045144,0.54906144,0.41710328,0.6794324,-0.10195196,-0.27601856,0.4665884,0.563572,-0.10247984,-0.1607634,-0.4496888,0.772404,0.3132482,0.9765956,-0.3064164,0.9789168,-0.9130118,-0.6026414,0.15327374,0.31205496,-0.060411856,0.09530128,0.55800224,-0.018148136],
[0.613432,-0.04670276,0.012221512,-0.44088232,-0.28312216,-0.5520936,-0.7074808,-0.559998,-0.52544,-0.0536128,-0.11770336,-0.1159866,-0.9397204,-0.5520584,-0.4210856,-0.6218544,-0.1295701,0.0937885,0.09353982,0.2299298,0.2102872,0.8254728,0.19111064,0.7698088,-0.50139088],
[0.6176332,0.8292472,0.22248648,-0.055295448,0.5987308,0.713096,-0.5262736,-0.3467746,0.9533264,-0.2524642,-0.7345364,-0.4255808,0.8616372,-0.9447484,-0.8565044,-0.10842354,-0.8036072,0.7216412,-0.3060028,-0.9737248,-0.0700564,0.25392936,-0.40498064,-0.026238224,-0.66386944],
[0.6176636,0.817584,-0.52991496,-0.15670408,0.19028,0.9298456,-0.8444256,-0.0538334,-0.7924572,-0.3325462,-0.431524,0.192644,-0.3160498,-0.0785684,0.8568588,0.2764406,-0.8246408,-0.8739672,0.647826,-0.7897138,0.38878584,-0.5629536,0.055935528,0.9773392,-0.9910672],
[0.6215692,-0.2179596,0.32164312,-0.79968296,0.73938608,0.33560044,0.7440044,-0.28376332,0.4845072,0.9450208,-0.7488316,-0.5108012,-0.0723,0.14066476,-0.8527876,-0.3716384,-0.2870316,0.4869566,0.9978748,0.5372754,-0.712934,0.059253968,-0.12921784,0.18933312,0.72385328],
[0.6223984,0.20191744,-0.45489568,-0.47829432,-0.16820568,-0.19369664,-0.651848,-0.31370024,0.12831856,-0.7476208,-0.1786872,-0.4075584,0.32131528,-0.7482216,-0.7516964,-0.2491426,-0.7614632,0.3095324,-0.13595602,0.1117016,-0.0860604,-0.65352168,0.64761024,-0.040142888,-0.09554024],
[0.6247436,0.40429,0.007903626,0.53440056,0.7279248,0.13783576,-0.504536,0.7666292,0.431492,-0.16878568,0.7069112,-0.0691068,-0.08902716,0.29810276,0.4732396,0.3677298,-0.8604076,-0.05965438,0.3405728,-0.6733838,0.19022304,0.8127976,-0.8261544,-0.8079976,-0.15409232],
[0.6315148,0.56911424,0.9706776,-0.9143808,0.014188384,-0.6018508,0.8150656,0.9577836,0.7229076,-0.588668,0.21723588,0.6582676,0.6203532,0.19673684,-0.9114756,-0.12968246,0.9619522,0.1628623,-0.9704506,-0.3038584,0.9552964,0.57275992,-0.8403504,0.5979312,0.49692768],
[0.6333156,-0.8478272,0.58755736,0.050292016,-0.9305632,0.29698132,0.7558032,0.9655952,-0.23144648,0.3075982,0.21226352,-0.11966164,-0.725434,-0.25612128,-0.24759436,-0.8108,0.21411,-0.4287134,-0.3705848,-0.9171384,-0.14325392,-0.08133528,-0.74156176,-0.57020328,0.75250936],
[0.6353312,-0.19561512,0.62094888,-0.60492656,0.034472096,0.9514936,-0.6636252,0.20786312,-0.497462,0.23585556,-0.811226,0.8295808,-0.17348552,0.030258028,-0.8525628,0.08959302,-0.66834,-0.8022698,0.13927804,-0.1119288,0.6547236,-0.63356008,-0.1525028,0.79125728,-0.9146232],
[0.6367404,0.8716264,-0.53096896,0.017638768,-0.209728,0.5492236,-0.25274084,-0.8399776,0.6164948,0.14100324,0.423068,0.06144716,-0.968204,-0.689616,0.4379388,-0.08879578,0.7747258,0.9090528,0.7386466,-0.5507256,0.16610708,0.75444304,0.09834832,-0.6718644,-0.18671248],
[0.6392064,-0.8696888,-0.062070336,0.59048296,-0.7785556,-0.09248268,0.5323336,-0.4938044,0.20363468,0.9384764,-0.06658488,-0.05470752,0.5936672,0.5243584,0.0425408,0.5831946,0.5190386,-0.6139352,0.6705608,0.648377,-0.79009,0.16184088,0.4662648,-0.5607436,0.20394144],
[0.6487936,-0.064656656,0.39669224,0.37293544,0.0603464,0.8417536,-0.4247276,0.18140288,0.5748872,-0.34995624,0.9657488,-0.11785332,0.7131064,-0.4418508,-0.6847936,-0.7774388,0.569997,0.5520588,-0.14990052,-0.11064946,0.039677,0.7575976,-0.48687704,0.73797616,-0.6272232],
[0.6502364,-0.8185376,0.44762824,0.9732768,0.51899144,0.6099068,0.7946936,-0.5836988,0.15771952,-0.2684228,0.38104516,-0.9611124,0.8013568,0.2123776,0.27294556,0.0900319,-0.2596974,-0.3144332,-0.8321712,0.7057144,0.5846096,-0.55264392,0.071824256,0.21421592,-0.65751664],
[0.6510516,-0.31512872,-0.360784,-0.56018688,-0.67619096,0.7869628,-0.4241916,-0.4015744,0.330916,0.33572432,-0.8359128,0.9795336,0.16617028,-0.7072956,-0.7391336,0.9544836,-0.6521356,0.8975416,-0.04181192,0.8667538,0.6536004,0.9358408,-0.8385824,0.11491248,-0.14219008],
[0.6636996,-0.27069808,-0.3468528,-0.32667832,0.74336392,0.6009996,0.8638736,0.9386164,-0.27957416,0.25260336,-0.6362188,0.435622,-0.9465796,-0.149507,-0.7201604,-0.920305,0.5938592,-0.6272358,0.6799332,0.91392,0.8797324,-0.11176792,-0.29735248,-0.24290616,-0.9674352],
[0.66495,0.37310432,0.35419168,0.34253328,0.61739104,-0.10554564,-0.24091232,-0.2433784,-0.8356824,0.546196,-0.5647468,0.762622,-0.8120292,-0.5255944,-0.7563168,0.4172688,0.0631874,-0.7669,0.7655794,0.13642942,-0.6726588,0.75767496,0.68717352,0.2044292,0.33210072],
[0.6682976,-0.77740496,0.8696256,-0.9420552,0.20861752,-0.9240624,-0.809484,-0.4016336,0.9193408,-0.038432176,0.973516,0.33146352,0.6516372,0.1361956,-0.9310124,-0.2451506,-0.03944206,0.6469246,-0.7402862,-0.04238276,0.11574136,0.7535276,-0.047238536,0.8421008,-0.79748904],
[0.6754792,-0.19497696,-0.60081904,-0.76454344,-0.36751744,-0.5163776,0.09574744,-0.23926888,0.4843936,-0.35521048,0.04478648,0.5812496,0.38343452,-0.18114964,0.6225268,-0.6483908,0.9179334,-0.7319,0.13775374,-0.004952426,-0.60924,-0.9680872,-0.1389496,0.13528432,-0.63647256],
[0.6800904,0.60265032,-0.40721992,0.4674624,-0.34421624,-0.376644,0.65406,0.7142624,-0.450002,-0.08281684,-0.8066908,-0.1878128,0.880996,0.20815972,0.6654228,-0.4753138,0.8992138,-0.2075868,0.7347964,0.8975866,0.414062,-0.766646,0.9155472,0.752778,0.22796064],
[0.6927772,0.2124524,0.9146312,-0.75129192,0.8930472,0.5186108,0.06175176,-0.34669472,-0.3330126,-0.5975492,0.9229724,0.05494784,0.8324436,0.786728,-0.07608212,0.10443876,0.6000582,0.785474,-0.04726326,0.8190338,-0.8193744,0.930304,0.10516328,-0.37034264,0.37115888],
[0.698952,0.8119608,0.19058592,-0.9118672,0.60599272,-0.8823448,-0.24977556,-0.5250368,-0.5621276,0.667278,0.75363,-0.35848588,0.7344656,-0.38083128,-0.8370068,-0.9932616,0.4451716,0.3675362,0.4433218,-0.3450514,0.020238508,-0.5375136,-0.08603792,-0.56148552,0.63322888],
[0.7013044,-0.3011876,-0.9714376,0.97716,-0.9153216,-0.04716044,-0.5095988,-0.39678476,-0.07062616,-0.16152796,0.517284,-0.1408128,-0.4902768,0.1556464,0.6592728,-0.6295894,0.9447218,0.1565703,0.2287438,0.3415914,-0.7950008,-0.032202536,-0.9138344,0.36468408,0.28931936],
[0.7044696,-0.77594336,0.17776224,-0.0946524,0.18540856,-0.7081248,-0.24611072,0.7926736,0.419906,-0.8152168,0.4289172,-0.796214,0.68313,0.4336352,0.8588924,0.8057552,-0.529814,0.6682254,-0.2522364,-0.4808786,0.19010504,-0.11732808,-0.9418048,-0.8691232,0.49514552],
[0.7067468,0.032754088,-0.069092488,0.52203672,0.71004688,0.3339682,0.7820376,-0.5434228,-0.850202,-0.7222572,0.9614512,0.65735,0.9191432,-0.5495544,0.6568868,0.8872716,0.14502278,-0.3692318,-0.9685034,0.6911164,0.7015904,0.9990096,0.32551088,-0.2221004,0.0168718],
[0.7076596,0.17921696,0.25518808,-0.56080824,0.54297672,0.470494,0.5585784,-0.583794,-0.9789816,-0.5902632,0.5604868,0.4812864,-0.6148232,0.25908692,-0.8331184,-0.328355,0.744529,-0.782002,0.956844,0.2678326,-0.966578,-0.24638616,0.925144,-0.5179004,-0.67670904],
[0.7130752,-0.42359024,0.58874288,-0.18716624,0.933404,0.7835444,0.02635396,0.10008288,-0.5534528,-0.06171352,0.988032,-0.9647768,-0.7498316,-0.8494948,-0.07899196,-0.5735242,0.9752374,0.2691052,0.7855392,0.418938,-0.4388868,0.8027056,0.35310696,-0.5152688,-0.25412432],
[0.7139144,0.62414728,-0.5229156,-0.1571552,-0.006997046,0.15411584,-0.038425212,-0.7849824,0.5171896,0.2863994,0.7292592,0.17482924,0.9020772,-0.24697488,0.9361128,0.2053662,0.5178746,-0.5281236,-0.8205816,0.6360398,0.007861112,-0.59574376,0.77610648,-0.33572648,-0.5060092],
[0.7149852,-0.56071872,0.915672,-0.7555252,0.75615112,0.2223492,-0.9929708,0.8612044,0.18157632,-0.6305988,-0.7024028,-0.6828532,-0.31507632,0.21020264,0.9581376,0.15738354,-0.4016428,0.3844374,0.18801672,-0.6072914,0.5230404,0.9106536,-0.16771976,0.36034072,-0.8620992],
[0.7166336,-0.886508,0.68084088,-0.15712824,-0.9722848,-0.5417968,0.4030228,-0.35316204,0.4405984,0.4543368,0.24762192,0.561756,-0.6641348,0.19071748,0.29306204,-0.5604892,0.3875798,-0.10979354,0.4504946,0.8977654,0.036543456,0.7044504,0.41819016,0.22768352,-0.061272056],
[0.718408,-0.58548224,0.13862584,-0.7474428,0.8894048,-0.0598542,0.8477392,0.650824,-0.21280068,0.13950292,0.4171804,-0.5967328,-0.026406532,0.50063,-0.31256048,-0.825381,0.2459578,0.7007096,0.2733084,0.9813258,0.16906004,-0.008678976,0.3864544,-0.7268728,-0.9725296],
[0.7218376,-0.5079296,-0.078505536,-0.9206032,0.04360752,-0.01158148,0.2875138,0.014775564,0.37925972,0.8217024,0.8510856,0.4788172,0.7254976,-0.9666392,0.7253368,-0.007343602,-0.014530944,-0.8314296,0.4265058,0.5500514,-0.15196632,-0.43257304,0.1006784,0.74689896,-0.13114936],
[0.7223732,-0.9792152,-0.17472088,0.34603344,-0.46590464,-0.402044,0.3379306,-0.5541792,0.2467446,-0.9762336,-0.7106228,-0.916532,-0.2817968,0.7503788,0.2536804,0.11918148,-0.776309,-0.4460856,-0.110487,-0.8840398,0.5480008,-0.14402544,0.5229888,0.25001528,0.62383872],
[0.7272868,0.22796768,0.38180304,-0.38418704,0.23380552,0.10912124,-0.4030496,-0.6638596,-0.5276772,0.7257856,0.7923148,0.888214,-0.011923856,-0.3705168,-0.4025824,-0.7226918,-0.9911052,0.7778968,0.5150466,-0.9650396,0.7617392,0.9355312,0.31310784,0.12157256,-0.8996264],
[0.7291768,0.16900144,-0.56621696,0.1398504,-0.76685416,0.26642608,0.688616,-0.13168528,-0.20909004,-0.8757768,-0.1769936,-0.94827,-0.7105776,0.4358288,0.88325,-0.1955056,-0.8742392,0.09311568,-0.9839504,0.7728594,0.08507012,0.859488,-0.55179632,-0.2134728,0.9786408],
[0.737902,0.34651296,-0.13194056,0.48334088,0.36062256,-0.25471364,0.9752844,0.04917716,0.5804272,0.21919372,-0.036553616,0.04707436,-0.16223496,0.764652,-0.14600348,-0.2202444,0.5031276,-0.03614524,-0.5988048,-0.6514082,0.11688008,-0.7660476,0.78653912,0.638264,-0.45264816],
[0.7453368,0.8452064,-0.8427664,0.036963344,0.51194448,0.37053888,-0.257366,0.7974776,-0.07946408,0.9761684,0.9979472,0.6027772,0.6644712,0.7063424,-0.34581784,0.19713364,-0.7262172,-0.494112,-0.06492068,0.901676,-0.8037608,-0.8268792,-0.3888276,-0.22348648,0.24597384],
[0.7596844,0.9701112,0.020944616,-0.42031608,0.33236296,0.29779224,-0.4817092,-0.31809752,-0.7582208,-0.6462312,-0.6931492,-0.6250344,0.30644148,-0.991408,0.0934912,-0.5216176,0.5286342,-0.19524984,0.2457012,-0.5861324,0.4368016,0.62709648,-0.022918984,0.2877324,-0.16089704],
[0.766956,0.72108824,-0.5328104,0.872456,0.2732748,0.18023084,-0.295738,-0.16949904,0.2408966,-0.00675628,-0.4786988,0.704292,0.3929834,-0.7065696,-0.06650668,0.15244958,0.09761534,-0.922805,-0.7660966,-0.357742,0.4902316,-0.40472456,0.5573424,-0.8914128,-0.53132728],
[0.7685484,-0.10204632,-0.8545048,-0.1115648,-0.73341976,0.22206684,-0.28700976,-0.7975892,-0.7091096,0.7709312,-0.845872,-0.7685916,0.033051668,-0.6090712,-0.0817024,0.4110308,0.515976,0.562631,0.19609722,-0.7912214,0.646728,0.046001896,0.58188768,0.36296344,-0.7339656],
[0.7707696,-0.42128104,-0.01383776,0.8721488,0.071190856,-0.4863828,0.5733552,-0.23208528,0.9460216,0.4780232,-0.34077692,-0.8644788,0.27523292,0.7393204,-0.6960152,0.07817736,-0.8694536,-0.4180956,0.7905862,-0.14915888,-0.19848336,-0.9384912,-0.9993168,-0.9636368,0.16664408],
[0.7708088,-0.27537752,-0.3202472,0.36723432,-0.85984,0.9795064,0.9260664,-0.30073748,-0.30862644,-0.439206,0.34753608,0.4243684,-0.6336904,-0.9574768,-0.3149854,-0.8029954,0.905144,0.7408498,0.08388224,-0.15804612,-0.9894544,0.70739584,-0.67963176,-0.857172,0.22499568],
[0.7813272,-0.7817536,-0.9338608,0.41489784,0.76433264,-0.6422912,-0.9104096,0.5979764,-0.8665636,-0.8867024,0.07342284,0.6645908,-0.4609448,0.7014272,0.568258,0.4221888,0.8745028,-0.9528624,0.3556334,0.5488082,0.23905456,0.36979592,-0.7525452,-0.008328656,-0.8412888],
[0.78624,-0.72878024,0.14593056,-0.53277336,-0.9070592,-0.4784268,-0.6449924,-0.4251504,0.9949048,-0.4532068,-0.08101304,0.16248408,0.5252452,0.5577468,-0.48115,-0.643469,-0.07354594,-0.9885194,-0.6900706,0.802287,-0.5576344,-0.26975072,0.35240176,0.9908648,-0.004388789],
[0.7918956,-0.720682,-0.71497096,0.9420712,0.11878424,0.26630072,-0.9859268,0.3924824,-0.6550432,-0.37818348,0.23429992,0.761666,-0.9592272,-0.023765728,0.25668516,-0.751369,-0.5596696,0.2146894,-0.01027967,-0.4039604,0.7477108,0.9770728,0.822804,0.7222496,-0.2393852],
[0.7922,-0.14770416,-0.60058264,-0.451456,-0.8854056,0.5928964,-0.11434156,0.35337052,0.6597264,0.16617936,-0.37935728,-0.026882584,0.34373208,-0.32399936,-0.24236316,0.8411126,0.6420164,-0.9185004,-0.18837632,-0.704978,0.7672548,0.8080896,0.31510816,-0.43958912,-0.10639168],
[0.7939776,-0.43864336,0.1331756,0.39860472,0.952916,-0.8531784,-0.7621736,-0.5924224,-0.7360328,-0.37829064,0.8456128,0.9684688,-0.9193868,-0.708236,-0.9002044,-0.2164306,0.19356698,0.6297088,-0.9476214,0.4413812,-0.16696544,-0.37770208,0.09527888,0.12965952,0.11202072],
[0.7974784,0.08567184,0.9344512,-0.5583244,-0.1684452,-0.6865872,0.5365516,-0.5482256,0.5710136,-0.8994336,-0.6625056,0.8639256,0.6203452,0.3017648,0.6939556,-0.631501,-0.7778788,-0.3110604,0.05804224,0.6670342,0.4797892,-0.8419048,-0.9982792,-0.47459784,0.8720392],
[0.7981404,0.4949192,-0.9143664,0.18077584,0.72518984,0.9367672,0.7439372,0.8357108,-0.22327256,0.6040328,0.27550708,-0.9559572,0.9123092,0.09049764,-0.8226252,-0.457663,-0.7702748,-0.9978556,0.584812,0.973781,-0.038512928,-0.6404508,-0.53055984,-0.4237816,-0.9524696],
[0.7981428,0.16275296,0.28894288,-0.6247352,0.57517888,-0.29825116,0.5361264,0.7689804,-0.8876024,-0.9681096,0.6264824,0.9352388,0.1381702,-0.9486116,-0.283618,0.8832048,0.4575972,0.18974566,0.2672832,0.9268108,0.05320052,-0.3406236,0.9283456,0.04653132,-0.8389104],
[0.7987436,-0.59918976,0.59371512,-0.5207232,0.42908848,0.37967972,0.9204116,0.585416,-0.9914796,-0.7686548,0.4685352,0.730488,-0.36208584,0.851308,0.7765708,-0.18939504,-0.701801,0.3661188,-0.3747242,0.14299622,-0.642918,0.61807944,-0.3596912,0.58339696,0.79231432],
[0.8010296,0.62674696,-0.21978888,-0.64701304,-0.44327648,-0.15307824,0.4469952,-0.19424256,0.908868,0.5800336,0.7983016,0.6163384,0.3205786,0.958488,-0.22225228,0.12346726,-0.4624238,0.583402,0.0874694,-0.1299941,-0.11059084,0.31324864,-0.66290352,-0.35005992,-0.3464532],
[0.819158,-0.54168856,-0.11607136,0.73994072,-0.010964256,0.6528336,0.018842276,0.29249128,0.2238374,0.4315892,-0.7851544,-0.2193652,0.23388828,-0.6257372,0.0505402,-0.3172644,-0.2504478,0.4845348,-0.12996934,0.2248434,-0.9741492,-0.13902696,-0.3465952,-0.69546224,0.76451312],
[0.8220872,-0.57327176,0.20480728,0.20724096,-0.22580496,0.22317072,0.25596728,0.115312,0.5455996,-0.5380996,0.9253096,-0.6655392,0.8631032,-0.500746,-0.33723928,0.7835194,0.2425744,-0.8265844,-0.7229228,-0.809486,-0.27650248,0.5143728,0.6598216,0.628228,0.48574744],
[0.8244452,0.24260352,0.52035224,0.4194208,-0.51730792,0.36440812,-0.1548774,-0.4491252,-0.8960652,-0.08190416,0.732652,-0.4947296,0.9177908,-0.5716196,-0.31818732,-0.7151244,-0.4717764,-0.5031654,-0.9188122,-0.7491162,0.8885492,0.5597244,-0.58569144,0.49522208,-0.32243608],
[0.8265264,0.54552136,-0.42381216,0.29364256,-0.44373888,0.9758084,0.9370836,0.8445432,-0.695634,0.37599152,0.00974198,-0.9796792,0.6234536,0.36069912,-0.5994508,-0.7232094,0.08759258,0.14269254,0.7007738,0.5545166,-0.2078982,0.19414248,-0.71666464,-0.13767656,0.53666504],
[0.8314464,0.20369672,-0.9618432,-0.063135144,-0.79353976,-0.5498532,0.5508636,0.5687256,-0.2132106,0.1980478,0.32063656,0.8524332,-0.985716,0.7177728,-0.32785768,-0.18241334,0.9355192,-0.05046334,0.11681334,-0.2074716,-0.6298268,0.007108382,-0.8915736,0.5921824,0.46151368],
[0.8318016,0.77428768,0.25837176,-0.35243432,0.43916288,-0.7166756,0.4282532,0.5304016,-0.4212784,0.9798216,-0.037337544,-0.366572,0.511704,-0.29989812,-0.6687704,-0.4132902,0.5398654,0.7092942,-0.799849,0.6884622,0.6784948,-0.9972696,-0.16893448,-0.41412816,-0.49759528],
[0.8389484,-0.8052176,-0.5226008,-0.26724232,-0.70344336,0.08685612,0.9661892,0.8969616,-0.08908408,0.22479596,-0.5180756,-0.05020772,0.4783052,0.670226,0.05168592,-0.3147362,-0.8347442,0.16336756,-0.16549466,-0.582624,0.676042,-0.42380704,-0.77834928,-0.58035792,0.9818216],
[0.84136,-0.33479832,-0.34072,-0.56891912,0.668786,0.7199588,-0.9081432,0.5561744,-0.468682,-0.7432648,-0.5804292,-0.9705108,0.37153112,0.5274984,-0.476728,-0.231109,-0.09566738,0.9809606,0.7433148,-0.4833152,0.592682,-0.8159744,-0.79877936,-0.2351988,-0.1524292],
[0.8430608,0.2828016,0.10316672,-0.18195184,-0.8045824,-0.4338448,0.9171432,0.26931096,-0.10343172,-0.7338036,0.11143064,0.020682928,0.5933312,-0.567396,-0.8446452,-0.4659538,0.6142838,0.492818,0.1001081,0.6754564,0.13420912,-0.70099192,-0.6435564,0.03012736,0.4028924],
[0.8521096,0.8011952,-0.27364048,-0.31539824,0.37978384,0.8616056,0.07260636,-0.32024648,-0.8388648,-0.4642636,0.4831608,0.033286044,0.5617548,0.65434,-0.9881912,-0.34352,-0.6027778,0.72825,0.5838238,0.5770308,-0.5250436,0.26827632,-0.4451268,-0.9978224,-0.71092632],
[0.8545608,-0.8363184,-0.5382344,0.51252296,-0.71550704,-0.7586508,0.05768036,-0.7370704,-0.1560614,0.5358876,0.19288144,0.4758616,-0.6879924,0.913234,0.19522772,0.07062754,0.17641774,0.292251,0.6863414,-0.7110782,-0.6742776,0.8940272,0.74358592,0.059637272,-0.8438512],
[0.85533,-0.7528844,-0.074584464,-0.05744176,0.9247656,0.07579016,-0.4805888,-0.2131612,-0.9754804,0.1101006,0.24204952,0.4008008,0.2094216,-0.24225812,-0.35121968,0.395442,-0.2704864,-0.6934138,-0.6983684,0.8697484,-0.602602,-0.68096408,0.25966528,-0.9707688,0.33824376],
[0.8562244,-0.33829032,-0.026545264,-0.8681008,0.6135276,-0.424492,-0.17623416,-0.5281516,-0.6630124,-0.7560124,0.09170856,0.7720464,-0.7673616,0.4457204,-0.7439024,0.14931546,-0.0598528,0.9473582,-0.4266802,-0.71417,0.72594,0.719416,-0.8215312,-0.28513248,-0.011409952],
[0.8639316,-0.1607364,0.47668864,0.36817856,0.69284104,-0.8457716,0.3192418,0.5279132,0.26904392,-0.824242,0.9478968,0.4938832,-0.7034996,0.10107072,0.208367,0.8935298,-0.4651018,0.7788432,0.4889512,0.833191,0.065629,0.73231848,0.33039024,-0.743054,0.8994992],
[0.8655424,-0.76756072,-0.2671536,-0.37505928,0.53432096,-0.9546452,-0.401128,-0.9824424,-0.4881128,-0.909046,-0.8736852,-0.8548404,0.6237684,0.5574328,0.7484492,0.6526396,-0.2079428,0.02855366,-0.5479398,0.5372102,-0.31525708,-0.30536632,-0.9280112,-0.52226376,-0.55056264],
[0.872988,-0.27873528,-0.45550728,-0.32217528,-0.11915496,0.33844368,0.6291952,0.6647564,0.7041232,0.8958952,-0.16415924,-0.660842,0.013519344,-0.7358808,-0.6250852,-0.2658216,-0.19989262,0.5536662,0.4876434,0.8113016,-0.5145796,0.45212512,-0.75021144,-0.31911528,-0.08622544],
[0.8737216,-0.40926784,0.043643624,-0.8995224,0.46484184,0.001119116,-0.07302128,0.596628,-0.12876356,0.05398008,-0.4660196,0.5672196,0.5290876,-0.20245912,0.05929276,0.9545174,-0.4988342,0.2406654,0.8382062,0.550373,-0.37533244,0.4204748,-0.45346304,0.48227576,0.948632],
[0.8760432,-0.014230824,0.3379568,0.9303832,-0.063587688,-0.30970968,0.6840592,0.5959244,-0.6945936,-0.5706296,0.2147556,-0.7156676,-0.2313368,0.08553784,0.5563684,-0.2006824,0.04115874,-0.776477,0.4230004,-0.3678076,-0.20588756,0.6635628,0.8153416,0.11017624,0.7828164],
[0.8787212,-0.71070496,0.42126736,0.28277416,-0.73655376,-0.06604212,-0.32718208,0.7393896,-0.031139232,0.9871068,-0.4726112,-0.7275956,0.6487296,-0.6879108,-0.35788368,0.004855188,-0.6205664,-0.017404258,0.702603,-0.9649424,0.7629648,0.6198556,0.69435408,-0.13493256,-0.66863896],
[0.8900924,-0.09971776,-0.41067496,-0.9528272,-0.64218624,0.38772616,-0.37238504,0.3635864,0.24565832,-0.9298204,-0.439618,0.4912872,-0.6590156,0.07425924,-0.07908212,-0.4210356,0.7263446,0.5960354,0.3181838,0.4830608,-0.8005272,0.26946512,0.22809328,0.21984152,-0.77142984],
[0.8949544,-0.77650848,-0.9819408,-0.71332008,0.8555216,-0.31614072,-0.650446,-0.5054604,0.19590404,0.6366996,-0.19455928,-0.980788,-0.04758116,-0.8504884,-0.6637212,-0.651496,-0.8477384,0.9385022,0.8302826,-0.8482916,0.8032156,-0.31761736,-0.55570624,0.66438408,-0.20781784],
[0.8962412,-0.9694728,-0.11270088,0.60717872,-0.76414384,0.9447308,0.9772196,0.8503392,0.581864,0.3435846,-0.025900008,0.38944492,0.08889804,0.9576848,-0.07084664,0.7564128,0.8846554,-0.4886264,0.9914352,-0.71129,0.961404,0.21387744,0.38634576,-0.28644176,0.8560416],
[0.9035876,0.32429024,-0.4148604,-0.9038296,0.61435952,-0.20027268,-0.937456,-0.3526238,0.756116,0.8852528,-0.37101292,0.587504,0.986388,0.22156836,0.27771112,-0.7671728,0.4903,-0.9345394,0.568908,0.8693238,-0.17675616,0.9869272,0.07869736,0.29232456,0.11522784],
[0.909006,-0.1809284,0.53187096,0.9370528,0.19429976,0.0725774,0.7580152,-0.8738796,0.17438796,-0.6325948,0.006480768,0.8770224,-0.18217352,-0.9303184,-0.33009328,0.3870458,0.5975392,0.378511,0.692817,0.5803656,0.6094008,-0.7048584,-0.51896064,0.58893416,0.09741328],
[0.9276336,0.52771392,0.08332408,0.59000552,-0.028067736,0.277782,0.901066,-0.7226576,0.8067352,0.22152728,0.09979024,-0.7787184,0.11036632,0.6425864,0.9131248,0.8544574,0.870127,-0.4806152,-0.11366888,0.8279452,-0.4417288,-0.270864,-0.62578248,0.40738264,-0.804288],
[0.9283364,0.63509344,-0.9994784,-0.8921904,-0.93974,-0.4166432,0.6663872,-0.9506372,-0.931036,-0.4756692,-0.9420076,0.6217076,-0.35917856,0.13622656,-0.1969196,-0.06725554,-0.8167874,-0.018628658,0.3340894,0.10889452,0.21256328,0.7189008,-0.39027592,-0.34969664,-0.11943848],
[0.9358884,-0.75747288,0.31313624,0.61965872,0.16719248,0.6649756,0.32683612,-0.8079556,-0.37063196,-0.537904,0.985868,-0.23911796,0.8442736,0.19748696,0.8315952,0.15073204,-0.716318,0.8078952,-0.04984084,-0.8233712,-0.7209824,-0.77598576,0.58330072,-0.62115672,0.23848016],
[0.9412868,0.12569264,-0.56710944,0.8217816,0.063221152,-0.015080652,0.471948,0.33715424,-0.9765068,-0.38429124,-0.025100052,0.9242908,-0.4904464,0.2871824,-0.7237052,0.4512134,-0.8846884,0.8968882,-0.9542942,-0.2641778,-0.3139046,0.910244,0.9341408,-0.045969776,-0.904592],
[0.9414736,0.9336016,-0.27324912,0.03518712,0.53310976,0.8478332,-0.856446,-0.695134,0.39190896,0.6496276,0.33718548,-0.99696,0.39408388,0.7899044,-0.06733164,-0.561838,-0.9100532,-0.439777,0.4555486,0.5656288,-0.865136,0.38638264,0.8564632,0.44244288,0.042671848],
[0.9434604,0.06651964,-0.61288432,-0.7946116,0.8006432,0.037014256,-0.05100448,-0.651226,0.1350348,-0.21181444,0.9997696,-0.32785888,-0.34011328,0.9849396,-0.4776672,0.5623662,0.3683434,0.88854,0.6661922,0.2829992,-0.6044412,0.055624272,0.394154,0.15632064,-0.12939136],
[0.9458724,0.73997056,-0.22167704,-0.006465765,0.618392,0.6560624,-0.05710252,-0.17358056,0.9986952,-0.00575562,0.9455892,-0.610134,-0.4060732,0.6418852,-0.8595628,-0.04715248,0.1141232,0.013407938,0.3380076,0.8532404,0.6725272,-0.1574932,-0.15877432,0.9238856,0.08879784],
[0.9467012,0.032313784,0.28863696,-0.079956384,-0.35217032,-0.8019644,-0.24142912,0.26766576,-0.720302,-0.8389148,-0.4560528,0.06993116,0.33767004,0.5403196,0.7617268,0.5898816,0.5396732,0.2408902,-0.015584772,0.300847,0.6954256,-0.185786,0.076937816,-0.4895524,-0.66603304],
[0.9492764,-0.7569528,0.8958336,0.4014216,0.9779216,-0.8066272,0.8089148,-0.9048328,0.4568664,0.8228752,0.018710436,-0.721736,0.5150656,-0.6403184,-0.6046396,0.4833242,-0.8750154,-0.9699098,0.2601344,-0.3646112,0.5081264,0.9475808,0.21255,0.5043148,0.9377544],
[0.95178,0.6367356,0.65953784,-0.018234008,0.15920656,-0.49687,0.7832848,-0.7921864,0.7444848,-0.6497348,0.7949776,-0.5820304,-0.07043132,-0.037531136,-0.7521684,-0.11200384,-0.72906,0.2558732,0.5809216,0.6654806,-0.34474068,0.8941584,0.21635816,0.53224432,0.70098616],
[0.954332,0.8868856,-0.30944424,0.05253012,-0.8481424,-0.28778588,0.9194828,0.38651324,-0.9562556,0.32869808,-0.33597584,0.8321288,0.35796308,-0.7754568,-0.8315648,-0.7720308,-0.7647406,0.09160166,-0.7934728,-0.62654,-0.8984708,0.2508652,0.75399344,0.10584824,0.26682056],
[0.957118,-0.9523008,0.37040552,0.35420112,-0.56282368,0.8570588,-0.4375492,0.90221,0.4542224,-0.8218912,-0.22438664,0.25120012,0.792354,0.4004636,-0.08591556,0.2329378,-0.6466092,-0.5745008,-0.10729476,0.3758482,-0.7561688,0.450132,-0.31243144,0.62407952,0.60826536],
[0.9602004,0.53912072,0.28492064,0.89498,-0.08985432,-0.32328848,0.3695962,-0.27973616,0.04791048,0.16770324,0.0570146,0.11709056,0.30060808,-0.13041556,0.024292972,-0.6422554,0.5902032,0.8046614,0.643201,0.4111862,-0.9513684,-0.2257884,-0.5436948,-0.857328,-0.50671112],
[0.962828,0.78682552,-0.38843224,0.021002072,-0.05978148,0.28277268,0.58598,-0.902882,-0.57989,0.37763616,-0.4290288,0.35068292,0.001809749,-0.8622844,0.8798148,-0.630277,0.4940172,0.3187106,0.3884638,-0.8275018,-0.39366424,-0.8970824,-0.1687844,-0.77358104,0.719512],
[0.975904,-0.9483616,0.29874432,-0.33895288,0.28293336,0.4070572,-0.769852,0.8398028,0.7530168,-0.7233444,0.7488492,-0.21270208,-0.9973912,-0.35168196,0.004174724,0.10326068,0.3265854,-0.07668508,-0.12905596,0.6855582,-0.5183584,0.53848288,0.46634208,0.340692,-0.005640709],
[0.9778168,-0.4416284,-0.51671016,0.072795416,0.60753936,-0.868234,0.8884024,0.774736,-0.29683864,0.8947356,-0.4677168,0.07056492,0.8283532,-0.04091988,-0.5629308,0.3136438,-0.02007128,0.1160053,-0.496273,-0.3032342,0.04363108,-0.040159128,-0.018807456,-0.79721872,0.74888696],
[0.9831388,-0.58101472,-0.44627088,-0.08017736,-0.8218808,-0.5036252,0.582744,0.10333768,-0.7654648,-0.24468372,-0.11668872,0.3644174,-0.1155636,0.5397984,-0.9109944,0.7281462,0.1725757,-0.8159796,0.8959322,0.29969,0.7791088,0.56647672,-0.68995584,-0.4430612,0.60779848],
[0.9875248,-0.65921496,-0.928928,-0.4246756,0.35909192,0.4686604,0.4968372,0.21628468,0.243766,-0.7778256,0.9318668,0.2067948,-0.5866528,-0.4171884,0.19262716,-0.6936874,0.13166804,0.7829012,0.518191,0.8256072,-0.8537328,0.08032416,-0.39956368,0.59077376,0.8398336],
[0.9914544,-0.050285912,-0.21688832,-0.09422648,-0.63137176,0.3729446,0.7937592,0.06939664,-0.035323288,-0.7411232,0.31815668,-0.7076548,0.5964988,0.07384496,0.6882196,-0.6615344,-0.9522156,-0.7463206,0.5877714,-0.2523558,0.799514,0.68709808,0.40410048,-0.066595408,-0.9858],
[0.9945768,0.15656832,-0.51088592,0.8184904,0.6937356,-0.5186884,0.38727012,-0.06736656,0.9276728,0.5226268,0.6737992,-0.22887896,0.28189608,0.6920124,0.478668,0.4321,0.5124978,0.2526026,-0.1178505,0.09192118,-0.07412924,0.21844864,-0.9817928,0.53824216,0.69590056],
[0.9951988,-0.19689744,-0.59704856,-0.013748008,-0.31334512,0.174308,-0.6286856,0.8817644,-0.6673748,-0.25470088,-0.4045392,0.4527572,-0.9877372,0.3627538,0.2126448,0.0964504,-0.18231966,-0.7403782,-0.6381626,0.7653484,0.7143812,-0.56124232,-0.8147816,-0.030903304,-0.88964],
[0.9956436,0.358282,-0.15275728,-0.57280664,-0.087762,0.939348,0.5316308,0.8886284,0.416306,0.39524728,0.7887828,0.39620296,0.38067348,-0.7793868,0.9313936,-0.281948,-0.08257332,0.3192,0.18656414,-0.1581843,0.8179192,0.485438,0.005795364,0.5511956,-0.34955368],
[0.9993388,-0.15829144,0.110528,-0.1104108,0.65763936,0.018751128,0.5150728,-0.8686552,0.003809682,-0.5171348,-0.8185576,0.709784,-0.446038,-0.06724404,0.02085272,-0.3851304,-0.8670188,0.5087578,0.5500584,-0.6376162,0.16387948,0.51113224,0.45510152,0.50295088,-0.30369624] ] )
return X, Y
class TestG(TestCase):
def test_find_subspaces(self):
X, Y = data()
N = X.shape[0]
num_obs = 500
chosen_points = np.random.choice(range(N), size = num_obs, replace = False)
X_red = X[chosen_points,:]
Y_red = Y[chosen_points]
remaining_pts = np.delete(np.arange(N), chosen_points)
chosen_valid_pts = np.random.choice(remaining_pts, size = 30, replace = False)
x_eval = X[chosen_valid_pts]
# Active subspace
mysubspace = Subspaces(method='active-subspace', sample_points=X_red, sample_outputs=Y_red)
W = mysubspace.get_subspace()
e = mysubspace.get_eigenvalues()
# Variable projection
mysubspace2 = Subspaces(method='variable-projection', sample_points=X_red, sample_outputs=Y_red)
W = mysubspace2.get_subspace()
poly = mysubspace2.get_subspace_polynomial()
def test_get_zonotope_vertices(self):
X, Y = data()
N = X.shape[0]
num_obs = 500
chosen_points = np.random.choice(range(N), size = num_obs, replace = False)
X_red = X[chosen_points,:]
Y_red = Y[chosen_points]
mysubspace = Subspaces(method='active-subspace', sample_points=X_red, sample_outputs=Y_red)
Y = mysubspace.get_zonotope_vertices()
def test_get_linear_inequalities(self):
Xorig, Y = data()
N,d = Xorig.shape
for j in range(d): #randomly scale each column of X
scale = np.random.uniform()*10.0
Xorig[:,j] *= scale
scaler = scaler_minmax()
scaler.fit(Xorig)
X = scaler.transform(Xorig)
np.testing.assert_array_almost_equal(Xorig,scaler.untransform(X),decimal=8)
num_obs = 500
chosen_points = np.random.choice(range(N), size = num_obs, replace = False)
X_red = X[chosen_points,:]
Y_red = Y[chosen_points]
mysubspace = Subspaces(method='active-subspace', sample_points=X_red, sample_outputs=Y_red)
subspace = mysubspace.get_subspace()
active_subspace = subspace[:, 0: mysubspace.subspace_dimension]
A, b = mysubspace.get_linear_inequalities()
# Now if we generate a handfull of inactive samples, they should have the same active coordinates!
sample_coord_index = np.random.randint(N)
active_sample_coord = np.dot(X[sample_coord_index,:], active_subspace)
S = mysubspace.get_samples_constraining_active_coordinates(100, active_sample_coord)
U = np.dot(S, active_subspace)
U_random_entry = U[np.random.randint(0, 99), :]
np.testing.assert_array_almost_equal(U_random_entry, active_sample_coord, decimal=4)
# Rescale samples (S) to original coordinates
Sorig = scaler.untransform(S)
if __name__== '__main__':
unittest.main()
|
jlegendary/orange | refs/heads/master | Orange/testing/regression/tests_20/reference_random_classifier.py | 6 | # Description: Shows a classifier that makes random decisions
# Category: classification
# Classes: RandomClassifier
# Uses: lenses
# Referenced: RandomClassifier.htm
import orange, orngTest, orngStat
data = orange.ExampleTable("lenses")
rc = orange.RandomClassifier()
rc.classVar = data.domain.classVar
rc.probabilities = [0.5, 0.3, 0.2]
for i in range(3):
for ex in data[:5]:
print ex, rc(ex)
print |
teltek/edx-platform | refs/heads/master | cms/djangoapps/contentstore/management/commands/utils.py | 25 | """
Common methods for cms commands to use
"""
from django.contrib.auth.models import User
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
def user_from_str(identifier):
"""
Return a user identified by the given string. The string could be an email
address, or a stringified integer corresponding to the ID of the user in
the database. If no user could be found, a User.DoesNotExist exception
will be raised.
"""
try:
user_id = int(identifier)
except ValueError:
return User.objects.get(email=identifier)
return User.objects.get(id=user_id)
def get_course_versions(course_key):
"""
Fetches the latest course versions
:param course_key:
:return: { 'draft-branch' : value1, 'published-branch' : value2}
"""
course_locator = CourseKey.from_string(course_key)
store = modulestore()._get_modulestore_for_courselike(course_locator) # pylint: disable=protected-access
index_entry = store.get_course_index(course_locator)
if index_entry is not None:
return {
'draft-branch': index_entry['versions']['draft-branch'],
'published-branch': index_entry['versions']['published-branch']
}
return None
|
ahnqirage/spark | refs/heads/master | python/pyspark/sql/utils.py | 14 | #
# 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 py4j
class CapturedException(Exception):
def __init__(self, desc, stackTrace):
self.desc = desc
self.stackTrace = stackTrace
def __str__(self):
return repr(self.desc)
class AnalysisException(CapturedException):
"""
Failed to analyze a SQL query plan.
"""
class ParseException(CapturedException):
"""
Failed to parse a SQL command.
"""
class IllegalArgumentException(CapturedException):
"""
Passed an illegal or inappropriate argument.
"""
class StreamingQueryException(CapturedException):
"""
Exception that stopped a :class:`StreamingQuery`.
"""
class QueryExecutionException(CapturedException):
"""
Failed to execute a query.
"""
def capture_sql_exception(f):
def deco(*a, **kw):
try:
return f(*a, **kw)
except py4j.protocol.Py4JJavaError as e:
s = e.java_exception.toString()
stackTrace = '\n\t at '.join(map(lambda x: x.toString(),
e.java_exception.getStackTrace()))
if s.startswith('org.apache.spark.sql.AnalysisException: '):
raise AnalysisException(s.split(': ', 1)[1], stackTrace)
if s.startswith('org.apache.spark.sql.catalyst.analysis'):
raise AnalysisException(s.split(': ', 1)[1], stackTrace)
if s.startswith('org.apache.spark.sql.catalyst.parser.ParseException: '):
raise ParseException(s.split(': ', 1)[1], stackTrace)
if s.startswith('org.apache.spark.sql.streaming.StreamingQueryException: '):
raise StreamingQueryException(s.split(': ', 1)[1], stackTrace)
if s.startswith('org.apache.spark.sql.execution.QueryExecutionException: '):
raise QueryExecutionException(s.split(': ', 1)[1], stackTrace)
if s.startswith('java.lang.IllegalArgumentException: '):
raise IllegalArgumentException(s.split(': ', 1)[1], stackTrace)
raise
return deco
def install_exception_handler():
"""
Hook an exception handler into Py4j, which could capture some SQL exceptions in Java.
When calling Java API, it will call `get_return_value` to parse the returned object.
If any exception happened in JVM, the result will be Java exception object, it raise
py4j.protocol.Py4JJavaError. We replace the original `get_return_value` with one that
could capture the Java exception and throw a Python one (with the same error message).
It's idempotent, could be called multiple times.
"""
original = py4j.protocol.get_return_value
# The original `get_return_value` is not patched, it's idempotent.
patched = capture_sql_exception(original)
# only patch the one used in py4j.java_gateway (call Java API)
py4j.java_gateway.get_return_value = patched
def toJArray(gateway, jtype, arr):
"""
Convert python list to java type array
:param gateway: Py4j Gateway
:param jtype: java type of element in array
:param arr: python type list
"""
jarr = gateway.new_array(jtype, len(arr))
for i in range(0, len(arr)):
jarr[i] = arr[i]
return jarr
def require_minimum_pandas_version():
""" Raise ImportError if minimum version of Pandas is not installed
"""
# TODO(HyukjinKwon): Relocate and deduplicate the version specification.
minimum_pandas_version = "0.19.2"
from distutils.version import LooseVersion
try:
import pandas
have_pandas = True
except ImportError:
have_pandas = False
if not have_pandas:
raise ImportError("Pandas >= %s must be installed; however, "
"it was not found." % minimum_pandas_version)
if LooseVersion(pandas.__version__) < LooseVersion(minimum_pandas_version):
raise ImportError("Pandas >= %s must be installed; however, "
"your version was %s." % (minimum_pandas_version, pandas.__version__))
def require_minimum_pyarrow_version():
""" Raise ImportError if minimum version of pyarrow is not installed
"""
# TODO(HyukjinKwon): Relocate and deduplicate the version specification.
minimum_pyarrow_version = "0.8.0"
from distutils.version import LooseVersion
try:
import pyarrow
have_arrow = True
except ImportError:
have_arrow = False
if not have_arrow:
raise ImportError("PyArrow >= %s must be installed; however, "
"it was not found." % minimum_pyarrow_version)
if LooseVersion(pyarrow.__version__) < LooseVersion(minimum_pyarrow_version):
raise ImportError("PyArrow >= %s must be installed; however, "
"your version was %s." % (minimum_pyarrow_version, pyarrow.__version__))
def require_test_compiled():
""" Raise Exception if test classes are not compiled
"""
import os
import glob
try:
spark_home = os.environ['SPARK_HOME']
except KeyError:
raise RuntimeError('SPARK_HOME is not defined in environment')
test_class_path = os.path.join(
spark_home, 'sql', 'core', 'target', '*', 'test-classes')
paths = glob.glob(test_class_path)
if len(paths) == 0:
raise RuntimeError(
"%s doesn't exist. Spark sql test classes are not compiled." % test_class_path)
class ForeachBatchFunction(object):
"""
This is the Python implementation of Java interface 'ForeachBatchFunction'. This wraps
the user-defined 'foreachBatch' function such that it can be called from the JVM when
the query is active.
"""
def __init__(self, sql_ctx, func):
self.sql_ctx = sql_ctx
self.func = func
def call(self, jdf, batch_id):
from pyspark.sql.dataframe import DataFrame
try:
self.func(DataFrame(jdf, self.sql_ctx), batch_id)
except Exception as e:
self.error = e
raise e
class Java:
implements = ['org.apache.spark.sql.execution.streaming.sources.PythonForeachBatchFunction']
|
davidnmurray/iris | refs/heads/master | lib/iris/tests/unit/fileformats/grib/load_convert/test_statistical_forecast_period_coord.py | 12 | # (C) British Crown Copyright 2014 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Tests for function
:func:`iris.fileformats.grib._load_convert.statistical_forecast_period`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# import iris tests first so that some things can be initialised
# before importing anything else.
import iris.tests as tests
import datetime
from iris.fileformats.grib._load_convert import \
statistical_forecast_period_coord
from iris.tests import mock
class Test(tests.IrisTest):
def setUp(self):
module = 'iris.fileformats.grib._load_convert'
self.module = module
self.patch_hindcast = self.patch(module + '._hindcast_fix')
self.forecast_seconds = 0.0
self.forecast_units = mock.Mock()
self.forecast_units.convert = lambda x, y: self.forecast_seconds
self.patch(module + '.time_range_unit',
return_value=self.forecast_units)
self.frt_coord = mock.Mock()
self.frt_coord.points = [1]
self.frt_coord.units.num2date = mock.Mock(
return_value=datetime.datetime(2010, 2, 3))
self.section = {}
self.section['yearOfEndOfOverallTimeInterval'] = 2010
self.section['monthOfEndOfOverallTimeInterval'] = 2
self.section['dayOfEndOfOverallTimeInterval'] = 3
self.section['hourOfEndOfOverallTimeInterval'] = 8
self.section['minuteOfEndOfOverallTimeInterval'] = 0
self.section['secondOfEndOfOverallTimeInterval'] = 0
self.section['forecastTime'] = mock.Mock()
self.section['indicatorOfUnitOfTimeRange'] = mock.Mock()
def test_basic(self):
coord = statistical_forecast_period_coord(self.section,
self.frt_coord)
self.assertEqual(coord.standard_name, 'forecast_period')
self.assertEqual(coord.units, 'hours')
self.assertArrayAlmostEqual(coord.points, [4.0])
self.assertArrayAlmostEqual(coord.bounds, [[0.0, 8.0]])
def test_with_hindcast(self):
coord = statistical_forecast_period_coord(self.section,
self.frt_coord)
self.assertEqual(self.patch_hindcast.call_count, 1)
def test_no_hindcast(self):
self.patch(self.module + '.options.support_hindcast_values', False)
coord = statistical_forecast_period_coord(self.section,
self.frt_coord)
self.assertEqual(self.patch_hindcast.call_count, 0)
if __name__ == '__main__':
tests.main()
|
i404ed/portfolio-dir | refs/heads/master | portfolio/settings.py | 1 | """
Django settings for resume project.
Generated by 'django-admin startproject' using Django 2.0.dev20170505004518.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import os
from decouple import config
from unipath import Path
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'jk^c1g3w6lu$uu@r7aoy-kr(*azs21k93lfx8zr)7xu3o2*tr('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
# Application definition
DEFAULT_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles'
]
THIRD_PARTY_APPS = [
]
LOCAL_APPS = [
'portfolio.apps.core',
'portfolio.apps.resume'
]
INSTALLED_APPS = DEFAULT_APPS + THIRD_PARTY_APPS + LOCAL_APPS
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'portfolio.urls'
WSGI_APPLICATION = 'portfolio.wsgi.application'
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
# https://docs.djangoproject.com/en/1.11/ref/databases/#connecting-to-the-database
DATABASES = {
'sqlite': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': os.path.join(BASE_DIR, os.path.join(BASE_DIR, 'root.mysql.cnf')),
},
}
}
# Password validation
# https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
AUTHY_API_KEY = config('AUTHY_API_KEY', default='')
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
# https://docs.djangoproject.com/en/1.11/ref/contrib/staticfiles/
PROJECT_DIR = Path(__file__).parent
STATIC_ROOT = PROJECT_DIR.parent.parent.child('static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, "static"),
os.path.join(BASE_DIR, "node_modules"),
)
MEDIA_ROOT = PROJECT_DIR.parent.parent.child('media')
MEDIA_URL = '/media/'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [PROJECT_DIR.child('templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
|
valsteen/ableton-live-webapi | refs/heads/master | ext_libs/Cython/Debugger/Tests/test_libcython_in_gdb.py | 112 | """
Tests that run inside GDB.
Note: debug information is already imported by the file generated by
Cython.Debugger.Cygdb.make_command_file()
"""
import os
import re
import sys
import trace
import inspect
import warnings
import unittest
import textwrap
import tempfile
import functools
import traceback
import itertools
from test import test_support
import gdb
from Cython.Debugger import libcython
from Cython.Debugger import libpython
from Cython.Debugger.Tests import TestLibCython as test_libcython
# for some reason sys.argv is missing in gdb
sys.argv = ['gdb']
def print_on_call_decorator(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
_debug(type(self).__name__, func.__name__)
try:
return func(self, *args, **kwargs)
except Exception, e:
_debug("An exception occurred:", traceback.format_exc(e))
raise
return wrapper
class TraceMethodCallMeta(type):
def __init__(self, name, bases, dict):
for func_name, func in dict.iteritems():
if inspect.isfunction(func):
setattr(self, func_name, print_on_call_decorator(func))
class DebugTestCase(unittest.TestCase):
"""
Base class for test cases. On teardown it kills the inferior and unsets
all breakpoints.
"""
__metaclass__ = TraceMethodCallMeta
def __init__(self, name):
super(DebugTestCase, self).__init__(name)
self.cy = libcython.cy
self.module = libcython.cy.cython_namespace['codefile']
self.spam_func, self.spam_meth = libcython.cy.functions_by_name['spam']
self.ham_func = libcython.cy.functions_by_qualified_name[
'codefile.ham']
self.eggs_func = libcython.cy.functions_by_qualified_name[
'codefile.eggs']
def read_var(self, varname, cast_to=None):
result = gdb.parse_and_eval('$cy_cvalue("%s")' % varname)
if cast_to:
result = cast_to(result)
return result
def local_info(self):
return gdb.execute('info locals', to_string=True)
def lineno_equals(self, source_line=None, lineno=None):
if source_line is not None:
lineno = test_libcython.source_to_lineno[source_line]
frame = gdb.selected_frame()
self.assertEqual(libcython.cython_info.lineno(frame), lineno)
def break_and_run(self, source_line):
break_lineno = test_libcython.source_to_lineno[source_line]
gdb.execute('cy break codefile:%d' % break_lineno, to_string=True)
gdb.execute('run', to_string=True)
def tearDown(self):
gdb.execute('delete breakpoints', to_string=True)
try:
gdb.execute('kill inferior 1', to_string=True)
except RuntimeError:
pass
gdb.execute('set args -c "import codefile"')
class TestDebugInformationClasses(DebugTestCase):
def test_CythonModule(self):
"test that debug information was parsed properly into data structures"
self.assertEqual(self.module.name, 'codefile')
global_vars = ('c_var', 'python_var', '__name__',
'__builtins__', '__doc__', '__file__')
assert set(global_vars).issubset(self.module.globals)
def test_CythonVariable(self):
module_globals = self.module.globals
c_var = module_globals['c_var']
python_var = module_globals['python_var']
self.assertEqual(c_var.type, libcython.CObject)
self.assertEqual(python_var.type, libcython.PythonObject)
self.assertEqual(c_var.qualified_name, 'codefile.c_var')
def test_CythonFunction(self):
self.assertEqual(self.spam_func.qualified_name, 'codefile.spam')
self.assertEqual(self.spam_meth.qualified_name,
'codefile.SomeClass.spam')
self.assertEqual(self.spam_func.module, self.module)
assert self.eggs_func.pf_cname, (self.eggs_func, self.eggs_func.pf_cname)
assert not self.ham_func.pf_cname
assert not self.spam_func.pf_cname
assert not self.spam_meth.pf_cname
self.assertEqual(self.spam_func.type, libcython.CObject)
self.assertEqual(self.ham_func.type, libcython.CObject)
self.assertEqual(self.spam_func.arguments, ['a'])
self.assertEqual(self.spam_func.step_into_functions,
set(['puts', 'some_c_function']))
expected_lineno = test_libcython.source_to_lineno['def spam(a=0):']
self.assertEqual(self.spam_func.lineno, expected_lineno)
self.assertEqual(sorted(self.spam_func.locals), list('abcd'))
class TestParameters(unittest.TestCase):
def test_parameters(self):
gdb.execute('set cy_colorize_code on')
assert libcython.parameters.colorize_code
gdb.execute('set cy_colorize_code off')
assert not libcython.parameters.colorize_code
class TestBreak(DebugTestCase):
def test_break(self):
breakpoint_amount = len(gdb.breakpoints() or ())
gdb.execute('cy break codefile.spam')
self.assertEqual(len(gdb.breakpoints()), breakpoint_amount + 1)
bp = gdb.breakpoints()[-1]
self.assertEqual(bp.type, gdb.BP_BREAKPOINT)
assert self.spam_func.cname in bp.location
assert bp.enabled
def test_python_break(self):
gdb.execute('cy break -p join')
assert 'def join(' in gdb.execute('cy run', to_string=True)
def test_break_lineno(self):
beginline = 'import os'
nextline = 'cdef int c_var = 12'
self.break_and_run(beginline)
self.lineno_equals(beginline)
step_result = gdb.execute('cy step', to_string=True)
self.lineno_equals(nextline)
assert step_result.rstrip().endswith(nextline)
class TestKilled(DebugTestCase):
def test_abort(self):
gdb.execute("set args -c 'import os; os.abort()'")
output = gdb.execute('cy run', to_string=True)
assert 'abort' in output.lower()
class DebugStepperTestCase(DebugTestCase):
def step(self, varnames_and_values, source_line=None, lineno=None):
gdb.execute(self.command)
for varname, value in varnames_and_values:
self.assertEqual(self.read_var(varname), value, self.local_info())
self.lineno_equals(source_line, lineno)
class TestStep(DebugStepperTestCase):
"""
Test stepping. Stepping happens in the code found in
Cython/Debugger/Tests/codefile.
"""
def test_cython_step(self):
gdb.execute('cy break codefile.spam')
gdb.execute('run', to_string=True)
self.lineno_equals('def spam(a=0):')
gdb.execute('cy step', to_string=True)
self.lineno_equals('b = c = d = 0')
self.command = 'cy step'
self.step([('b', 0)], source_line='b = 1')
self.step([('b', 1), ('c', 0)], source_line='c = 2')
self.step([('c', 2)], source_line='int(10)')
self.step([], source_line='puts("spam")')
gdb.execute('cont', to_string=True)
self.assertEqual(len(gdb.inferiors()), 1)
self.assertEqual(gdb.inferiors()[0].pid, 0)
def test_c_step(self):
self.break_and_run('some_c_function()')
gdb.execute('cy step', to_string=True)
self.assertEqual(gdb.selected_frame().name(), 'some_c_function')
def test_python_step(self):
self.break_and_run('os.path.join("foo", "bar")')
result = gdb.execute('cy step', to_string=True)
curframe = gdb.selected_frame()
self.assertEqual(curframe.name(), 'PyEval_EvalFrameEx')
pyframe = libpython.Frame(curframe).get_pyop()
# With Python 3 inferiors, pyframe.co_name will return a PyUnicodePtr,
# be compatible
frame_name = pyframe.co_name.proxyval(set())
self.assertEqual(frame_name, 'join')
assert re.match(r'\d+ def join\(', result), result
class TestNext(DebugStepperTestCase):
def test_cython_next(self):
self.break_and_run('c = 2')
lines = (
'int(10)',
'puts("spam")',
'os.path.join("foo", "bar")',
'some_c_function()',
)
for line in lines:
gdb.execute('cy next')
self.lineno_equals(line)
class TestLocalsGlobals(DebugTestCase):
def test_locals(self):
self.break_and_run('int(10)')
result = gdb.execute('cy locals', to_string=True)
assert 'a = 0', repr(result)
assert 'b = (int) 1', result
assert 'c = (int) 2' in result, repr(result)
def test_globals(self):
self.break_and_run('int(10)')
result = gdb.execute('cy globals', to_string=True)
assert '__name__ ' in result, repr(result)
assert '__doc__ ' in result, repr(result)
assert 'os ' in result, repr(result)
assert 'c_var ' in result, repr(result)
assert 'python_var ' in result, repr(result)
class TestBacktrace(DebugTestCase):
def test_backtrace(self):
libcython.parameters.colorize_code.value = False
self.break_and_run('os.path.join("foo", "bar")')
def match_backtrace_output(result):
assert re.search(r'\#\d+ *0x.* in spam\(\) at .*codefile\.pyx:22',
result), result
assert 'os.path.join("foo", "bar")' in result, result
result = gdb.execute('cy bt', to_string=True)
match_backtrace_output(result)
result = gdb.execute('cy bt -a', to_string=True)
match_backtrace_output(result)
# Apparently not everyone has main()
# assert re.search(r'\#0 *0x.* in main\(\)', result), result
class TestFunctions(DebugTestCase):
def test_functions(self):
self.break_and_run('c = 2')
result = gdb.execute('print $cy_cname("b")', to_string=True)
assert re.search('__pyx_.*b', result), result
result = gdb.execute('print $cy_lineno()', to_string=True)
supposed_lineno = test_libcython.source_to_lineno['c = 2']
assert str(supposed_lineno) in result, (supposed_lineno, result)
result = gdb.execute('print $cy_cvalue("b")', to_string=True)
assert '= 1' in result
class TestPrint(DebugTestCase):
def test_print(self):
self.break_and_run('c = 2')
result = gdb.execute('cy print b', to_string=True)
self.assertEqual('b = (int) 1\n', result)
class TestUpDown(DebugTestCase):
def test_updown(self):
self.break_and_run('os.path.join("foo", "bar")')
gdb.execute('cy step')
self.assertRaises(RuntimeError, gdb.execute, 'cy down')
result = gdb.execute('cy up', to_string=True)
assert 'spam()' in result
assert 'os.path.join("foo", "bar")' in result
class TestExec(DebugTestCase):
def setUp(self):
super(TestExec, self).setUp()
self.fd, self.tmpfilename = tempfile.mkstemp()
self.tmpfile = os.fdopen(self.fd, 'r+')
def tearDown(self):
super(TestExec, self).tearDown()
try:
self.tmpfile.close()
finally:
os.remove(self.tmpfilename)
def eval_command(self, command):
gdb.execute('cy exec open(%r, "w").write(str(%s))' %
(self.tmpfilename, command))
return self.tmpfile.read().strip()
def test_cython_exec(self):
self.break_and_run('os.path.join("foo", "bar")')
# test normal behaviour
self.assertEqual("[0]", self.eval_command('[a]'))
# test multiline code
result = gdb.execute(textwrap.dedent('''\
cy exec
pass
"nothing"
end
'''))
result = self.tmpfile.read().rstrip()
self.assertEqual('', result)
def test_python_exec(self):
self.break_and_run('os.path.join("foo", "bar")')
gdb.execute('cy step')
gdb.execute('cy exec some_random_var = 14')
self.assertEqual('14', self.eval_command('some_random_var'))
class CySet(DebugTestCase):
def test_cyset(self):
self.break_and_run('os.path.join("foo", "bar")')
gdb.execute('cy set a = $cy_eval("{None: []}")')
stringvalue = self.read_var("a", cast_to=str)
self.assertEqual(stringvalue, "{None: []}")
class TestCyEval(DebugTestCase):
"Test the $cy_eval() gdb function."
def test_cy_eval(self):
# This function leaks a few objects in the GDB python process. This
# is no biggie
self.break_and_run('os.path.join("foo", "bar")')
result = gdb.execute('print $cy_eval("None")', to_string=True)
assert re.match(r'\$\d+ = None\n', result), result
result = gdb.execute('print $cy_eval("[a]")', to_string=True)
assert re.match(r'\$\d+ = \[0\]', result), result
class TestClosure(DebugTestCase):
def break_and_run_func(self, funcname):
gdb.execute('cy break ' + funcname)
gdb.execute('cy run')
def test_inner(self):
self.break_and_run_func('inner')
self.assertEqual('', gdb.execute('cy locals', to_string=True))
# Allow the Cython-generated code to initialize the scope variable
gdb.execute('cy step')
self.assertEqual(str(self.read_var('a')), "'an object'")
print_result = gdb.execute('cy print a', to_string=True).strip()
self.assertEqual(print_result, "a = 'an object'")
def test_outer(self):
self.break_and_run_func('outer')
self.assertEqual('', gdb.execute('cy locals', to_string=True))
# Initialize scope with 'a' uninitialized
gdb.execute('cy step')
self.assertEqual('', gdb.execute('cy locals', to_string=True))
# Initialize 'a' to 1
gdb.execute('cy step')
print_result = gdb.execute('cy print a', to_string=True).strip()
self.assertEqual(print_result, "a = 'an object'")
_do_debug = os.environ.get('GDB_DEBUG')
if _do_debug:
_debug_file = open('/dev/tty', 'w')
def _debug(*messages):
if _do_debug:
messages = itertools.chain([sys._getframe(1).f_code.co_name, ':'],
messages)
_debug_file.write(' '.join(str(msg) for msg in messages) + '\n')
def run_unittest_in_module(modulename):
try:
gdb.lookup_type('PyModuleObject')
except RuntimeError:
msg = ("Unable to run tests, Python was not compiled with "
"debugging information. Either compile python with "
"-g or get a debug build (configure with --with-pydebug).")
warnings.warn(msg)
os._exit(1)
else:
m = __import__(modulename, fromlist=[''])
tests = inspect.getmembers(m, inspect.isclass)
# test_support.run_unittest(tests)
test_loader = unittest.TestLoader()
suite = unittest.TestSuite(
[test_loader.loadTestsFromTestCase(cls) for name, cls in tests])
result = unittest.TextTestRunner(verbosity=1).run(suite)
return result.wasSuccessful()
def runtests():
"""
Run the libcython and libpython tests. Ensure that an appropriate status is
returned to the parent test process.
"""
from Cython.Debugger.Tests import test_libpython_in_gdb
success_libcython = run_unittest_in_module(__name__)
success_libpython = run_unittest_in_module(test_libpython_in_gdb.__name__)
if not success_libcython or not success_libpython:
sys.exit(2)
def main(version, trace_code=False):
global inferior_python_version
inferior_python_version = version
if trace_code:
tracer = trace.Trace(count=False, trace=True, outfile=sys.stderr,
ignoredirs=[sys.prefix, sys.exec_prefix])
tracer.runfunc(runtests)
else:
runtests()
|
lilleswing/deepchem | refs/heads/master | deepchem/feat/tests/test_atomic_coordinates.py | 1 | """
Test atomic coordinates and neighbor lists.
"""
import os
import logging
import numpy as np
import unittest
from deepchem.utils import conformers
from deepchem.feat import AtomicCoordinates
from deepchem.feat import NeighborListAtomicCoordinates
from deepchem.feat import NeighborListComplexAtomicCoordinates
logger = logging.getLogger(__name__)
class TestAtomicCoordinates(unittest.TestCase):
"""
Test AtomicCoordinates.
"""
def setUp(self):
"""
Set up tests.
"""
smiles = 'CC(=O)OC1=CC=CC=C1C(=O)O'
from rdkit import Chem
mol = Chem.MolFromSmiles(smiles)
engine = conformers.ConformerGenerator(max_conformers=1)
self.mol = engine.generate_conformers(mol)
self.get_angstrom_coords = AtomicCoordinates()._featurize
assert self.mol.GetNumConformers() > 0
def test_atomic_coordinates(self):
"""
Simple test that atomic coordinates returns ndarray of right shape.
"""
N = self.mol.GetNumAtoms()
atomic_coords_featurizer = AtomicCoordinates()
coords = atomic_coords_featurizer._featurize(self.mol)
assert isinstance(coords, np.ndarray)
assert coords.shape == (N, 3)
def test_neighbor_list_shape(self):
"""
Simple test that Neighbor Lists have right shape.
"""
nblist_featurizer = NeighborListAtomicCoordinates()
N = self.mol.GetNumAtoms()
coords = self.get_angstrom_coords(self.mol)
nblist_featurizer = NeighborListAtomicCoordinates()
nblist = nblist_featurizer._featurize(self.mol)[1]
assert isinstance(nblist, dict)
assert len(nblist.keys()) == N
for (atom, neighbors) in nblist.items():
assert isinstance(atom, int)
assert isinstance(neighbors, list)
assert len(neighbors) <= N
# Do a manual distance computation and make
for i in range(N):
for j in range(N):
dist = np.linalg.norm(coords[i] - coords[j])
logger.info("Distance(%d, %d) = %f" % (i, j, dist))
if dist < nblist_featurizer.neighbor_cutoff and i != j:
assert j in nblist[i]
else:
assert j not in nblist[i]
def test_neighbor_list_extremes(self):
"""
Test Neighbor Lists with large/small boxes.
"""
N = self.mol.GetNumAtoms()
# Test with cutoff 0 angstroms. There should be no neighbors in this case.
nblist_featurizer = NeighborListAtomicCoordinates(neighbor_cutoff=.1)
nblist = nblist_featurizer._featurize(self.mol)[1]
for atom in range(N):
assert len(nblist[atom]) == 0
# Test with cutoff 100 angstroms. Everything should be neighbors now.
nblist_featurizer = NeighborListAtomicCoordinates(neighbor_cutoff=100)
nblist = nblist_featurizer._featurize(self.mol)[1]
for atom in range(N):
assert len(nblist[atom]) == N - 1
def test_neighbor_list_max_num_neighbors(self):
"""
Test that neighbor lists return only max_num_neighbors.
"""
N = self.mol.GetNumAtoms()
max_num_neighbors = 1
nblist_featurizer = NeighborListAtomicCoordinates(max_num_neighbors)
nblist = nblist_featurizer._featurize(self.mol)[1]
for atom in range(N):
assert len(nblist[atom]) <= max_num_neighbors
# Do a manual distance computation and ensure that selected neighbor is
# closest since we set max_num_neighbors = 1
coords = self.get_angstrom_coords(self.mol)
for i in range(N):
closest_dist = np.inf
closest_nbr = None
for j in range(N):
if i == j:
continue
dist = np.linalg.norm(coords[i] - coords[j])
logger.info("Distance(%d, %d) = %f" % (i, j, dist))
if dist < closest_dist:
closest_dist = dist
closest_nbr = j
logger.info("Closest neighbor to %d is %d" % (i, closest_nbr))
logger.info("Distance: %f" % closest_dist)
if closest_dist < nblist_featurizer.neighbor_cutoff:
assert nblist[i] == [closest_nbr]
else:
assert nblist[i] == []
def test_neighbor_list_periodic(self):
"""Test building a neighbor list with periodic boundary conditions."""
cutoff = 4.0
box_size = np.array([10.0, 8.0, 9.0])
N = self.mol.GetNumAtoms()
coords = self.get_angstrom_coords(self.mol)
featurizer = NeighborListAtomicCoordinates(
neighbor_cutoff=cutoff, periodic_box_size=box_size)
neighborlist = featurizer._featurize(self.mol)[1]
expected_neighbors = [set() for i in range(N)]
for i in range(N):
for j in range(i):
delta = coords[i] - coords[j]
delta -= np.round(delta / box_size) * box_size
if np.linalg.norm(delta) < cutoff:
expected_neighbors[i].add(j)
expected_neighbors[j].add(i)
for i in range(N):
assert (set(neighborlist[i]) == expected_neighbors[i])
def test_complex_featurization_simple(self):
"""Test Neighbor List computation on protein-ligand complex."""
dir_path = os.path.dirname(os.path.realpath(__file__))
ligand_file = os.path.join(dir_path, "data/3zso_ligand_hyd.pdb")
protein_file = os.path.join(dir_path, "data/3zso_protein.pdb")
max_num_neighbors = 4
complex_featurizer = NeighborListComplexAtomicCoordinates(max_num_neighbors)
system_coords, system_neighbor_list = complex_featurizer._featurize(
ligand_file, protein_file)
N = system_coords.shape[0]
assert len(system_neighbor_list.keys()) == N
for atom in range(N):
assert len(system_neighbor_list[atom]) <= max_num_neighbors
# TODO(rbharath): This test will be uncommented in the next PR up on the docket.
# def test_full_complex_featurization(self):
# """Unit test for ComplexNeighborListFragmentAtomicCoordinates."""
# dir_path = os.path.dirname(os.path.realpath(__file__))
# ligand_file = os.path.join(dir_path, "data/3zso_ligand_hyd.pdb")
# protein_file = os.path.join(dir_path, "data/3zso_protein.pdb")
# # Pulled from PDB files. For larger datasets with more PDBs, would use
# # max num atoms instead of exact.
# frag1_num_atoms = 44 # for ligand atoms
# frag2_num_atoms = 2336 # for protein atoms
# complex_num_atoms = 2380 # in total
# max_num_neighbors = 4
# # Cutoff in angstroms
# neighbor_cutoff = 4
# complex_featurizer = ComplexNeighborListFragmentAtomicCoordinates(
# frag1_num_atoms, frag2_num_atoms, complex_num_atoms, max_num_neighbors,
# neighbor_cutoff)
# (frag1_coords, frag1_neighbor_list, frag1_z, frag2_coords,
# frag2_neighbor_list, frag2_z, complex_coords,
# complex_neighbor_list, complex_z) = complex_featurizer._featurize_complex(
# ligand_file, protein_file)
#
# assert frag1_coords.shape == (frag1_num_atoms, 3)
# self.assertEqual(
# sorted(list(frag1_neighbor_list.keys())), list(range(frag1_num_atoms)))
# self.assertEqual(frag1_z.shape, (frag1_num_atoms,))
#
# self.assertEqual(frag2_coords.shape, (frag2_num_atoms, 3))
# self.assertEqual(
# sorted(list(frag2_neighbor_list.keys())), list(range(frag2_num_atoms)))
# self.assertEqual(frag2_z.shape, (frag2_num_atoms,))
#
# self.assertEqual(complex_coords.shape, (complex_num_atoms, 3))
# self.assertEqual(
# sorted(list(complex_neighbor_list.keys())),
# list(range(complex_num_atoms)))
# self.assertEqual(complex_z.shape, (complex_num_atoms,))
|
paprykarz/vdebug | refs/heads/master | python3/vdebug/session.py | 2 | import socket
import vim
from . import dbgp
from . import error
from . import event
from . import listener
from . import log
from . import opts
from . import util
class SessionHandler:
def __init__(self, ui, breakpoints):
self.__ui = ui
self.__breakpoints = breakpoints
self.__ex_handler = util.ExceptionHandler(self)
self.__session = None
self.listener = None
def dispatch_event(self, name, *args):
event.Dispatcher(self).dispatch_event(name, *args)
def ui(self):
return self.__ui
def breakpoints(self):
return self.__breakpoints
def session(self):
return self.__session
def listen(self):
if self.listener and self.listener.is_listening():
print("Waiting for a connection: none found so far")
elif self.listener and self.listener.is_ready():
print("Found connection, starting debugger")
log.Log("Got connection, starting", log.Logger.DEBUG)
self.__new_session()
else:
self.start_listener()
def start_listener(self):
self.listener = listener.Listener.create()
print("Vdebug will wait for a connection")
util.Environment.reload()
if self.is_open():
self.ui().set_status("listening")
self.listener.start()
self.start_if_ready()
def stop_listening(self):
if self.listener:
self.listener.stop()
self.ui().say("Vdebug stopped waiting for a connection")
if self.__session:
self.__session.close_connection()
def run(self):
if self.is_connected():
self.dispatch_event("run")
else:
self.listen()
def stop(self, quiet=False):
if self.is_connected():
self.__session.close_connection()
elif self.is_listening():
self.stop_listening()
elif self.is_open():
self.__ui.close()
else:
if False is quiet:
self.__ui.say("Vdebug is not running")
def close(self):
self.stop_listening()
if self.is_connected():
self.__session.close_connection()
if self.is_open():
self.__ui.close()
def is_connected(self):
return self.__session and self.__session.is_connected()
def is_listening(self):
return self.listener and self.listener.is_listening()
def is_open(self):
return self.__ui.is_open
def status(self):
if self.is_connected():
return "running"
return self.listener.status()
def status_for_statusline(self):
return "vdebug(%s)" % self.status()
def start_if_ready(self):
try:
if self.listener.is_ready():
print("Found connection, starting debugger")
log.Log("Got connection, starting", log.Logger.DEBUG)
self.__new_session()
return True
return False
except Exception as e:
print("Error starting Vdebug: %s" %
self.__ex_handler.exception_to_string(e))
def __new_session(self):
log.Log("create session", log.Logger.DEBUG)
self.__session = Session(self.__ui, self.__breakpoints,
util.Keymapper())
log.Log("start session", log.Logger.DEBUG)
status = self.__session.start(self.listener.create_connection())
log.Log("refresh event", log.Logger.DEBUG)
self.dispatch_event("refresh", status)
class Session:
def __init__(self, ui, breakpoints, keymapper):
self.__ui = ui
self.__breakpoints = breakpoints
self.__keymapper = keymapper
self.__api = None
self.cur_file = None
self.cur_lineno = None
self.context_names = None
def api(self):
return self.__api
def keymapper(self):
return self.__keymapper
def is_connected(self):
return self.__api is not None
def is_open(self):
return self.__ui.is_open
def ui(self):
return self.__ui
def close(self):
""" Close both the connection and vdebug.ui.
"""
self.close_connection()
self.__ui.close()
self.__keymapper.unmap()
def close_connection(self, stop=True):
""" Close the connection to the debugger.
"""
self.__ui.mark_as_stopped()
try:
if self.is_connected():
log.Log("Closing the connection")
if stop:
if opts.Options.get('on_close') == 'detach':
try:
self.__api.detach()
except dbgp.CmdNotImplementedError:
self.__ui.error('Detach is not supported by the '
'debugger, stopping instead')
opts.Options.overwrite('on_close', 'stop')
self.__api.stop()
else:
self.__api.stop()
self.__api.conn.close()
self.__api = None
self.__breakpoints.unlink_api()
else:
self.__api = None
self.__breakpoints.unlink_api()
except EOFError:
self.__api = None
self.__ui.say("Connection has been closed")
except socket.error:
self.__api = None
self.__ui.say("Connection has been closed")
def start(self, connection):
util.Environment.reload()
if self.__ui.is_modified():
raise error.ModifiedBufferError("Modified buffers must be saved "
"before debugging")
try:
self.__api = dbgp.Api(connection)
if not self.is_open():
self.__ui.open()
self.__keymapper.map()
self.__ui.set_listener_details(opts.Options.get('server'),
opts.Options.get('port'),
opts.Options.get('ide_key'))
addr = self.__api.conn.address
log.Log("Found connection from %s" % str(addr), log.Logger.INFO)
self.__ui.set_conn_details(addr[0], addr[1])
self.__collect_context_names()
self.__check_features() # only for debugging at the moment
self.__set_default_features() # features we try by default
self.__set_features() # user defined features
self.__initialize_breakpoints()
if opts.Options.get('break_on_open', int) == 1:
log.Log('starting with step_into (break_on_open = 1)', log.Logger.DEBUG)
status = self.__api.step_into()
else:
log.Log('starting with run (break_on_open = 0)', log.Logger.DEBUG)
status = self.__api.run()
return status
except Exception:
self.close()
raise
def detach(self):
"""Detach the debugger engine, and allow it to continue execution.
"""
if self.is_connected():
self.__ui.say("Detaching the debugger")
self.__api.detach()
self.close_connection(False)
def __check_features(self):
must_features = [
'language_supports_threads',
'language_name',
'language_version',
'encoding', # has set
'protocol_version',
'supports_async',
'data_encoding',
'breakpoint_languages',
'breakpoint_types',
'resolved_breakpoints',
'multiple_sessions', # has set
'max_children', # has set
'max_data', # has set
'max_depth', # has set
'extended_properties', # has set
]
maybe_features = [
'supported_encodings',
'supports_postmortem',
'show_hidden', # has set
'notify_ok', # has set
]
for feature in must_features:
try:
feature_value = self.__api.feature_get(feature)
log.Log(
"Must Feature: %s = %s" % (feature, str(feature_value)),
log.Logger.DEBUG
)
except dbgp.DBGPError:
error_str = "Failed to get feature %s" % feature
log.Log(error_str, log.Logger.DEBUG)
for feature in maybe_features:
try:
feature_value = self.__api.feature_get(feature)
log.Log(
"Maybe Feature: %s = %s" % (feature, str(feature_value)),
log.Logger.DEBUG
)
except dbgp.DBGPError:
error_str = "Failed to get feature %s" % feature
log.Log(error_str, log.Logger.DEBUG)
def __set_default_features(self):
features = {
'multiple_sessions': 0, # explicitly disable multiple sessions atm
'extended_properties': 1,
}
for name, value in features.items():
try:
self.__api.feature_set(name, value)
except dbgp.DBGPError as e:
error_str = "Failed to set feature %s: %s" % (name, e.args[0])
log.Log(error_str, log.Logger.DEBUG)
def __set_features(self):
"""Evaluate vim dictionary of features and pass to debugger.
Errors are caught if the debugger doesn't like the feature name or
value. This doesn't break the loop, so multiple features can be set
even in the case of an error."""
features = vim.eval('g:vdebug_features')
for name, value in features.items():
try:
self.__api.feature_set(name, value)
except dbgp.DBGPError as e:
error_str = "Failed to set feature %s: %s" % (name, e.args[0])
self.__ui.error(error_str)
def __initialize_breakpoints(self):
self.__breakpoints.update_lines(
self.__ui.get_breakpoint_sign_positions())
self.__breakpoints.link_api(self.__api)
def __collect_context_names(self):
cn_res = self.__api.context_names()
self.context_names = cn_res.names()
log.Log("Available context names: %s" % self.context_names,
log.Logger.DEBUG)
|
SlimRemix/android_external_chromium_org | refs/heads/lp5.1 | tools/telemetry/telemetry/core/platform/android_device_unittest.py | 26 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from telemetry.core.platform import android_device
from telemetry.unittest import system_stub
class AndroidDeviceTest(unittest.TestCase):
def setUp(self):
self._android_device_stub = system_stub.Override(
android_device, ['adb_commands'])
def testGetAllAttachedAndroidDevices(self):
self._android_device_stub.adb_commands.attached_devices = [
'01', '02']
self.assertEquals(
set(['01', '02']),
set(device.device_id for device in
android_device.AndroidDevice.GetAllConnectedDevices()
))
def tearDown(self):
self._android_device_stub.Restore()
|
chinmaygarde/mojo | refs/heads/ios | third_party/re2/re2/make_unicode_groups.py | 219 | #!/usr/bin/python
# Copyright 2008 The RE2 Authors. All Rights Reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""Generate C++ tables for Unicode Script and Category groups."""
import sys
import unicode
_header = """
// GENERATED BY make_unicode_groups.py; DO NOT EDIT.
// make_unicode_groups.py >unicode_groups.cc
#include "re2/unicode_groups.h"
namespace re2 {
"""
_trailer = """
} // namespace re2
"""
n16 = 0
n32 = 0
def MakeRanges(codes):
"""Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]]"""
ranges = []
last = -100
for c in codes:
if c == last+1:
ranges[-1][1] = c
else:
ranges.append([c, c])
last = c
return ranges
def PrintRanges(type, name, ranges):
"""Print the ranges as an array of type named name."""
print "static %s %s[] = {" % (type, name,)
for lo, hi in ranges:
print "\t{ %d, %d }," % (lo, hi)
print "};"
# def PrintCodes(type, name, codes):
# """Print the codes as an array of type named name."""
# print "static %s %s[] = {" % (type, name,)
# for c in codes:
# print "\t%d," % (c,)
# print "};"
def PrintGroup(name, codes):
"""Print the data structures for the group of codes.
Return a UGroup literal for the group."""
# See unicode_groups.h for a description of the data structure.
# Split codes into 16-bit ranges and 32-bit ranges.
range16 = MakeRanges([c for c in codes if c < 65536])
range32 = MakeRanges([c for c in codes if c >= 65536])
# Pull singleton ranges out of range16.
# code16 = [lo for lo, hi in range16 if lo == hi]
# range16 = [[lo, hi] for lo, hi in range16 if lo != hi]
global n16
global n32
n16 += len(range16)
n32 += len(range32)
ugroup = "{ \"%s\", +1" % (name,)
# if len(code16) > 0:
# PrintCodes("uint16", name+"_code16", code16)
# ugroup += ", %s_code16, %d" % (name, len(code16))
# else:
# ugroup += ", 0, 0"
if len(range16) > 0:
PrintRanges("URange16", name+"_range16", range16)
ugroup += ", %s_range16, %d" % (name, len(range16))
else:
ugroup += ", 0, 0"
if len(range32) > 0:
PrintRanges("URange32", name+"_range32", range32)
ugroup += ", %s_range32, %d" % (name, len(range32))
else:
ugroup += ", 0, 0"
ugroup += " }"
return ugroup
def main():
print _header
ugroups = []
for name, codes in unicode.Categories().iteritems():
ugroups.append(PrintGroup(name, codes))
for name, codes in unicode.Scripts().iteritems():
ugroups.append(PrintGroup(name, codes))
print "// %d 16-bit ranges, %d 32-bit ranges" % (n16, n32)
print "UGroup unicode_groups[] = {";
ugroups.sort()
for ug in ugroups:
print "\t%s," % (ug,)
print "};"
print "int num_unicode_groups = %d;" % (len(ugroups),)
print _trailer
if __name__ == '__main__':
main()
|
robinro/ansible | refs/heads/devel | lib/ansible/modules/cloud/dimensiondata/dimensiondata_network.py | 42 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Dimension Data
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software. If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
# - Aimon Bustardo <aimon.bustardo@dimensiondata.com>
# - Bert Diwa <Lamberto.Diwa@dimensiondata.com>
# - Adam Friedman <tintoy@tintoy.io>
#
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: dimensiondata_network
short_description: Create, update, and delete MCP 1.0 & 2.0 networks
extends_documentation_fragment:
- dimensiondata
- dimensiondata_wait
description:
- Create, update, and delete MCP 1.0 & 2.0 networks
version_added: "2.3"
author: 'Aimon Bustardo (@aimonb)'
options:
name:
description:
- The name of the network domain to create.
required: true
description:
description:
- Additional description of the network domain.
required: false
service_plan:
description:
- The service plan, either “ESSENTIALS” or “ADVANCED”.
- MCP 2.0 Only.
choices: [ESSENTIALS, ADVANCED]
default: ESSENTIALS
state:
description:
- Should the resource be present or absent.
choices: [present, absent]
default: present
'''
EXAMPLES = '''
# Create an MCP 1.0 network
- dimensiondata_network:
region: na
location: NA5
name: mynet
# Create an MCP 2.0 network
- dimensiondata_network:
region: na
mcp_user: my_user
mcp_password: my_password
location: NA9
name: mynet
service_plan: ADVANCED
# Delete a network
- dimensiondata_network:
region: na
location: NA1
name: mynet
state: absent
'''
RETURN = '''
network:
description: Dictionary describing the network.
returned: On success when I(state=present).
type: complex
contains:
id:
description: Network ID.
type: string
sample: "8c787000-a000-4050-a215-280893411a7d"
name:
description: Network name.
type: string
sample: "My network"
description:
description: Network description.
type: string
sample: "My network description"
location:
description: Datacenter location.
type: string
sample: NA3
status:
description: Network status. (MCP 2.0 only)
type: string
sample: NORMAL
private_net:
description: Private network subnet. (MCP 1.0 only)
type: string
sample: "10.2.3.0"
multicast:
description: Multicast enabled? (MCP 1.0 only)
type: boolean
sample: false
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.dimensiondata import DimensionDataModule, DimensionDataAPIException
from ansible.module_utils.pycompat24 import get_exception
try:
from libcloud.compute.base import NodeLocation
HAS_LIBCLOUD = True
except ImportError:
HAS_LIBCLOUD = False
class DimensionDataNetworkModule(DimensionDataModule):
"""
The dimensiondata_network module for Ansible.
"""
def __init__(self):
"""
Create a new Dimension Data network module.
"""
super(DimensionDataNetworkModule, self).__init__(
module=AnsibleModule(
argument_spec=DimensionDataModule.argument_spec_with_wait(
name=dict(type='str', required=True),
description=dict(type='str', required=False),
service_plan=dict(default='ESSENTIALS', choices=['ADVANCED', 'ESSENTIALS']),
state=dict(default='present', choices=['present', 'absent'])
),
required_together=DimensionDataModule.required_together()
)
)
self.name = self.module.params['name']
self.description = self.module.params['description']
self.service_plan = self.module.params['service_plan']
self.state = self.module.params['state']
def state_present(self):
network = self._get_network()
if network:
self.module.exit_json(
changed=False,
msg='Network already exists',
network=self._network_to_dict(network)
)
return
network = self._create_network()
self.module.exit_json(
changed=True,
msg='Created network "%s" in datacenter "%s".' % (self.name, self.location),
network=self._network_to_dict(network)
)
def state_absent(self):
network = self._get_network()
if not network:
self.module.exit_json(
changed=False,
msg='Network "%s" does not exist' % self.name,
network=self._network_to_dict(network)
)
return
self._delete_network(network)
def _get_network(self):
if self.mcp_version == '1.0':
networks = self.driver.list_networks(location=self.location)
else:
networks = self.driver.ex_list_network_domains(location=self.location)
matched_network = [network for network in networks if network.name == self.name]
if matched_network:
return matched_network[0]
return None
def _network_to_dict(self, network):
network_dict = dict(
id=network.id,
name=network.name,
description=network.description
)
if isinstance(network.location, NodeLocation):
network_dict['location'] = network.location.id
else:
network_dict['location'] = network.location
if self.mcp_version == '1.0':
network_dict['private_net'] = network.private_net
network_dict['multicast'] = network.multicast
network_dict['status'] = None
else:
network_dict['private_net'] = None
network_dict['multicast'] = None
network_dict['status'] = network.status
return network_dict
def _create_network(self):
# Make sure service_plan argument is defined
if self.mcp_version == '2.0' and 'service_plan' not in self.module.params:
self.module.fail_json(
msg='service_plan required when creating network and location is MCP 2.0'
)
return None
# Create network
try:
if self.mcp_version == '1.0':
network = self.driver.ex_create_network(
self.location,
self.name,
description=self.description
)
else:
network = self.driver.ex_create_network_domain(
self.location,
self.name,
self.module.params['service_plan'],
description=self.description
)
except DimensionDataAPIException:
api_exception = get_exception()
self.module.fail_json(
msg="Failed to create new network: %s" % str(api_exception)
)
return None
if self.module.params['wait'] is True:
network = self._wait_for_network_state(network.id, 'NORMAL')
return network
def _delete_network(self, network):
try:
if self.mcp_version == '1.0':
deleted = self.driver.ex_delete_network(network)
else:
deleted = self.driver.ex_delete_network_domain(network)
if deleted:
self.module.exit_json(
changed=True,
msg="Deleted network with id %s" % network.id
)
self.module.fail_json(
"Unexpected failure deleting network with id %s", network.id
)
except DimensionDataAPIException:
api_exception = get_exception()
self.module.fail_json(
msg="Failed to delete network: %s" % str(api_exception)
)
def _wait_for_network_state(self, net_id, state_to_wait_for):
try:
return self.driver.connection.wait_for_state(
state_to_wait_for,
self.driver.ex_get_network_domain,
self.module.params['wait_poll_interval'],
self.module.params['wait_time'],
net_id
)
except DimensionDataAPIException:
api_exception = get_exception()
self.module.fail_json(
msg='Network did not reach % state in time: %s' % (state_to_wait_for, api_exception.msg)
)
def main():
module = DimensionDataNetworkModule()
if module.state == 'present':
module.state_present()
elif module.state == 'absent':
module.state_absent()
if __name__ == '__main__':
main()
|
naresh21/synergetics-edx-platform | refs/heads/oxa/master.fic | openedx/core/lib/api/fields.py | 53 | """Fields useful for edX API implementations."""
from rest_framework.serializers import Field, URLField
class ExpandableField(Field):
"""Field that can dynamically use a more detailed serializer based on a user-provided "expand" parameter.
Kwargs:
collapsed_serializer (Serializer): the serializer to use for a non-expanded representation.
expanded_serializer (Serializer): the serializer to use for an expanded representation.
"""
def __init__(self, **kwargs):
"""Sets up the ExpandableField with the collapsed and expanded versions of the serializer."""
assert 'collapsed_serializer' in kwargs and 'expanded_serializer' in kwargs
self.collapsed = kwargs.pop('collapsed_serializer')
self.expanded = kwargs.pop('expanded_serializer')
super(ExpandableField, self).__init__(**kwargs)
def to_representation(self, obj):
"""
Return a representation of the field that is either expanded or collapsed.
"""
should_expand = self.field_name in self.context.get("expand", [])
field = self.expanded if should_expand else self.collapsed
# Avoid double-binding the field, otherwise we'll get
# an error about the source kwarg being redundant.
if field.source is None:
field.bind(self.field_name, self)
if should_expand:
self.expanded.context["expand"] = set(field.context.get("expand", []))
return field.to_representation(obj)
class AbsoluteURLField(URLField):
"""
Field that serializes values to absolute URLs based on the current request.
If the value to be serialized is already a URL, that value will returned.
"""
def to_representation(self, value):
request = self.context.get('request', None)
assert request is not None, (
"`%s` requires the request in the serializer context. "
"Add `context={'request': request}` when instantiating the serializer." % self.__class__.__name__
)
if value.startswith(('http:', 'https:')):
return value
return request.build_absolute_uri(value)
|
TeamExodus/external_chromium_org | refs/heads/EXODUS-5.1 | tools/site_compare/commands/measure.py | 189 | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Command for measuring how long pages take to load in a browser.
Prerequisites:
1. The command_line package from tools/site_compare
2. Either the IE BHO or Firefox extension (or both)
Installation:
1. Build the IE BHO, or call regsvr32 on a prebuilt binary
2. Add a file called "measurepageloadtimeextension@google.com" to
the default Firefox profile directory under extensions, containing
the path to the Firefox extension root
Invoke with the command line arguments as documented within
the command line.
"""
import command_line
import win32process
from drivers import windowing
from utils import browser_iterate
def CreateCommand(cmdline):
"""Inserts the command and arguments into a command line for parsing."""
cmd = cmdline.AddCommand(
["measure"],
"Measures how long a series of URLs takes to load in one or more browsers.",
None,
ExecuteMeasure)
browser_iterate.SetupIterationCommandLine(cmd)
cmd.AddArgument(
["-log", "--logfile"], "File to write output", type="string", required=True)
def ExecuteMeasure(command):
"""Executes the Measure command."""
def LogResult(url, proc, wnd, result):
"""Write the result of the browse to the log file."""
log_file.write(result)
log_file = open(command["--logfile"], "w")
browser_iterate.Iterate(command, LogResult)
# Close the log file and return. We're done.
log_file.close()
|
jabber-at/python-nbxmpp | refs/heads/master | nbxmpp/plugin.py | 1 | ## plugin.py
##
## Copyright (C) 2003-2005 Alexey "Snake" Nezhdanov
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2, or (at your option)
## any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
# $Id: client.py,v 1.52 2006/01/02 19:40:55 normanr Exp $
"""
Provides PlugIn class functionality to develop extentions for xmpppy
"""
import logging
log = logging.getLogger('nbxmpp.plugin')
class PlugIn(object):
"""
Abstract xmpppy plugin infrastructure code, providing plugging in/out and
debugging functionality
Inherit to develop pluggable objects. No code change on the owner class
required (the object where we plug into)
For every instance of PlugIn class the 'owner' is the class in what the plug
was plugged.
"""
def __init__(self):
self._exported_methods=[]
def PlugIn(self, owner, *args, **kwargs):
"""
Attach to owner and register ourself and our _exported_methods in it.
If defined by a subclass, call self.plugin(owner) to execute hook
code after plugging
"""
self._owner=owner
log.info('Plugging %s __INTO__ %s' % (self, self._owner))
if self.__class__.__name__ in owner.__dict__:
log.debug('Plugging ignored: another instance already plugged.')
return
self._old_owners_methods=[]
for method in self._exported_methods:
if method.__name__ in owner.__dict__:
self._old_owners_methods.append(owner.__dict__[method.__name__])
owner.__dict__[method.__name__]=method
if self.__class__.__name__.endswith('Dispatcher'):
# FIXME: I need BOSHDispatcher or XMPPDispatcher on .Dispatcher
# there must be a better way..
owner.__dict__['Dispatcher']=self
else:
owner.__dict__[self.__class__.__name__]=self
# Execute hook
if hasattr(self, 'plugin'):
return self.plugin(owner, *args, **kwargs)
def PlugOut(self, *args, **kwargs):
"""
Unregister our _exported_methods from owner and detach from it.
If defined by a subclass, call self.plugout() after unplugging to execute
hook code
"""
log.info('Plugging %s __OUT__ of %s.' % (self, self._owner))
for method in self._exported_methods:
del self._owner.__dict__[method.__name__]
for method in self._old_owners_methods:
self._owner.__dict__[method.__name__]=method
# FIXME: Dispatcher workaround
if self.__class__.__name__.endswith('Dispatcher'):
del self._owner.__dict__['Dispatcher']
else:
del self._owner.__dict__[self.__class__.__name__]
# Execute hook
if hasattr(self, 'plugout'):
return self.plugout(*args, **kwargs)
del self._owner
@classmethod
def get_instance(cls, *args, **kwargs):
"""
Factory Method for object creation
Use this instead of directly initializing the class in order to make
unit testing easier. For testing, this method can be patched to inject
mock objects.
"""
return cls(*args, **kwargs)
|
autoreject/autoreject | refs/heads/master | autoreject/tests/test_ransac.py | 1 | # Author: Mainak Jas <mainak.jas@telecom-paristech.fr>
# License: BSD (3-clause)
import pytest
import numpy as np
import mne
from mne.datasets import sample
from mne import io
from autoreject import Ransac
import matplotlib
matplotlib.use('Agg')
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
raw = io.read_raw_fif(raw_fname, preload=False)
raw.crop(0, 15)
raw.info['projs'] = list()
def test_ransac():
"""Some basic tests for ransac."""
event_id = {'Visual/Left': 3}
tmin, tmax = -0.2, 0.5
events = mne.find_events(raw)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,
baseline=(None, 0), decim=8,
reject=None, preload=True)
# normal case
picks = mne.pick_types(epochs.info, meg='mag', eeg=False, stim=False,
eog=False, exclude=[])
ransac = Ransac(picks=picks, random_state=np.random.RandomState(42))
epochs_clean = ransac.fit_transform(epochs)
assert len(epochs_clean) == len(epochs)
# Pass numpy instead of epochs
X = epochs.get_data()
pytest.raises(AttributeError, ransac.fit, X)
#
# should not contain both channel types
picks = mne.pick_types(epochs.info, meg=True, eeg=False, stim=False,
eog=False, exclude=[])
ransac = Ransac(picks=picks)
pytest.raises(ValueError, ransac.fit, epochs)
#
# should not contain other channel types.
picks = mne.pick_types(raw.info, meg=False, eeg=True, stim=True,
eog=False, exclude=[])
ransac = Ransac(picks=picks)
pytest.raises(ValueError, ransac.fit, epochs)
|
utamaro/youtube-dl | refs/heads/master | test/test_postprocessors.py | 151 | #!/usr/bin/env python
from __future__ import unicode_literals
# Allow direct execution
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from youtube_dl.postprocessor import MetadataFromTitlePP
class TestMetadataFromTitle(unittest.TestCase):
def test_format_to_regex(self):
pp = MetadataFromTitlePP(None, '%(title)s - %(artist)s')
self.assertEqual(pp._titleregex, '(?P<title>.+)\ \-\ (?P<artist>.+)')
|
bobellis/ghost_blog | refs/heads/master | node_modules/grunt-docker/node_modules/docker/node_modules/pygmentize-bundled/vendor/pygments/pygments/styles/trac.py | 364 | # -*- coding: utf-8 -*-
"""
pygments.styles.trac
~~~~~~~~~~~~~~~~~~~~
Port of the default trac highlighter design.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic, Whitespace
class TracStyle(Style):
"""
Port of the default trac highlighter design.
"""
default_style = ''
styles = {
Whitespace: '#bbbbbb',
Comment: 'italic #999988',
Comment.Preproc: 'bold noitalic #999999',
Comment.Special: 'bold #999999',
Operator: 'bold',
String: '#bb8844',
String.Regex: '#808000',
Number: '#009999',
Keyword: 'bold',
Keyword.Type: '#445588',
Name.Builtin: '#999999',
Name.Function: 'bold #990000',
Name.Class: 'bold #445588',
Name.Exception: 'bold #990000',
Name.Namespace: '#555555',
Name.Variable: '#008080',
Name.Constant: '#008080',
Name.Tag: '#000080',
Name.Attribute: '#008080',
Name.Entity: '#800080',
Generic.Heading: '#999999',
Generic.Subheading: '#aaaaaa',
Generic.Deleted: 'bg:#ffdddd #000000',
Generic.Inserted: 'bg:#ddffdd #000000',
Generic.Error: '#aa0000',
Generic.Emph: 'italic',
Generic.Strong: 'bold',
Generic.Prompt: '#555555',
Generic.Output: '#888888',
Generic.Traceback: '#aa0000',
Error: 'bg:#e3d2d2 #a61717'
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.