repo_name stringlengths 6 100 | path stringlengths 4 294 | copies stringlengths 1 5 | size stringlengths 4 6 | content stringlengths 606 896k | license stringclasses 15
values |
|---|---|---|---|---|---|
tvtsoft/odoo8 | addons/mail/tests/test_invite.py | 2 | 1924 | # -*- coding: utf-8 -*-
from .common import TestMail
from openerp.tools import mute_logger
class TestInvite(TestMail):
@mute_logger('openerp.addons.mail.models.mail_mail')
def test_invite_email(self):
mail_invite = self.env['mail.wizard.invite'].with_context({
'default_res_model': 'mail.channel',
'default_res_id': self.group_pigs.id
}).sudo(self.user_employee.id).create({
'partner_ids': [(4, self.user_portal.partner_id.id), (4, self.partner_1.id)],
'send_mail': True})
mail_invite.add_followers()
# Test: Pigs followers should contain Admin, Bert
self.assertEqual(self.group_pigs.message_follower_ids,
self.user_portal.partner_id | self.partner_1,
'invite wizard: Pigs followers after invite is incorrect, should be Admin + added follower')
# Test: (pretend to) send email and check subject, body
self.assertEqual(len(self._mails), 2, 'invite wizard: sent email number incorrect, should be only for Bert')
self.assertEqual(self._mails[0].get('subject'), 'Invitation to follow Discussion group: Pigs',
'invite wizard: subject of invitation email is incorrect')
self.assertEqual(self._mails[1].get('subject'), 'Invitation to follow Discussion group: Pigs',
'invite wizard: subject of invitation email is incorrect')
self.assertIn('%s invited you to follow Discussion group document: Pigs' % self.user_employee.name,
self._mails[0].get('body'),
'invite wizard: body of invitation email is incorrect')
self.assertIn('%s invited you to follow Discussion group document: Pigs' % self.user_employee.name,
self._mails[1].get('body'),
'invite wizard: body of invitation email is incorrect')
| agpl-3.0 |
openstack/cloudbase-init | cloudbaseinit/tests/utils/test_debiface.py | 3 | 2720 | # Copyright 2014 Cloudbase Solutions Srl
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import unittest
from cloudbaseinit.models import network as network_model
from cloudbaseinit.tests.metadata import fake_json_response
from cloudbaseinit.tests import testutils
from cloudbaseinit.utils import debiface
class TestInterfacesParser(unittest.TestCase):
def setUp(self):
date = "2013-04-04"
content = fake_json_response.get_fake_metadata_json(date)
self.data = content["network_config"]["debian_config"]
def _test_parse_nics(self, no_nics=False):
with testutils.LogSnatcher('cloudbaseinit.utils.'
'debiface') as snatcher:
nics = debiface.parse(self.data)
if no_nics:
expected_logging = 'Invalid Debian config to parse:'
self.assertTrue(snatcher.output[0].startswith(expected_logging))
self.assertFalse(nics)
return
# check what we've got
nic0 = network_model.NetworkDetails(
fake_json_response.NAME0,
fake_json_response.MAC0.upper(),
fake_json_response.ADDRESS0,
fake_json_response.ADDRESS60,
fake_json_response.NETMASK0,
fake_json_response.NETMASK60,
fake_json_response.BROADCAST0,
fake_json_response.GATEWAY0,
fake_json_response.GATEWAY60,
fake_json_response.DNSNS0.split()
)
nic1 = network_model.NetworkDetails(
fake_json_response.NAME1,
None,
fake_json_response.ADDRESS1,
fake_json_response.ADDRESS61,
fake_json_response.NETMASK1,
fake_json_response.NETMASK61,
fake_json_response.BROADCAST1,
fake_json_response.GATEWAY1,
fake_json_response.GATEWAY61,
None
)
self.assertEqual([nic0, nic1], nics)
def test_nothing_to_parse(self):
invalid = [None, "", 324242, ("dasd", "dsa")]
for data in invalid:
self.data = data
self._test_parse_nics(no_nics=True)
def test_parse(self):
self._test_parse_nics()
| apache-2.0 |
p0psicles/SickRage | lib/github/File.py | 74 | 5212 | # -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# #
# This file is part of PyGithub. http://jacquev6.github.com/PyGithub/ #
# #
# PyGithub 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. #
# #
# PyGithub 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 PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
# ##############################################################################
import github.GithubObject
class File(github.GithubObject.NonCompletableGithubObject):
"""
This class represents Files as returned for example by http://developer.github.com/v3/todo
"""
@property
def additions(self):
"""
:type: integer
"""
return self._additions.value
@property
def blob_url(self):
"""
:type: string
"""
return self._blob_url.value
@property
def changes(self):
"""
:type: integer
"""
return self._changes.value
@property
def contents_url(self):
"""
:type: string
"""
return self._contents_url.value
@property
def deletions(self):
"""
:type: integer
"""
return self._deletions.value
@property
def filename(self):
"""
:type: string
"""
return self._filename.value
@property
def patch(self):
"""
:type: string
"""
return self._patch.value
@property
def raw_url(self):
"""
:type: string
"""
return self._raw_url.value
@property
def sha(self):
"""
:type: string
"""
return self._sha.value
@property
def status(self):
"""
:type: string
"""
return self._status.value
def _initAttributes(self):
self._additions = github.GithubObject.NotSet
self._blob_url = github.GithubObject.NotSet
self._changes = github.GithubObject.NotSet
self._contents_url = github.GithubObject.NotSet
self._deletions = github.GithubObject.NotSet
self._filename = github.GithubObject.NotSet
self._patch = github.GithubObject.NotSet
self._raw_url = github.GithubObject.NotSet
self._sha = github.GithubObject.NotSet
self._status = github.GithubObject.NotSet
def _useAttributes(self, attributes):
if "additions" in attributes: # pragma no branch
self._additions = self._makeIntAttribute(attributes["additions"])
if "blob_url" in attributes: # pragma no branch
self._blob_url = self._makeStringAttribute(attributes["blob_url"])
if "changes" in attributes: # pragma no branch
self._changes = self._makeIntAttribute(attributes["changes"])
if "contents_url" in attributes: # pragma no branch
self._contents_url = self._makeStringAttribute(attributes["contents_url"])
if "deletions" in attributes: # pragma no branch
self._deletions = self._makeIntAttribute(attributes["deletions"])
if "filename" in attributes: # pragma no branch
self._filename = self._makeStringAttribute(attributes["filename"])
if "patch" in attributes: # pragma no branch
self._patch = self._makeStringAttribute(attributes["patch"])
if "raw_url" in attributes: # pragma no branch
self._raw_url = self._makeStringAttribute(attributes["raw_url"])
if "sha" in attributes: # pragma no branch
self._sha = self._makeStringAttribute(attributes["sha"])
if "status" in attributes: # pragma no branch
self._status = self._makeStringAttribute(attributes["status"])
| gpl-3.0 |
kenshay/ImageScript | ProgramData/SystemFiles/Python/Lib/site-packages/pip/_vendor/chardet/utf8prober.py | 290 | 2766 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# 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 .enums import ProbingState, MachineState
from .codingstatemachine import CodingStateMachine
from .mbcssm import UTF8_SM_MODEL
class UTF8Prober(CharSetProber):
ONE_CHAR_PROB = 0.5
def __init__(self):
super(UTF8Prober, self).__init__()
self.coding_sm = CodingStateMachine(UTF8_SM_MODEL)
self._num_mb_chars = None
self.reset()
def reset(self):
super(UTF8Prober, self).reset()
self.coding_sm.reset()
self._num_mb_chars = 0
@property
def charset_name(self):
return "utf-8"
@property
def language(self):
return ""
def feed(self, byte_str):
for c in byte_str:
coding_state = self.coding_sm.next_state(c)
if coding_state == MachineState.ERROR:
self._state = ProbingState.NOT_ME
break
elif coding_state == MachineState.ITS_ME:
self._state = ProbingState.FOUND_IT
break
elif coding_state == MachineState.START:
if self.coding_sm.get_current_charlen() >= 2:
self._num_mb_chars += 1
if self.state == ProbingState.DETECTING:
if self.get_confidence() > self.SHORTCUT_THRESHOLD:
self._state = ProbingState.FOUND_IT
return self.state
def get_confidence(self):
unlike = 0.99
if self._num_mb_chars < 6:
unlike *= self.ONE_CHAR_PROB ** self._num_mb_chars
return 1.0 - unlike
else:
return unlike
| gpl-3.0 |
naokimiyasaka/sublime-text | Packages/Package Control/package_control/commands/existing_packages_command.py | 11 | 2110 | import os
import re
import sublime
from ..package_manager import PackageManager
class ExistingPackagesCommand():
"""
Allows listing installed packages and their current version
"""
def __init__(self):
self.manager = PackageManager()
def make_package_list(self, action=''):
"""
Returns a list of installed packages suitable for displaying in the
quick panel.
:param action:
An action to display at the beginning of the third element of the
list returned for each package
:return:
A list of lists, each containing three strings:
0 - package name
1 - package description
2 - [action] installed version; package url
"""
packages = self.manager.list_packages()
if action:
action += ' '
package_list = []
for package in sorted(packages, key=lambda s: s.lower()):
package_entry = [package]
metadata = self.manager.get_metadata(package)
package_dir = os.path.join(sublime.packages_path(), package)
description = metadata.get('description')
if not description:
description = 'No description provided'
package_entry.append(description)
version = metadata.get('version')
if not version and os.path.exists(os.path.join(package_dir,
'.git')):
installed_version = 'git repository'
elif not version and os.path.exists(os.path.join(package_dir,
'.hg')):
installed_version = 'hg repository'
else:
installed_version = 'v' + version if version else \
'unknown version'
url = metadata.get('url')
if url:
url = '; ' + re.sub('^https?://', '', url)
else:
url = ''
package_entry.append(action + installed_version + url)
package_list.append(package_entry)
return package_list
| mit |
cgstudiomap/cgstudiomap | main/eggs/Django-1.9-py2.7.egg/django/contrib/gis/gdal/libgdal.py | 449 | 3598 | from __future__ import unicode_literals
import logging
import os
import re
from ctypes import CDLL, CFUNCTYPE, c_char_p, c_int
from ctypes.util import find_library
from django.contrib.gis.gdal.error import GDALException
from django.core.exceptions import ImproperlyConfigured
logger = logging.getLogger('django.contrib.gis')
# Custom library path set?
try:
from django.conf import settings
lib_path = settings.GDAL_LIBRARY_PATH
except (AttributeError, EnvironmentError,
ImportError, ImproperlyConfigured):
lib_path = None
if lib_path:
lib_names = None
elif os.name == 'nt':
# Windows NT shared libraries
lib_names = ['gdal111', 'gdal110', 'gdal19', 'gdal18', 'gdal17']
elif os.name == 'posix':
# *NIX library names.
lib_names = ['gdal', 'GDAL', 'gdal1.11.0', 'gdal1.10.0', 'gdal1.9.0',
'gdal1.8.0', 'gdal1.7.0']
else:
raise GDALException('Unsupported OS "%s"' % os.name)
# Using the ctypes `find_library` utility to find the
# path to the GDAL library from the list of library names.
if lib_names:
for lib_name in lib_names:
lib_path = find_library(lib_name)
if lib_path is not None:
break
if lib_path is None:
raise GDALException('Could not find the GDAL library (tried "%s"). '
'Try setting GDAL_LIBRARY_PATH in your settings.' %
'", "'.join(lib_names))
# This loads the GDAL/OGR C library
lgdal = CDLL(lib_path)
# On Windows, the GDAL binaries have some OSR routines exported with
# STDCALL, while others are not. Thus, the library will also need to
# be loaded up as WinDLL for said OSR functions that require the
# different calling convention.
if os.name == 'nt':
from ctypes import WinDLL
lwingdal = WinDLL(lib_path)
def std_call(func):
"""
Returns the correct STDCALL function for certain OSR routines on Win32
platforms.
"""
if os.name == 'nt':
return lwingdal[func]
else:
return lgdal[func]
# #### Version-information functions. ####
# Returns GDAL library version information with the given key.
_version_info = std_call('GDALVersionInfo')
_version_info.argtypes = [c_char_p]
_version_info.restype = c_char_p
def gdal_version():
"Returns only the GDAL version number information."
return _version_info(b'RELEASE_NAME')
def gdal_full_version():
"Returns the full GDAL version information."
return _version_info('')
version_regex = re.compile(r'^(?P<major>\d+)\.(?P<minor>\d+)(\.(?P<subminor>\d+))?')
def gdal_version_info():
ver = gdal_version().decode()
m = version_regex.match(ver)
if not m:
raise GDALException('Could not parse GDAL version string "%s"' % ver)
return {key: m.group(key) for key in ('major', 'minor', 'subminor')}
_verinfo = gdal_version_info()
GDAL_MAJOR_VERSION = int(_verinfo['major'])
GDAL_MINOR_VERSION = int(_verinfo['minor'])
GDAL_SUBMINOR_VERSION = _verinfo['subminor'] and int(_verinfo['subminor'])
GDAL_VERSION = (GDAL_MAJOR_VERSION, GDAL_MINOR_VERSION, GDAL_SUBMINOR_VERSION)
del _verinfo
# Set library error handling so as errors are logged
CPLErrorHandler = CFUNCTYPE(None, c_int, c_int, c_char_p)
def err_handler(error_class, error_number, message):
logger.error('GDAL_ERROR %d: %s' % (error_number, message))
err_handler = CPLErrorHandler(err_handler)
def function(name, args, restype):
func = std_call(name)
func.argtypes = args
func.restype = restype
return func
set_error_handler = function('CPLSetErrorHandler', [CPLErrorHandler], CPLErrorHandler)
set_error_handler(err_handler)
| agpl-3.0 |
maartenq/ansible | lib/ansible/modules/network/f5/bigip_cli_alias.py | 6 | 12104 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: bigip_cli_alias
short_description: Manage CLI aliases on a BIG-IP
description:
- Allows for managing both private and shared aliases on a BIG-IP.
version_added: 2.7
options:
name:
description:
- Specifies the name of the alias.
required: True
scope:
description:
- The scope of the alias; whether it is shared on the system, or usable only
for the user who created it.
default: shared
choices:
- private
- shared
command:
description:
- The command to alias.
description:
description:
- Description of the alias.
partition:
description:
- Device partition to manage resources on.
- This parameter is disregarded when the C(scope) is C(private).
default: Common
state:
description:
- When C(present), ensures that the resource exists.
- When C(absent), ensures the resource is removed.
default: present
choices:
- present
- absent
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
'''
EXAMPLES = r'''
- name: Create a new alias
bigip_cli_alias:
name: sync_device_to_bside
scope: shared
command: save /sys config partitions all; run /cm config-sync to-group device-group-1
provider:
password: secret
server: lb.mydomain.com
user: admin
delegate_to: localhost
'''
RETURN = r'''
command:
description: The new command that is aliased.
returned: changed
type: string
sample: run /util bash
description:
description: The new description of the alias.
returned: changed
type: string
sample: Run the bash shell
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
try:
from library.module_utils.network.f5.bigip import F5RestClient
from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import AnsibleF5Parameters
from library.module_utils.network.f5.common import cleanup_tokens
from library.module_utils.network.f5.common import f5_argument_spec
from library.module_utils.network.f5.common import exit_json
from library.module_utils.network.f5.common import fail_json
from library.module_utils.network.f5.common import transform_name
except ImportError:
from ansible.module_utils.network.f5.bigip import F5RestClient
from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import AnsibleF5Parameters
from ansible.module_utils.network.f5.common import cleanup_tokens
from ansible.module_utils.network.f5.common import f5_argument_spec
from ansible.module_utils.network.f5.common import exit_json
from ansible.module_utils.network.f5.common import fail_json
from ansible.module_utils.network.f5.common import transform_name
class Parameters(AnsibleF5Parameters):
api_map = {
'tmCommand': 'command'
}
api_attributes = [
'tmCommand',
'description',
]
returnables = [
'command',
'description',
]
updatables = [
'command',
'description',
]
@property
def full_name(self):
if self.scope == 'shared':
return transform_name(self.partition, self.name)
else:
return self.name
class ApiParameters(Parameters):
pass
class ModuleParameters(Parameters):
pass
class Changes(Parameters):
def to_return(self):
result = {}
try:
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
except Exception:
pass
return result
class UsableChanges(Changes):
pass
class ReportableChanges(Changes):
pass
class Difference(object):
def __init__(self, want, have=None):
self.want = want
self.have = have
def compare(self, param):
try:
result = getattr(self, param)
return result
except AttributeError:
return self.__default(param)
def __default(self, param):
attr1 = getattr(self.want, param)
try:
attr2 = getattr(self.have, param)
if attr1 != attr2:
return attr1
except AttributeError:
return attr1
class ModuleManager(object):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.want = ModuleParameters(params=self.module.params)
self.have = ApiParameters()
self.changes = UsableChanges()
def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = UsableChanges(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
updatables = Parameters.updatables
changed = dict()
for k in updatables:
change = diff.compare(k)
if change is None:
continue
else:
if isinstance(change, dict):
changed.update(change)
else:
changed[k] = change
if changed:
self.changes = UsableChanges(params=changed)
return True
return False
def should_update(self):
result = self._update_changed_options()
if result:
return True
return False
def exec_module(self):
changed = False
result = dict()
state = self.want.state
if state == "present":
changed = self.present()
elif state == "absent":
changed = self.absent()
reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return()
result.update(**changes)
result.update(dict(changed=changed))
self._announce_deprecations(result)
return result
def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
def present(self):
if self.exists():
return self.update()
else:
return self.create()
def exists(self):
uri = "https://{0}:{1}/mgmt/tm/cli/alias/{2}/{3}".format(
self.client.provider['server'],
self.client.provider['server_port'],
self.want.scope,
self.want.full_name
)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError:
return False
if resp.status == 404 or 'code' in response and response['code'] == 404:
return False
return True
def update(self):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.module.check_mode:
return True
self.update_on_device()
return True
def remove(self):
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the resource.")
return True
def create(self):
self._set_changed_options()
if self.module.check_mode:
return True
self.create_on_device()
return True
def create_on_device(self):
params = self.changes.api_params()
params['name'] = self.want.name
params['partition'] = self.want.partition
uri = "https://{0}:{1}/mgmt/tm/cli/alias/{2}/".format(
self.client.provider['server'],
self.client.provider['server_port'],
self.want.scope
)
resp = self.client.api.post(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] in [400, 403]:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
def update_on_device(self):
params = self.changes.api_params()
uri = "https://{0}:{1}/mgmt/tm/cli/alias/{2}/{3}".format(
self.client.provider['server'],
self.client.provider['server_port'],
self.want.scope,
self.want.full_name
)
resp = self.client.api.patch(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
def absent(self):
if self.exists():
return self.remove()
return False
def remove_from_device(self):
uri = "https://{0}:{1}/mgmt/tm/cli/alias/{2}/{3}".format(
self.client.provider['server'],
self.client.provider['server_port'],
self.want.scope,
self.want.full_name
)
resp = self.client.api.delete(uri)
if resp.status == 200:
return True
def read_current_from_device(self):
uri = "https://{0}:{1}/mgmt/tm/cli/alias/{2}/{3}".format(
self.client.provider['server'],
self.client.provider['server_port'],
self.want.scope,
self.want.full_name
)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
return ApiParameters(params=response)
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
argument_spec = dict(
name=dict(required=True),
scope=dict(
choices=['private', 'shared'],
default='shared'
),
description=dict(),
command=dict(),
state=dict(
default='present',
choices=['present', 'absent']
),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
)
try:
client = F5RestClient(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
exit_json(module, results, client)
except F5ModuleError as ex:
cleanup_tokens(client)
fail_json(module, ex, client)
if __name__ == '__main__':
main()
| gpl-3.0 |
holiman/pyethereum | ethereum/ethash_utils.py | 6 | 3288 | import sha3
from rlp.utils import decode_hex, encode_hex
import sys
WORD_BYTES = 4 # bytes in word
DATASET_BYTES_INIT = 2**30 # bytes in dataset at genesis
DATASET_BYTES_GROWTH = 2**23 # growth per epoch (~7 GB per year)
CACHE_BYTES_INIT = 2**24 # Size of the dataset relative to the cache
CACHE_BYTES_GROWTH = 2**17 # Size of the dataset relative to the cache
EPOCH_LENGTH = 30000 # blocks per epoch
MIX_BYTES = 128 # width of mix
HASH_BYTES = 64 # hash length in bytes
DATASET_PARENTS = 256 # number of parents of each dataset element
CACHE_ROUNDS = 3 # number of rounds in cache production
ACCESSES = 64 # number of accesses in hashimoto loop
FNV_PRIME = 0x01000193
def fnv(v1, v2):
return (v1 * FNV_PRIME ^ v2) % 2**32
# Assumes little endian bit ordering (same as Intel architectures)
def decode_int(s):
return int(encode_hex(s[::-1]), 16) if s else 0
def encode_int(s):
a = "%x" % s
return b'' if s == 0 else decode_hex('0' * (len(a) % 2) + a)[::-1]
def zpad(s, length):
return s + b'\x00' * max(0, length - len(s))
def serialize_hash(h):
return b''.join([zpad(encode_int(x), 4) for x in h])
def deserialize_hash(h):
return [decode_int(h[i:i+WORD_BYTES]) for i in range(0, len(h), WORD_BYTES)]
def hash_words(h, sz, x):
if isinstance(x, list):
x = serialize_hash(x)
y = h(x)
return deserialize_hash(y)
def to_bytes(x):
if sys.version_info.major > 2 and isinstance(x, str):
x = bytes(x, 'utf-8')
return x
# sha3 hash function, outputs 64 bytes
def sha3_512(x):
return hash_words(lambda v: sha3.sha3_512(to_bytes(v)).digest(), 64, x)
def sha3_256(x):
return hash_words(lambda v: sha3.sha3_256(to_bytes(v)).digest(), 32, x)
def xor(a, b):
return a ^ b
# Works for dataset and cache
def serialize_cache(ds):
return b''.join([serialize_hash(h) for h in ds])
serialize_dataset = serialize_cache
def deserialize_cache(ds):
return [deserialize_hash(ds[i:i+HASH_BYTES])
for i in range(0, len(ds), HASH_BYTES)]
deserialize_dataset = deserialize_cache
class ListWrapper(list):
def __init__(self, data):
self.data = data
self.len = len(data) / HASH_BYTES
def __len__(self):
return self.len
def __getitem__(self, i):
if i >= self.len:
raise Exception("listwrap access out of range")
return deserialize_hash(self.data[i*HASH_BYTES:(i+1)*HASH_BYTES])
def __iter__(self):
for i in range(self.len):
yield self[i]
def __repr__(self):
return repr([x for x in self])
def isprime(x):
for i in range(2, int(x**0.5)):
if not x % i:
return False
return True
def get_cache_size(block_number):
sz = CACHE_BYTES_INIT + CACHE_BYTES_GROWTH * (block_number // EPOCH_LENGTH)
sz -= HASH_BYTES
while not isprime(sz / HASH_BYTES):
sz -= 2 * HASH_BYTES
return sz
def get_full_size(block_number):
sz = DATASET_BYTES_INIT + DATASET_BYTES_GROWTH * (block_number // EPOCH_LENGTH)
sz -= MIX_BYTES
while not isprime(sz / MIX_BYTES):
sz -= 2 * MIX_BYTES
return sz
| mit |
NYU-DevOps-S17/Orders | tests/test_server.py | 1 | 6572 | # Test cases can be run with either of the following:
# python -m unittest discover
# nosetests -v --rednose --nologcapture
import unittest
import logging
import json
from app import server
# Status Codes
HTTP_200_OK = 200
HTTP_201_CREATED = 201
HTTP_204_NO_CONTENT = 204
HTTP_400_BAD_REQUEST = 400
HTTP_404_NOT_FOUND = 404
HTTP_409_CONFLICT = 409
######################################################################
# T E S T C A S E S
######################################################################
class TestOrderServer(unittest.TestCase):
def setUp(self):
server.app.debug = True
server.app.logger.addHandler(logging.StreamHandler())
server.app.logger.setLevel(logging.CRITICAL)
self.app = server.app.test_client()
server.inititalize_redis()
server.data_reset()
server.data_load({"customer_name": "Tom", "amount_paid": "200"})
server.data_load({"customer_name": "Bob", "amount_paid": "300"})
def test_index(self):
resp = self.app.get('/')
self.assertEqual( resp.status_code, HTTP_200_OK )
self.assertTrue ('Order Demo REST API Service' in resp.data)
def test_get_order_list(self):
resp = self.app.get('/orders')
self.assertEqual( resp.status_code, HTTP_200_OK )
self.assertTrue( len(resp.data) > 0 )
def test_get_order(self):
resp = self.app.get('/orders/2')
#print 'resp_data: ' + resp.data
self.assertEqual( resp.status_code, HTTP_200_OK )
data = json.loads(resp.data)
self.assertEqual (data['customer_name'], 'Bob')
def test_get_order_not_found(self):
resp = self.app.get('/orders/0')
self.assertEqual( resp.status_code, HTTP_404_NOT_FOUND )
def test_create_order(self):
# save the current number of orders for later comparrison
order_count = self.get_order_count()
# add a new order
new_order = {'customer_name': 'Kate', 'amount_paid': '400'}
data = json.dumps(new_order)
resp = self.app.post('/orders', data=data, content_type='application/json')
self.assertEqual( resp.status_code, HTTP_201_CREATED )
# Make sure location header is set
location = resp.headers.get('Location', None)
self.assertTrue( location != None)
# Check the data is correct
new_json = json.loads(resp.data)
self.assertEqual (new_json['customer_name'], 'Kate')
# check that count has gone up and includes Kate
resp = self.app.get('/orders')
# print 'resp_data(2): ' + resp.data
data = json.loads(resp.data)
self.assertEqual( resp.status_code, HTTP_200_OK )
self.assertEqual( len(data), order_count + 1 )
self.assertIn( new_json, data )
def test_update_order(self):
new_order = {'customer_name': 'Bob', 'amount_paid': '500'}
data = json.dumps(new_order)
resp = self.app.put('/orders/2', data=data, content_type='application/json')
self.assertEqual( resp.status_code, HTTP_200_OK )
resp = self.app.get('/orders/2', content_type='application/json')
self.assertEqual( resp.status_code, HTTP_200_OK )
new_json = json.loads(resp.data)
self.assertEqual (new_json['amount_paid'], '500')
def test_update_order_with_no_customer_name(self):
new_order = {'amount_paid': '200'}
data = json.dumps(new_order)
resp = self.app.put('/orders/2', data=data, content_type='application/json')
self.assertEqual( resp.status_code, HTTP_400_BAD_REQUEST )
def test_update_order_not_found(self):
new_order = {"customer_name": "ossso", "amount_paid": '3000'}
data = json.dumps(new_order)
resp = self.app.put('/orders/0', data=data, content_type='application/json')
self.assertEquals( resp.status_code, HTTP_404_NOT_FOUND )
def test_delete_order(self):
# save the current number of orders for later comparrison
order_count = self.get_order_count()
# delete a order
resp = self.app.delete('/orders/2', content_type='application/json')
self.assertEqual( resp.status_code, HTTP_204_NO_CONTENT )
self.assertEqual( len(resp.data), 0 )
new_count = self.get_order_count()
self.assertEqual( new_count, order_count - 1)
def test_create_order_with_no_customer_name(self):
new_order = {'amount_paid': '200'}
data = json.dumps(new_order)
resp = self.app.post('/orders', data=data, content_type='application/json')
self.assertEqual( resp.status_code, HTTP_400_BAD_REQUEST )
def test_create_order_with_no_content_type(self):
new_order = {'amount_paid': '200'}
data = json.dumps(new_order)
resp = self.app.post('/orders', data=data)
self.assertEqual( resp.status_code, HTTP_400_BAD_REQUEST )
def test_get_nonexisting_order(self):
resp = self.app.get('/orders/5')
self.assertEqual( resp.status_code, HTTP_404_NOT_FOUND )
def test_query_order_list(self):
resp = self.app.get('/orders', query_string='customer_name=Tom')
self.assertEqual( resp.status_code, HTTP_200_OK )
self.assertTrue( len(resp.data) > 0 )
self.assertTrue( 'Tom' in resp.data)
self.assertFalse( 'Bob' in resp.data)
data = json.loads(resp.data)
query_item = data[0]
self.assertEqual(query_item['customer_name'], 'Tom')
def test_duplicate_nonexisting_order(self):
resp = self.app.put('/orders/11111/duplicate')
self.assertEqual(resp.status_code, HTTP_400_BAD_REQUEST)
def test_duplicate_existing_order(self):
order_count_old = self.get_order_count()
resp = self.app.put('/orders/1/duplicate')
self.assertEqual(resp.status_code,HTTP_201_CREATED)
order_count_new = self.get_order_count()
self.assertEqual(order_count_new,order_count_old+1)
######################################################################
# Utility functions
######################################################################
def get_order_count(self):
# save the current number of orders
resp = self.app.get('/orders')
self.assertEqual( resp.status_code, HTTP_200_OK )
data = json.loads(resp.data)
return len(data)
######################################################################
# M A I N
######################################################################
if __name__ == '__main__':
unittest.main()
| apache-2.0 |
Endika/django | django/conf/locale/sk/formats.py | 504 | 1173 | # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j. F Y'
TIME_FORMAT = 'G:i'
DATETIME_FORMAT = 'j. F Y G:i'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j. F'
SHORT_DATE_FORMAT = 'd.m.Y'
SHORT_DATETIME_FORMAT = 'd.m.Y G:i'
FIRST_DAY_OF_WEEK = 1 # Monday
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
DATE_INPUT_FORMATS = [
'%d.%m.%Y', '%d.%m.%y', # '25.10.2006', '25.10.06'
'%y-%m-%d', # '06-10-25'
# '%d. %B %Y', '%d. %b. %Y', # '25. October 2006', '25. Oct. 2006'
]
DATETIME_INPUT_FORMATS = [
'%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59'
'%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200'
'%d.%m.%Y %H:%M', # '25.10.2006 14:30'
'%d.%m.%Y', # '25.10.2006'
]
DECIMAL_SEPARATOR = ','
THOUSAND_SEPARATOR = '\xa0' # non-breaking space
NUMBER_GROUPING = 3
| bsd-3-clause |
jorik041/stackprinter | app/lib/deliciousapi.py | 2 | 50450 | """
Unofficial Python API for retrieving data from Delicious.com.
This module provides the following features plus some more:
* retrieving a URL's full public bookmarking history including
* users who bookmarked the URL including tags used for such bookmarks
and the creation time of the bookmark (up to YYYY-MM-DD granularity)
* top tags (up to a maximum of 10) including tag count
* title as stored on Delicious.com
* total number of bookmarks/users for this URL at Delicious.com
* retrieving a user's full bookmark collection, including any private bookmarks
if you know the corresponding password
* retrieving a user's full public tagging vocabulary, i.e. tags and tag counts
* retrieving a user's network information (network members and network fans)
* HTTP proxy support
* updated to support Delicious.com "version 2" (mini-relaunch as of August 2008)
The official Delicious.com API and the JSON/RSS feeds do not provide all
the functionality mentioned above, and in such cases this module will query
the Delicious.com *website* directly and extract the required information
by parsing the HTML code of the resulting Web pages (a kind of poor man's
web mining). The module is able to detect IP throttling, which is employed
by Delicious.com to temporarily block abusive HTTP request behavior, and
will raise a custom Python error to indicate that. Please be a nice netizen
and do not stress the Delicious.com service more than necessary.
It is strongly advised that you read the Delicious.com Terms of Use
before using this Python module. In particular, read section 5
'Intellectual Property'.
The code is licensed to you under version 2 of the GNU General Public
License.
More information about this module can be found at
http://www.michael-noll.com/wiki/Del.icio.us_Python_API
Changelog is available at
http://code.michael-noll.com/?p=deliciousapi;a=log
Copyright 2006-2010 Michael G. Noll <http://www.michael-noll.com/>
"""
__author__ = "Michael G. Noll"
__copyright__ = "(c) 2006-2010 Michael G. Noll"
__description__ = "Unofficial Python API for retrieving data from Delicious.com"
__email__ = "coding[AT]michael-REMOVEME-noll[DOT]com"
__license__ = "GPLv2"
__maintainer__ = "Michael G. Noll"
__status__ = "Development"
__url__ = "http://www.michael-noll.com/"
__version__ = "1.6.3"
import base64
import cgi
import datetime
import hashlib
from operator import itemgetter
import re
import socket
import time
import urllib2
import xml.dom.minidom
try:
from BeautifulSoup import BeautifulSoup
except:
print "ERROR: could not import BeautifulSoup Python module"
print
print "You can download BeautifulSoup from the Python Cheese Shop at"
print "http://cheeseshop.python.org/pypi/BeautifulSoup/"
print "or directly from http://www.crummy.com/software/BeautifulSoup/"
print
raise
try:
from app.lib import simplejson
except:
print "ERROR: could not import simplejson module"
print
print "Since version 1.5.0, DeliciousAPI requires the simplejson module."
print "You can download simplejson from the Python Cheese Shop at"
print "http://pypi.python.org/pypi/simplejson"
print
raise
class DeliciousUser(object):
"""This class wraps all available information about a user into one object.
Variables:
bookmarks:
A list of (url, tags, title, comment, timestamp) tuples representing
a user's bookmark collection.
url is a 'unicode'
tags is a 'list' of 'unicode' ([] if no tags)
title is a 'unicode'
comment is a 'unicode' (u"" if no comment)
timestamp is a 'datetime.datetime'
tags (read-only property):
A list of (tag, tag_count) tuples, aggregated over all a user's
retrieved bookmarks. The tags represent a user's tagging vocabulary.
username:
The Delicious.com account name of the user.
"""
def __init__(self, username, bookmarks=None):
assert username
self.username = username
self.bookmarks = bookmarks or []
def __str__(self):
total_tag_count = 0
total_tags = set()
for url, tags, title, comment, timestamp in self.bookmarks:
if tags:
total_tag_count += len(tags)
for tag in tags:
total_tags.add(tag)
return "[%s] %d bookmarks, %d tags (%d unique)" % \
(self.username, len(self.bookmarks), total_tag_count, len(total_tags))
def __repr__(self):
return self.username
def get_tags(self):
"""Returns a dictionary mapping tags to their tag count.
For example, if the tag count of tag 'foo' is 23, then
23 bookmarks were annotated with 'foo'. A different way
to put it is that 23 users used the tag 'foo' when
bookmarking the URL.
"""
total_tags = {}
for url, tags, title, comment, timestamp in self.bookmarks:
for tag in tags:
total_tags[tag] = total_tags.get(tag, 0) + 1
return total_tags
tags = property(fget=get_tags, doc="Returns a dictionary mapping tags to their tag count")
class DeliciousURL(object):
"""This class wraps all available information about a web document into one object.
Variables:
bookmarks:
A list of (user, tags, comment, timestamp) tuples, representing a
document's bookmark history. Generally, this variable is populated
via get_url(), so the number of bookmarks available in this variable
depends on the parameters of get_url(). See get_url() for more
information.
user is a 'unicode'
tags is a 'list' of 'unicode's ([] if no tags)
comment is a 'unicode' (u"" if no comment)
timestamp is a 'datetime.datetime' (granularity: creation *day*,
i.e. the day but not the time of day)
tags (read-only property):
A list of (tag, tag_count) tuples, aggregated over all a document's
retrieved bookmarks.
top_tags:
A list of (tag, tag_count) tuples, representing a document's so-called
"top tags", i.e. the up to 10 most popular tags for this document.
url:
The URL of the document.
hash (read-only property):
The MD5 hash of the URL.
title:
The document's title.
total_bookmarks:
The number of total bookmarks (posts) of the document.
Note that the value of total_bookmarks can be greater than the
length of "bookmarks" depending on how much (detailed) bookmark
data could be retrieved from Delicious.com.
Here's some more background information:
The value of total_bookmarks is the "real" number of bookmarks of
URL "url" stored at Delicious.com as reported by Delicious.com
itself (so it's the "ground truth"). On the other hand, the length
of "bookmarks" depends on iteratively scraped bookmarking data.
Since scraping Delicous.com's Web pages has its limits in practice,
this means that DeliciousAPI could most likely not retrieve all
available bookmarks. In such a case, the value reported by
total_bookmarks is greater than the length of "bookmarks".
"""
def __init__(self, url, top_tags=None, bookmarks=None, title=u"", total_bookmarks=0):
assert url
self.url = url
self.top_tags = top_tags or []
self.bookmarks = bookmarks or []
self.title = title
self.total_bookmarks = total_bookmarks
def __str__(self):
total_tag_count = 0
total_tags = set()
for user, tags, comment, timestamp in self.bookmarks:
if tags:
total_tag_count += len(tags)
for tag in tags:
total_tags.add(tag)
return "[%s] %d total bookmarks (= users), %d tags (%d unique), %d out of 10 max 'top' tags" % \
(self.url, self.total_bookmarks, total_tag_count, \
len(total_tags), len(self.top_tags))
def __repr__(self):
return self.url
def get_tags(self):
"""Returns a dictionary mapping tags to their tag count.
For example, if the tag count of tag 'foo' is 23, then
23 bookmarks were annotated with 'foo'. A different way
to put it is that 23 users used the tag 'foo' when
bookmarking the URL.
@return: Dictionary mapping tags to their tag count.
"""
total_tags = {}
for user, tags, comment, timestamp in self.bookmarks:
for tag in tags:
total_tags[tag] = total_tags.get(tag, 0) + 1
return total_tags
tags = property(fget=get_tags, doc="Returns a dictionary mapping tags to their tag count")
def get_hash(self):
m = hashlib.md5()
m.update(self.url)
return m.hexdigest()
hash = property(fget=get_hash, doc="Returns the MD5 hash of the URL of this document")
class DeliciousAPI(object):
"""
This class provides a custom, unofficial API to the Delicious.com service.
Instead of using just the functionality provided by the official
Delicious.com API (which has limited features), this class retrieves
information from the Delicious.com website directly and extracts data from
the Web pages.
Note that Delicious.com will block clients with too many queries in a
certain time frame (similar to their API throttling). So be a nice citizen
and don't stress their website.
"""
def __init__(self,
http_proxy="",
tries=3,
wait_seconds=3,
user_agent="DeliciousAPI/%s (+http://www.michael-noll.com/wiki/Del.icio.us_Python_API)" % __version__,
timeout=30,
):
"""Set up the API module.
@param http_proxy: Optional, default: "".
Use an HTTP proxy for HTTP connections. Proxy support for
HTTPS is not available yet.
Format: "hostname:port" (e.g., "localhost:8080")
@type http_proxy: str
@param tries: Optional, default: 3.
Try the specified number of times when downloading a monitored
document fails. tries must be >= 1. See also wait_seconds.
@type tries: int
@param wait_seconds: Optional, default: 3.
Wait the specified number of seconds before re-trying to
download a monitored document. wait_seconds must be >= 0.
See also tries.
@type wait_seconds: int
@param user_agent: Optional, default: "DeliciousAPI/<version>
(+http://www.michael-noll.com/wiki/Del.icio.us_Python_API)".
The User-Agent HTTP Header to use when querying Delicous.com.
@type user_agent: str
@param timeout: Optional, default: 30.
Set network timeout. timeout must be >= 0.
@type timeout: int
"""
assert tries >= 1
assert wait_seconds >= 0
assert timeout >= 0
self.http_proxy = http_proxy
self.tries = tries
self.wait_seconds = wait_seconds
self.user_agent = user_agent
self.timeout = timeout
#socket.setdefaulttimeout(self.timeout)
def _query(self, path, host="delicious.com", user=None, password=None, use_ssl=False):
"""Queries Delicious.com for information, specified by (query) path.
@param path: The HTTP query path.
@type path: str
@param host: The host to query, default: "delicious.com".
@type host: str
@param user: The Delicious.com username if any, default: None.
@type user: str
@param password: The Delicious.com password of user, default: None.
@type password: unicode/str
@param use_ssl: Whether to use SSL encryption or not, default: False.
@type use_ssl: bool
@return: None on errors (i.e. on all HTTP status other than 200).
On success, returns the content of the HTML response.
"""
opener = None
handlers = []
# add HTTP Basic authentication if available
if user and password:
pwd_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
pwd_mgr.add_password(None, host, user, password)
basic_auth_handler = urllib2.HTTPBasicAuthHandler(pwd_mgr)
handlers.append(basic_auth_handler)
# add proxy support if requested
if self.http_proxy:
proxy_handler = urllib2.ProxyHandler({'http': 'http://%s' % self.http_proxy})
handlers.append(proxy_handler)
if handlers:
opener = urllib2.build_opener(*handlers)
else:
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', self.user_agent)]
data = None
tries = self.tries
if use_ssl:
protocol = "https"
else:
protocol = "http"
url = "%s://%s%s" % (protocol, host, path)
while tries > 0:
try:
f = opener.open(url)
data = f.read()
f.close()
break
except urllib2.HTTPError, e:
if e.code == 301:
raise DeliciousMovedPermanentlyWarning, "Delicious.com status %s - url moved permanently" % e.code
if e.code == 302:
raise DeliciousMovedTemporarilyWarning, "Delicious.com status %s - url moved temporarily" % e.code
elif e.code == 401:
raise DeliciousUnauthorizedError, "Delicious.com error %s - unauthorized (authentication failed?)" % e.code
elif e.code == 403:
raise DeliciousForbiddenError, "Delicious.com error %s - forbidden" % e.code
elif e.code == 404:
raise DeliciousNotFoundError, "Delicious.com error %s - url not found" % e.code
elif e.code == 500:
raise Delicious500Error, "Delicious.com error %s - server problem" % e.code
elif e.code == 503 or e.code == 999:
raise DeliciousThrottleError, "Delicious.com error %s - unable to process request (your IP address has been throttled/blocked)" % e.code
else:
raise DeliciousUnknownError, "Delicious.com error %s - unknown error" % e.code
break
except urllib2.URLError, e:
time.sleep(self.wait_seconds)
except socket.error, msg:
# sometimes we get a "Connection Refused" error
# wait a bit and then try again
time.sleep(self.wait_seconds)
#finally:
# f.close()
tries -= 1
return data
def get_url(self, url, max_bookmarks=50, sleep_seconds=1):
"""
Returns a DeliciousURL instance representing the Delicious.com history of url.
Generally, this method is what you want for getting title, bookmark, tag,
and user information about a URL.
Delicious only returns up to 50 bookmarks per URL. This means that
we have to do subsequent queries plus parsing if we want to retrieve
more than 50. Roughly speaking, the processing time of get_url()
increases linearly with the number of 50-bookmarks-chunks; i.e.
it will take 10 times longer to retrieve 500 bookmarks than 50.
@param url: The URL of the web document to be queried for.
@type url: str
@param max_bookmarks: Optional, default: 50.
See the documentation of get_bookmarks() for more information
as get_url() uses get_bookmarks() to retrieve a url's
bookmarking history.
@type max_bookmarks: int
@param sleep_seconds: Optional, default: 1.
See the documentation of get_bookmarks() for more information
as get_url() uses get_bookmarks() to retrieve a url's
bookmarking history. sleep_seconds must be >= 1 to comply with
Delicious.com's Terms of Use.
@type sleep_seconds: int
@return: DeliciousURL instance representing the Delicious.com history
of url.
"""
# we must wait at least 1 second between subsequent queries to
# comply with Delicious.com's Terms of Use
assert sleep_seconds >= 1
document = DeliciousURL(url)
m = hashlib.md5()
m.update(url)
hash = m.hexdigest()
path = "/v2/json/urlinfo/%s" % hash
data = self._query(path, host="feeds.delicious.com")
if data:
urlinfo = {}
try:
urlinfo = simplejson.loads(data)
if urlinfo:
urlinfo = urlinfo[0]
else:
urlinfo = {}
except TypeError:
pass
try:
document.title = urlinfo['title'] or u""
except KeyError:
pass
try:
top_tags = urlinfo['top_tags'] or {}
if top_tags:
document.top_tags = sorted(top_tags.iteritems(), key=itemgetter(1), reverse=True)
else:
document.top_tags = []
except KeyError:
pass
try:
document.total_bookmarks = int(urlinfo['total_posts'])
except (KeyError, ValueError):
pass
document.bookmarks = self.get_bookmarks(url=url, max_bookmarks=max_bookmarks, sleep_seconds=sleep_seconds)
return document
def get_network(self, username):
"""
Returns the user's list of followees and followers.
Followees are users in his Delicious "network", i.e. those users whose
bookmark streams he's subscribed to. Followers are his Delicious.com
"fans", i.e. those users who have subscribed to the given user's
bookmark stream).
Example:
A --------> --------> C
D --------> B --------> E
F --------> --------> F
followers followees
of B of B
Arrows from user A to user B denote that A has subscribed to B's
bookmark stream, i.e. A is "following" or "tracking" B.
Note that user F is both a followee and a follower of B, i.e. F tracks
B and vice versa. In Delicious.com terms, F is called a "mutual fan"
of B.
Comparing this network concept to information retrieval, one could say
that followers are incoming links and followees outgoing links of B.
@param username: Delicous.com username for which network information is
retrieved.
@type username: unicode/str
@return: Tuple of two lists ([<followees>, [<followers>]), where each list
contains tuples of (username, tracking_since_timestamp).
If a network is set as private, i.e. hidden from public view,
(None, None) is returned.
If a network is public but empty, ([], []) is returned.
"""
assert username
followees = followers = None
# followees (network members)
path = "/v2/json/networkmembers/%s" % username
data = None
try:
data = self._query(path, host="feeds.delicious.com")
except DeliciousForbiddenError:
pass
if data:
followees = []
users = []
try:
users = simplejson.loads(data)
except TypeError:
pass
uname = tracking_since = None
for user in users:
# followee's username
try:
uname = user['user']
except KeyError:
pass
# try to convert uname to Unicode
if uname:
try:
# we assume UTF-8 encoding
uname = uname.decode('utf-8')
except UnicodeDecodeError:
pass
# time when the given user started tracking this user
try:
tracking_since = datetime.datetime.strptime(user['dt'], "%Y-%m-%dT%H:%M:%SZ")
except KeyError:
pass
if uname:
followees.append( (uname, tracking_since) )
# followers (network fans)
path = "/v2/json/networkfans/%s" % username
data = None
try:
data = self._query(path, host="feeds.delicious.com")
except DeliciousForbiddenError:
pass
if data:
followers = []
users = []
try:
users = simplejson.loads(data)
except TypeError:
pass
uname = tracking_since = None
for user in users:
# fan's username
try:
uname = user['user']
except KeyError:
pass
# try to convert uname to Unicode
if uname:
try:
# we assume UTF-8 encoding
uname = uname.decode('utf-8')
except UnicodeDecodeError:
pass
# time when fan started tracking the given user
try:
tracking_since = datetime.datetime.strptime(user['dt'], "%Y-%m-%dT%H:%M:%SZ")
except KeyError:
pass
if uname:
followers.append( (uname, tracking_since) )
return ( followees, followers )
def get_bookmarks(self, url=None, username=None, max_bookmarks=50, sleep_seconds=1):
"""
Returns the bookmarks of url or user, respectively.
Delicious.com only returns up to 50 bookmarks per URL on its website.
This means that we have to do subsequent queries plus parsing if
we want to retrieve more than 50. Roughly speaking, the processing
time of get_bookmarks() increases linearly with the number of
50-bookmarks-chunks; i.e. it will take 10 times longer to retrieve
500 bookmarks than 50.
@param url: The URL of the web document to be queried for.
Cannot be used together with 'username'.
@type url: str
@param username: The Delicious.com username to be queried for.
Cannot be used together with 'url'.
@type username: str
@param max_bookmarks: Optional, default: 50.
Maximum number of bookmarks to retrieve. Set to 0 to disable
this limitation/the maximum and retrieve all available
bookmarks of the given url.
Bookmarks are sorted so that newer bookmarks are first.
Setting max_bookmarks to 50 means that get_bookmarks() will retrieve
the 50 most recent bookmarks of the given url.
In the case of getting bookmarks of a URL (url is set),
get_bookmarks() will take *considerably* longer to run
for pages with lots of bookmarks when setting max_bookmarks
to a high number or when you completely disable the limit.
Delicious returns only up to 50 bookmarks per result page,
so for example retrieving 250 bookmarks requires 5 HTTP
connections and parsing 5 HTML pages plus wait time between
queries (to comply with delicious' Terms of Use; see
also parameter 'sleep_seconds').
In the case of getting bookmarks of a user (username is set),
the same restrictions as for a URL apply with the exception
that we can retrieve up to 100 bookmarks per HTTP query
(instead of only up to 50 per HTTP query for a URL).
@type max_bookmarks: int
@param sleep_seconds: Optional, default: 1.
Wait the specified number of seconds between subsequent
queries in case that there are multiple pages of bookmarks
for the given url. sleep_seconds must be >= 1 to comply with
Delicious.com's Terms of Use.
See also parameter 'max_bookmarks'.
@type sleep_seconds: int
@return: Returns the bookmarks of url or user, respectively.
For urls, it returns a list of (user, tags, comment, timestamp)
tuples.
For users, it returns a list of (url, tags, title, comment,
timestamp) tuples.
Bookmarks are sorted "descendingly" by creation time, i.e. newer
bookmarks come first.
"""
# we must wait at least 1 second between subsequent queries to
# comply with delicious' Terms of Use
assert sleep_seconds >= 1
# url XOR username
assert bool(username) is not bool(url)
# maximum number of urls/posts Delicious.com will display
# per page on its website
max_html_count = 100
# maximum number of pages that Delicious.com will display;
# currently, the maximum number of pages is 20. Delicious.com
# allows to go beyond page 20 via pagination, but page N (for
# N > 20) will always display the same content as page 20.
max_html_pages = 20
path = None
if url:
m = hashlib.md5()
m.update(url)
hash = m.hexdigest()
# path will change later on if there are multiple pages of boomarks
# for the given url
path = "/url/%s" % hash
elif username:
# path will change later on if there are multiple pages of boomarks
# for the given username
path = "/%s?setcount=%d" % (username, max_html_count)
else:
raise Exception('You must specify either url or user.')
page_index = 1
bookmarks = []
while path and page_index <= max_html_pages:
data = self._query(path)
path = None
if data:
# extract bookmarks from current page
if url:
bookmarks.extend(self._extract_bookmarks_from_url_history(data))
else:
bookmarks.extend(self._extract_bookmarks_from_user_history(data))
# stop scraping if we already have as many bookmarks as we want
if (len(bookmarks) >= max_bookmarks) and max_bookmarks != 0:
break
else:
# check if there are multiple pages of bookmarks for this
# url on Delicious.com
soup = BeautifulSoup(data)
paginations = soup.findAll("div", id="pagination")
if paginations:
# find next path
nexts = paginations[0].findAll("a", attrs={ "class": "pn next" })
if nexts and (max_bookmarks == 0 or len(bookmarks) < max_bookmarks) and len(bookmarks) > 0:
# e.g. /url/2bb293d594a93e77d45c2caaf120e1b1?show=all&page=2
path = nexts[0]['href']
if username:
path += "&setcount=%d" % max_html_count
page_index += 1
# wait one second between queries to be compliant with
# delicious' Terms of Use
time.sleep(sleep_seconds)
if max_bookmarks > 0:
return bookmarks[:max_bookmarks]
else:
return bookmarks
def _extract_bookmarks_from_url_history(self, data):
"""
Extracts user bookmarks from a URL's history page on Delicious.com.
The Python library BeautifulSoup is used to parse the HTML page.
@param data: The HTML source of a URL history Web page on Delicious.com.
@type data: str
@return: list of user bookmarks of the corresponding URL
"""
bookmarks = []
soup = BeautifulSoup(data)
bookmark_elements = soup.findAll("div", attrs={"class": re.compile("^bookmark\s*")})
timestamp = None
for bookmark_element in bookmark_elements:
# extract bookmark creation time
#
# this timestamp has to "persist" until a new timestamp is
# found (delicious only provides the creation time data for the
# first bookmark in the list of bookmarks for a given day
dategroups = bookmark_element.findAll("div", attrs={"class": "dateGroup"})
if dategroups:
spans = dategroups[0].findAll('span')
if spans:
date_str = spans[0].contents[0].strip()
timestamp = datetime.datetime.strptime(date_str, '%d %b %y')
# extract comments
comment = u""
datas = bookmark_element.findAll("div", attrs={"class": "data"})
if datas:
divs = datas[0].findAll("div", attrs={"class": "description"})
if divs:
comment = divs[0].contents[0].strip()
# extract tags
user_tags = []
tagdisplays = bookmark_element.findAll("div", attrs={"class": "tagdisplay"})
if tagdisplays:
spans = tagdisplays[0].findAll("span", attrs={"class": "tagItem"})
for span in spans:
tag = span.contents[0]
user_tags.append(tag)
# extract user information
metas = bookmark_element.findAll("div", attrs={"class": "meta"})
if metas:
links = metas[0].findAll("a", attrs={"class": "user user-tag"})
if links:
user_a = links[0]
spans = user_a.findAll('span')
if spans:
try:
user = spans[0].contents[0]
except IndexError:
# WORKAROUND: it seems there is a bug on Delicious.com where
# sometimes a bookmark is shown in a URL history without any
# associated Delicious username (username is empty); this could
# be caused by special characters in the username or other things
#
# this problem of Delicious is very rare, so we just skip such
# entries until they find a fix
pass
bookmarks.append( (user, user_tags, comment, timestamp) )
return bookmarks
def _extract_bookmarks_from_user_history(self, data):
"""
Extracts a user's bookmarks from his user page on Delicious.com.
The Python library BeautifulSoup is used to parse the HTML page.
@param data: The HTML source of a user page on Delicious.com.
@type data: str
@return: list of bookmarks of the corresponding user
"""
bookmarks = []
soup = BeautifulSoup(data)
ul = soup.find("ul", id="bookmarklist")
if ul:
bookmark_elements = ul.findAll("div", attrs={"class": re.compile("^bookmark\s*")})
timestamp = None
for bookmark_element in bookmark_elements:
# extract bookmark creation time
#
# this timestamp has to "persist" until a new timestamp is
# found (delicious only provides the creation time data for the
# first bookmark in the list of bookmarks for a given day
dategroups = bookmark_element.findAll("div", attrs={"class": "dateGroup"})
if dategroups:
spans = dategroups[0].findAll('span')
if spans:
date_str = spans[0].contents[0].strip()
timestamp = datetime.datetime.strptime(date_str, '%d %b %y')
# extract url, title and comments
url = u""
title = u""
comment = u""
datas = bookmark_element.findAll("div", attrs={"class": "data"})
if datas:
links = datas[0].findAll("a", attrs={"class": re.compile("^taggedlink\s*")})
if links:
title = links[0].contents[0].strip()
url = links[0]['href']
divs = datas[0].findAll("div", attrs={"class": "description"})
if divs:
comment = divs[0].contents[0].strip()
# extract tags
url_tags = []
tagdisplays = bookmark_element.findAll("div", attrs={"class": "tagdisplay"})
if tagdisplays:
spans = tagdisplays[0].findAll("span", attrs={"class": "tagItem"})
for span in spans:
tag = span.contents[0]
url_tags.append(tag)
bookmarks.append( (url, url_tags, title, comment, timestamp) )
return bookmarks
def get_user(self, username, password=None, max_bookmarks=50, sleep_seconds=1):
"""Retrieves a user's bookmarks from Delicious.com.
If a correct username AND password are supplied, a user's *full*
bookmark collection (which also includes private bookmarks) is
retrieved. Data communication is encrypted using SSL in this case.
If no password is supplied, only the *public* bookmarks of the user
are retrieved. Here, the parameter 'max_bookmarks' specifies how
many public bookmarks will be retrieved (default: 50). Set the
parameter to 0 to retrieve all public bookmarks.
This function can be used to backup all of a user's bookmarks if
called with a username and password.
@param username: The Delicious.com username.
@type username: str
@param password: Optional, default: None.
The user's Delicious.com password. If password is set,
all communication with Delicious.com is SSL-encrypted.
@type password: unicode/str
@param max_bookmarks: Optional, default: 50.
See the documentation of get_bookmarks() for more
information as get_url() uses get_bookmarks() to
retrieve a url's bookmarking history.
The parameter is NOT used when a password is specified
because in this case the *full* bookmark collection of
a user will be retrieved.
@type max_bookmarks: int
@param sleep_seconds: Optional, default: 1.
See the documentation of get_bookmarks() for more information as
get_url() uses get_bookmarks() to retrieve a url's bookmarking
history. sleep_seconds must be >= 1 to comply with Delicious.com's
Terms of Use.
@type sleep_seconds: int
@return: DeliciousUser instance
"""
assert username
user = DeliciousUser(username)
bookmarks = []
if password:
# We have username AND password, so we call
# the official Delicious.com API.
path = "/v1/posts/all"
data = self._query(path, host="api.del.icio.us", use_ssl=True, user=username, password=password)
if data:
soup = BeautifulSoup(data)
elements = soup.findAll("post")
for element in elements:
url = element["href"]
title = element["description"] or u""
comment = element["extended"] or u""
tags = []
if element["tag"]:
tags = element["tag"].split()
timestamp = datetime.datetime.strptime(element["time"], "%Y-%m-%dT%H:%M:%SZ")
bookmarks.append( (url, tags, title, comment, timestamp) )
user.bookmarks = bookmarks
else:
# We have only the username, so we extract data from
# the user's JSON feed. However, the feed is restricted
# to the most recent public bookmarks of the user, which
# is about 100 if any. So if we need more than 100, we start
# scraping the Delicious.com website directly
if max_bookmarks > 0 and max_bookmarks <= 100:
path = "/v2/json/%s/stackoverflow?count=100" % username
data = self._query(path, host="feeds.delicious.com", user=username)
if data:
posts = []
try:
posts = simplejson.loads(data)
except TypeError:
pass
url = timestamp = None
title = comment = u""
tags = []
for post in posts:
# url
try:
url = post['u']
except KeyError:
pass
# title
try:
title = post['d']
except KeyError:
pass
# tags
try:
tags = post['t']
except KeyError:
pass
if not tags:
tags = [u"system:unfiled"]
# comment / notes
try:
comment = post['n']
except KeyError:
pass
# bookmark creation time
try:
timestamp = datetime.datetime.strptime(post['dt'], "%Y-%m-%dT%H:%M:%SZ")
except KeyError:
pass
bookmarks.append( (url, tags, title, comment, timestamp) )
user.bookmarks = bookmarks[:max_bookmarks]
else:
# TODO: retrieve the first 100 bookmarks via JSON before
# falling back to scraping the delicous.com website
user.bookmarks = self.get_bookmarks(username=username, max_bookmarks=max_bookmarks, sleep_seconds=sleep_seconds)
return user
def get_urls(self, tag=None, popular=True, max_urls=100, sleep_seconds=1):
"""
Returns the list of recent URLs (of web documents) tagged with a given tag.
This is very similar to parsing Delicious' RSS/JSON feeds directly,
but this function will return up to 2,000 links compared to a maximum
of 100 links when using the official feeds (with query parameter
count=100).
The return list of links will be sorted by recency in descending order,
i.e. newest items first.
Note that even when setting max_urls, get_urls() cannot guarantee that
it can retrieve *at least* this many URLs. It is really just an upper
bound.
@param tag: Retrieve links which have been tagged with the given tag.
If tag is not set (default), links will be retrieved from the
Delicious.com front page (aka "delicious hotlist").
@type tag: unicode/str
@param popular: If true (default), retrieve only popular links (i.e.
/popular/<tag>). Otherwise, the most recent links tagged with
the given tag will be retrieved (i.e. /tag/<tag>).
As of January 2009, it seems that Delicious.com modified the list
of popular tags to contain only up to a maximum of 15 URLs.
This also means that setting max_urls to values larger than 15
will not change the results of get_urls().
So if you are interested in more URLs, set the "popular" parameter
to false.
Note that if you set popular to False, the returned list of URLs
might contain duplicate items. This is due to the way Delicious.com
creates its /tag/<tag> Web pages. So if you need a certain
number of unique URLs, you have to take care of that in your
own code.
@type popular: bool
@param max_urls: Retrieve at most max_urls links. The default is 100,
which is the maximum number of links that can be retrieved by
parsing the official JSON feeds. The maximum value of max_urls
in practice is 2000 (currently). If it is set higher, Delicious
will return the same links over and over again, giving lots of
duplicate items.
@type max_urls: int
@param sleep_seconds: Optional, default: 1.
Wait the specified number of seconds between subsequent queries in
case that there are multiple pages of bookmarks for the given url.
Must be greater than or equal to 1 to comply with Delicious.com's
Terms of Use.
See also parameter 'max_urls'.
@type sleep_seconds: int
@return: The list of recent URLs (of web documents) tagged with a given tag.
"""
assert sleep_seconds >= 1
urls = []
path = None
if tag is None or (tag is not None and max_urls > 0 and max_urls <= 100):
# use official JSON feeds
max_json_count = 100
if tag:
# tag-specific JSON feed
if popular:
path = "/v2/json/popular/%s?count=%d" % (tag, max_json_count)
else:
path = "/v2/json/tag/%s?count=%d" % (tag, max_json_count)
else:
# Delicious.com hotlist
path = "/v2/json/?count=%d" % (max_json_count)
data = self._query(path, host="feeds.delicious.com")
if data:
posts = []
try:
posts = simplejson.loads(data)
except TypeError:
pass
for post in posts:
# url
try:
url = post['u']
if url:
urls.append(url)
except KeyError:
pass
else:
# maximum number of urls/posts Delicious.com will display
# per page on its website
max_html_count = 100
# maximum number of pages that Delicious.com will display;
# currently, the maximum number of pages is 20. Delicious.com
# allows to go beyond page 20 via pagination, but page N (for
# N > 20) will always display the same content as page 20.
max_html_pages = 20
if popular:
path = "/popular/%s?setcount=%d" % (tag, max_html_count)
else:
path = "/tag/%s?setcount=%d" % (tag, max_html_count)
page_index = 1
urls = []
while path and page_index <= max_html_pages:
data = self._query(path)
path = None
if data:
# extract urls from current page
soup = BeautifulSoup(data)
links = soup.findAll("a", attrs={"class": re.compile("^taggedlink\s*")})
for link in links:
try:
url = link['href']
if url:
urls.append(url)
except KeyError:
pass
# check if there are more multiple pages of urls
soup = BeautifulSoup(data)
paginations = soup.findAll("div", id="pagination")
if paginations:
# find next path
nexts = paginations[0].findAll("a", attrs={ "class": "pn next" })
if nexts and (max_urls == 0 or len(urls) < max_urls) and len(urls) > 0:
# e.g. /url/2bb293d594a93e77d45c2caaf120e1b1?show=all&page=2
path = nexts[0]['href']
path += "&setcount=%d" % max_html_count
page_index += 1
# wait between queries to Delicious.com to be
# compliant with its Terms of Use
time.sleep(sleep_seconds)
if max_urls > 0:
return urls[:max_urls]
else:
return urls
def get_tags_of_user(self, username):
"""
Retrieves user's public tags and their tag counts from Delicious.com.
The tags represent a user's full public tagging vocabulary.
DeliciousAPI uses the official JSON feed of the user. We could use
RSS here, but the JSON feed has proven to be faster in practice.
@param username: The Delicious.com username.
@type username: str
@return: Dictionary mapping tags to their tag counts.
"""
tags = {}
path = "/v2/json/tags/%s" % username
data = self._query(path, host="feeds.delicious.com")
if data:
try:
tags = simplejson.loads(data)
except TypeError:
pass
return tags
def get_number_of_users(self, url):
"""get_number_of_users() is obsolete and has been removed. Please use get_url() instead."""
reason = "get_number_of_users() is obsolete and has been removed. Please use get_url() instead."
raise Exception(reason)
def get_common_tags_of_url(self, url):
"""get_common_tags_of_url() is obsolete and has been removed. Please use get_url() instead."""
reason = "get_common_tags_of_url() is obsolete and has been removed. Please use get_url() instead."
raise Exception(reason)
def _html_escape(self, s):
"""HTML-escape a string or object.
This converts any non-string objects passed into it to strings
(actually, using unicode()). All values returned are
non-unicode strings (using "&#num;" entities for all non-ASCII
characters).
None is treated specially, and returns the empty string.
@param s: The string that needs to be escaped.
@type s: str
@return: The escaped string.
"""
if s is None:
return ''
if not isinstance(s, basestring):
if hasattr(s, '__unicode__'):
s = unicode(s)
else:
s = str(s)
s = cgi.escape(s, True)
if isinstance(s, unicode):
s = s.encode('ascii', 'xmlcharrefreplace')
return s
class DeliciousError(Exception):
"""Used to indicate that an error occurred when trying to access Delicious.com via its API."""
class DeliciousWarning(Exception):
"""Used to indicate a warning when trying to access Delicious.com via its API.
Warnings are raised when it is useful to alert the user of some condition
where that condition doesn't warrant raising an exception and terminating
the program. For example, we issue a warning when Delicious.com returns a
HTTP status code for redirections (3xx).
"""
class DeliciousThrottleError(DeliciousError):
"""Used to indicate that the client computer (i.e. its IP address) has been temporarily blocked by Delicious.com."""
pass
class DeliciousUnknownError(DeliciousError):
"""Used to indicate that Delicious.com returned an (HTTP) error which we don't know how to handle yet."""
pass
class DeliciousUnauthorizedError(DeliciousError):
"""Used to indicate that Delicious.com returned a 401 Unauthorized error.
Most of the time, the user credentials for accessing restricted functions
of the official Delicious.com API are incorrect.
"""
pass
class DeliciousForbiddenError(DeliciousError):
"""Used to indicate that Delicious.com returned a 403 Forbidden error.
"""
pass
class DeliciousNotFoundError(DeliciousError):
"""Used to indicate that Delicious.com returned a 404 Not Found error.
Most of the time, retrying some seconds later fixes the problem
(because we only query existing pages with this API).
"""
pass
class Delicious500Error(DeliciousError):
"""Used to indicate that Delicious.com returned a 500 error.
Most of the time, retrying some seconds later fixes the problem.
"""
pass
class DeliciousMovedPermanentlyWarning(DeliciousWarning):
"""Used to indicate that Delicious.com returned a 301 Found (Moved Permanently) redirection."""
pass
class DeliciousMovedTemporarilyWarning(DeliciousWarning):
"""Used to indicate that Delicious.com returned a 302 Found (Moved Temporarily) redirection."""
pass
__all__ = ['DeliciousAPI', 'DeliciousURL', 'DeliciousError', 'DeliciousThrottleError', 'DeliciousUnauthorizedError', 'DeliciousUnknownError', 'DeliciousNotFoundError' , 'Delicious500Error', 'DeliciousMovedTemporarilyWarning']
if __name__ == "__main__":
d = DeliciousAPI()
max_bookmarks = 50
url = 'http://www.michael-noll.com/wiki/Del.icio.us_Python_API'
print "Retrieving Delicious.com information about url"
print "'%s'" % url
print "Note: This might take some time..."
print "========================================================="
document = d.get_url(url, max_bookmarks=max_bookmarks)
print document
| bsd-3-clause |
kustodian/ansible | lib/ansible/modules/network/voss/voss_config.py | 42 | 18722 | #!/usr/bin/python
# Copyright: (c) 2018, Extreme Networks Inc.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: voss_config
version_added: "2.8"
author: "Lindsay Hill (@LindsayHill)"
short_description: Manage Extreme VOSS configuration sections
description:
- Extreme VOSS configurations use a simple flat text file syntax.
This module provides an implementation for working with EXOS
configuration lines in a deterministic way.
notes:
- Tested against VOSS 7.0.0
- Abbreviated commands are NOT idempotent, see
L(Network FAQ,../network/user_guide/faq.html#why-do-the-config-modules-always-return-changed-true-with-abbreviated-commands).
options:
lines:
description:
- The ordered set of commands that should be configured in the
section. The commands must be the exact same commands as found
in the device running-config. Be sure to note the configuration
command syntax as some commands are automatically modified by the
device config parser.
aliases: ['commands']
parents:
description:
- The parent line that uniquely identifies the section the commands
should be checked against. If this argument is omitted, the commands
are checked against the set of top level or global commands. Note
that VOSS configurations only support one level of nested commands.
src:
description:
- Specifies the source path to the file that contains the configuration
or configuration template to load. The path to the source file can
either be the full path on the Ansible control host or a relative
path from the playbook or role root directory. This argument is mutually
exclusive with I(lines), I(parents).
before:
description:
- The ordered set of commands to push on to the command stack if
a change needs to be made. This allows the playbook designer
the opportunity to perform configuration commands prior to pushing
any changes without affecting how the set of commands are matched
against the system.
after:
description:
- The ordered set of commands to append to the end of the command
stack if a change needs to be made. Just like with I(before) this
allows the playbook designer to append a set of commands to be
executed after the command set.
match:
description:
- Instructs the module on the way to perform the matching of
the set of commands against the current device config. If
match is set to I(line), commands are matched line by line. If
match is set to I(strict), command lines are matched with respect
to position. If match is set to I(exact), command lines
must be an equal match. Finally, if match is set to I(none), the
module will not attempt to compare the source configuration with
the running configuration on the remote device.
choices: ['line', 'strict', 'exact', 'none']
default: line
replace:
description:
- Instructs the module on the way to perform the configuration
on the device. If the replace argument is set to I(line) then
the modified lines are pushed to the device in configuration
mode. If the replace argument is set to I(block) then the entire
command block is pushed to the device in configuration mode if any
line is not correct.
default: line
choices: ['line', 'block']
backup:
description:
- This argument will cause the module to create a full backup of
the current C(running-config) from the remote device before any
changes are made. If the C(backup_options) value is not given,
the backup file is written to the C(backup) folder in the playbook
root directory or role root directory, if playbook is part of an
ansible role. If the directory does not exist, it is created.
type: bool
default: 'no'
running_config:
description:
- The module, by default, will connect to the remote device and
retrieve the current running-config to use as a base for comparing
against the contents of source. There are times when it is not
desirable to have the task get the current running-config for
every task in a playbook. The I(running_config) argument allows the
implementer to pass in the configuration to use as the base
config for comparison.
aliases: ['config']
defaults:
description:
- This argument specifies whether or not to collect all defaults
when getting the remote device running config. When enabled,
the module will get the current config by issuing the command
C(show running-config verbose).
type: bool
default: 'no'
save_when:
description:
- When changes are made to the device running-configuration, the
changes are not copied to non-volatile storage by default. Using
this argument will change that behavior. If the argument is set to
I(always), then the running-config will always be saved and the
I(modified) flag will always be set to True. If the argument is set
to I(modified), then the running-config will only be saved if it
has changed since the last save to startup-config. If the argument
is set to I(never), the running-config will never be saved.
If the argument is set to I(changed), then the running-config
will only be saved if the task has made a change.
default: never
choices: ['always', 'never', 'modified', 'changed']
diff_against:
description:
- When using the C(ansible-playbook --diff) command line argument
the module can generate diffs against different sources.
- When this option is configure as I(startup), the module will return
the diff of the running-config against the startup-config.
- When this option is configured as I(intended), the module will
return the diff of the running-config against the configuration
provided in the C(intended_config) argument.
- When this option is configured as I(running), the module will
return the before and after diff of the running-config with respect
to any changes made to the device configuration.
choices: ['running', 'startup', 'intended']
diff_ignore_lines:
description:
- Use this argument to specify one or more lines that should be
ignored during the diff. This is used for lines in the configuration
that are automatically updated by the system. This argument takes
a list of regular expressions or exact line matches.
intended_config:
description:
- The C(intended_config) provides the master configuration that
the node should conform to and is used to check the final
running-config against. This argument will not modify any settings
on the remote device and is strictly used to check the compliance
of the current device's configuration against. When specifying this
argument, the task should also modify the C(diff_against) value and
set it to I(intended).
backup_options:
description:
- This is a dict object containing configurable options related to backup file path.
The value of this option is read only when C(backup) is set to I(yes), if C(backup) is set
to I(no) this option will be silently ignored.
suboptions:
filename:
description:
- The filename to be used to store the backup configuration. If the the filename
is not given it will be generated based on the hostname, current time and date
in format defined by <hostname>_config.<current-date>@<current-time>
dir_path:
description:
- This option provides the path ending with directory name in which the backup
configuration file will be stored. If the directory does not exist it will be first
created and the filename is either the value of C(filename) or default filename
as described in C(filename) options description. If the path value is not given
in that case a I(backup) directory will be created in the current working directory
and backup configuration will be copied in C(filename) within I(backup) directory.
type: path
type: dict
version_added: "2.8"
"""
EXAMPLES = """
- name: configure system name
voss_config:
lines: prompt "{{ inventory_hostname }}"
- name: configure interface settings
voss_config:
lines:
- name "ServerA"
backup: yes
parents: interface GigabitEthernet 1/1
- name: check the running-config against master config
voss_config:
diff_against: intended
intended_config: "{{ lookup('file', 'master.cfg') }}"
- name: check the startup-config against the running-config
voss_config:
diff_against: startup
diff_ignore_lines:
- qos queue-profile .*
- name: save running to startup when modified
voss_config:
save_when: modified
- name: configurable backup path
voss_config:
backup: yes
backup_options:
filename: backup.cfg
dir_path: /home/user
"""
RETURN = """
updates:
description: The set of commands that will be pushed to the remote device
returned: always
type: list
sample: ['prompt "VSP200"']
commands:
description: The set of commands that will be pushed to the remote device
returned: always
type: list
sample: ['interface GigabitEthernet 1/1', 'name "ServerA"', 'exit']
backup_path:
description: The full path to the backup file
returned: when backup is yes
type: str
sample: /playbooks/ansible/backup/vsp200_config.2018-08-21@15:00:21
"""
from ansible.module_utils._text import to_text
from ansible.module_utils.connection import ConnectionError
from ansible.module_utils.network.voss.voss import run_commands, get_config
from ansible.module_utils.network.voss.voss import get_defaults_flag, get_connection
from ansible.module_utils.network.voss.voss import get_sublevel_config, VossNetworkConfig
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.common.config import dumps
def get_candidate_config(module):
candidate = VossNetworkConfig(indent=0)
if module.params['src']:
candidate.load(module.params['src'])
elif module.params['lines']:
parents = module.params['parents'] or list()
commands = module.params['lines'][0]
if (isinstance(commands, dict)) and (isinstance(commands['command'], list)):
candidate.add(commands['command'], parents=parents)
elif (isinstance(commands, dict)) and (isinstance(commands['command'], str)):
candidate.add([commands['command']], parents=parents)
else:
candidate.add(module.params['lines'], parents=parents)
return candidate
def get_running_config(module, current_config=None, flags=None):
running = module.params['running_config']
if not running:
if not module.params['defaults'] and current_config:
running = current_config
else:
running = get_config(module, flags=flags)
return running
def save_config(module, result):
result['changed'] = True
if not module.check_mode:
run_commands(module, 'save config\r')
else:
module.warn('Skipping command `save config` '
'due to check_mode. Configuration not copied to '
'non-volatile storage')
def main():
""" main entry point for module execution
"""
backup_spec = dict(
filename=dict(),
dir_path=dict(type='path')
)
argument_spec = dict(
src=dict(type='path'),
lines=dict(aliases=['commands'], type='list'),
parents=dict(type='list'),
before=dict(type='list'),
after=dict(type='list'),
match=dict(default='line', choices=['line', 'strict', 'exact', 'none']),
replace=dict(default='line', choices=['line', 'block']),
running_config=dict(aliases=['config']),
intended_config=dict(),
defaults=dict(type='bool', default=False),
backup=dict(type='bool', default=False),
backup_options=dict(type='dict', options=backup_spec),
save_when=dict(choices=['always', 'never', 'modified', 'changed'], default='never'),
diff_against=dict(choices=['startup', 'intended', 'running']),
diff_ignore_lines=dict(type='list'),
)
mutually_exclusive = [('lines', 'src'),
('parents', 'src')]
required_if = [('match', 'strict', ['lines']),
('match', 'exact', ['lines']),
('replace', 'block', ['lines']),
('diff_against', 'intended', ['intended_config'])]
module = AnsibleModule(argument_spec=argument_spec,
mutually_exclusive=mutually_exclusive,
required_if=required_if,
supports_check_mode=True)
result = {'changed': False}
parents = module.params['parents'] or list()
match = module.params['match']
replace = module.params['replace']
warnings = list()
result['warnings'] = warnings
diff_ignore_lines = module.params['diff_ignore_lines']
config = None
contents = None
flags = get_defaults_flag(module) if module.params['defaults'] else []
connection = get_connection(module)
if module.params['backup'] or (module._diff and module.params['diff_against'] == 'running'):
contents = get_config(module, flags=flags)
config = VossNetworkConfig(indent=0, contents=contents)
if module.params['backup']:
result['__backup__'] = contents
if any((module.params['lines'], module.params['src'])):
candidate = get_candidate_config(module)
if match != 'none':
config = get_running_config(module)
config = VossNetworkConfig(contents=config, indent=0)
if parents:
config = get_sublevel_config(config, module)
configobjs = candidate.difference(config, match=match, replace=replace)
else:
configobjs = candidate.items
if configobjs:
commands = dumps(configobjs, 'commands')
commands = commands.split('\n')
if module.params['before']:
commands[:0] = module.params['before']
if module.params['after']:
commands.extend(module.params['after'])
result['commands'] = commands
result['updates'] = commands
# send the configuration commands to the device and merge
# them with the current running config
if not module.check_mode:
if commands:
try:
connection.edit_config(candidate=commands)
except ConnectionError as exc:
module.fail_json(msg=to_text(commands, errors='surrogate_then_replace'))
result['changed'] = True
running_config = module.params['running_config']
startup = None
if module.params['save_when'] == 'always':
save_config(module, result)
elif module.params['save_when'] == 'modified':
match = module.params['match']
replace = module.params['replace']
try:
# Note we need to re-retrieve running config, not use cached version
running = connection.get_config(source='running')
startup = connection.get_config(source='startup')
response = connection.get_diff(candidate=startup, running=running, diff_match=match,
diff_ignore_lines=diff_ignore_lines, path=None,
diff_replace=replace)
except ConnectionError as exc:
module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))
config_diff = response['config_diff']
if config_diff:
save_config(module, result)
elif module.params['save_when'] == 'changed' and result['changed']:
save_config(module, result)
if module._diff:
if not running_config:
try:
# Note we need to re-retrieve running config, not use cached version
contents = connection.get_config(source='running')
except ConnectionError as exc:
module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))
else:
contents = running_config
# recreate the object in order to process diff_ignore_lines
running_config = VossNetworkConfig(indent=0, contents=contents,
ignore_lines=diff_ignore_lines)
if module.params['diff_against'] == 'running':
if module.check_mode:
module.warn("unable to perform diff against running-config due to check mode")
contents = None
else:
contents = config.config_text
elif module.params['diff_against'] == 'startup':
if not startup:
try:
contents = connection.get_config(source='startup')
except ConnectionError as exc:
module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))
else:
contents = startup
elif module.params['diff_against'] == 'intended':
contents = module.params['intended_config']
if contents is not None:
base_config = VossNetworkConfig(indent=0, contents=contents,
ignore_lines=diff_ignore_lines)
if running_config.sha1 != base_config.sha1:
if module.params['diff_against'] == 'intended':
before = running_config
after = base_config
elif module.params['diff_against'] in ('startup', 'running'):
before = base_config
after = running_config
result.update({
'changed': True,
'diff': {'before': str(before), 'after': str(after)}
})
module.exit_json(**result)
if __name__ == '__main__':
main()
| gpl-3.0 |
leppa/home-assistant | homeassistant/components/fibaro/cover.py | 7 | 2452 | """Support for Fibaro cover - curtains, rollershutters etc."""
import logging
from homeassistant.components.cover import (
ATTR_POSITION,
ATTR_TILT_POSITION,
ENTITY_ID_FORMAT,
CoverDevice,
)
from . import FIBARO_DEVICES, FibaroDevice
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Fibaro covers."""
if discovery_info is None:
return
add_entities(
[FibaroCover(device) for device in hass.data[FIBARO_DEVICES]["cover"]], True
)
class FibaroCover(FibaroDevice, CoverDevice):
"""Representation a Fibaro Cover."""
def __init__(self, fibaro_device):
"""Initialize the Vera device."""
super().__init__(fibaro_device)
self.entity_id = ENTITY_ID_FORMAT.format(self.ha_id)
@staticmethod
def bound(position):
"""Normalize the position."""
if position is None:
return None
position = int(position)
if position <= 5:
return 0
if position >= 95:
return 100
return position
@property
def current_cover_position(self):
"""Return current position of cover. 0 is closed, 100 is open."""
return self.bound(self.level)
@property
def current_cover_tilt_position(self):
"""Return the current tilt position for venetian blinds."""
return self.bound(self.level2)
def set_cover_position(self, **kwargs):
"""Move the cover to a specific position."""
self.set_level(kwargs.get(ATTR_POSITION))
def set_cover_tilt_position(self, **kwargs):
"""Move the cover to a specific position."""
self.set_level2(kwargs.get(ATTR_TILT_POSITION))
@property
def is_closed(self):
"""Return if the cover is closed."""
if self.current_cover_position is None:
return None
return self.current_cover_position == 0
def open_cover(self, **kwargs):
"""Open the cover."""
self.action("open")
def close_cover(self, **kwargs):
"""Close the cover."""
self.action("close")
def open_cover_tilt(self, **kwargs):
"""Open the cover tilt."""
self.set_level2(100)
def close_cover_tilt(self, **kwargs):
"""Close the cover."""
self.set_level2(0)
def stop_cover(self, **kwargs):
"""Stop the cover."""
self.action("stop")
| apache-2.0 |
orkacoin/orkacoin | share/qt/make_spinner.py | 4415 | 1035 | #!/usr/bin/env python
# W.J. van der Laan, 2011
# Make spinning .mng animation from a .png
# Requires imagemagick 6.7+
from __future__ import division
from os import path
from PIL import Image
from subprocess import Popen
SRC='img/reload_scaled.png'
DST='../../src/qt/res/movies/update_spinner.mng'
TMPDIR='/tmp'
TMPNAME='tmp-%03i.png'
NUMFRAMES=35
FRAMERATE=10.0
CONVERT='convert'
CLOCKWISE=True
DSIZE=(16,16)
im_src = Image.open(SRC)
if CLOCKWISE:
im_src = im_src.transpose(Image.FLIP_LEFT_RIGHT)
def frame_to_filename(frame):
return path.join(TMPDIR, TMPNAME % frame)
frame_files = []
for frame in xrange(NUMFRAMES):
rotation = (frame + 0.5) / NUMFRAMES * 360.0
if CLOCKWISE:
rotation = -rotation
im_new = im_src.rotate(rotation, Image.BICUBIC)
im_new.thumbnail(DSIZE, Image.ANTIALIAS)
outfile = frame_to_filename(frame)
im_new.save(outfile, 'png')
frame_files.append(outfile)
p = Popen([CONVERT, "-delay", str(FRAMERATE), "-dispose", "2"] + frame_files + [DST])
p.communicate()
| mit |
Mtax/xadmin-khb | xadmin/plugins/relate.py | 6 | 8064 | # coding=UTF-8
from django.core.urlresolvers import reverse
from django.utils.encoding import force_str
from django.utils.encoding import smart_str
from django.utils.safestring import mark_safe
from django.db.models.sql.query import LOOKUP_SEP
from django.db.models.fields.related import ForeignObjectRel
from django.utils.translation import ugettext as _
from django.db import models
from xadmin.sites import site
from xadmin.views import BaseAdminPlugin, ListAdminView, CreateAdminView, UpdateAdminView, DeleteAdminView
RELATE_PREFIX = '_rel_'
class RelateMenuPlugin(BaseAdminPlugin):
related_list = []
use_related_menu = True
def get_related_list(self):
if hasattr(self, '_related_acts'):
return self._related_acts
_related_acts = []
for r in self.opts.get_all_related_objects() + self.opts.get_all_related_many_to_many_objects():
if self.related_list and (r.get_accessor_name() not in self.related_list):
continue
if r.model not in self.admin_site._registry.keys():
continue
has_view_perm = self.has_model_perm(r.model, 'view')
has_add_perm = self.has_model_perm(r.model, 'add')
if not (has_view_perm or has_add_perm):
continue
_related_acts.append((r, has_view_perm, has_add_perm))
self._related_acts = _related_acts
return self._related_acts
def related_link(self, instance):
links = []
for r, view_perm, add_perm in self.get_related_list():
label = r.opts.app_label
model_name = r.opts.model_name
f = r.field
rel_name = f.rel.get_related_field().name
verbose_name = force_str(r.opts.verbose_name)
lookup_name = '%s__%s__exact' % (f.name, rel_name)
link = ''.join(('<li class="with_menu_btn">',
'<a href="%s?%s=%s" title="%s"><i class="icon fa fa-th-list"></i> %s</a>' %
(
reverse('%s:%s_%s_changelist' % (
self.admin_site.app_name, label, model_name)),
RELATE_PREFIX + lookup_name, str(instance.pk), verbose_name, verbose_name) if view_perm else
'<a><span class="text-muted"><i class="icon fa fa-blank"></i> %s</span></a>' % verbose_name,
'<a class="add_link dropdown-menu-btn" href="%s?%s=%s"><i class="icon fa fa-plus pull-right"></i></a>' %
(
reverse('%s:%s_%s_add' % (
self.admin_site.app_name, label, model_name)),
RELATE_PREFIX + lookup_name, str(
instance.pk)) if add_perm else "",
'</li>'))
links.append(link)
ul_html = '<ul class="dropdown-menu" role="menu">%s</ul>' % ''.join(
links)
return '<div class="dropdown related_menu pull-right"><a title="%s" class="relate_menu dropdown-toggle" data-toggle="dropdown"><i class="icon fa fa-list"></i></a>%s</div>' % (_('Related Objects'), ul_html)
related_link.short_description = ' '
related_link.allow_tags = True
related_link.allow_export = False
related_link.is_column = False
def get_list_display(self, list_display):
if self.use_related_menu and len(self.get_related_list()):
list_display.append('related_link')
self.admin_view.related_link = self.related_link
return list_display
class RelateObject(object):
def __init__(self, admin_view, lookup, value):
self.admin_view = admin_view
self.org_model = admin_view.model
self.opts = admin_view.opts
self.lookup = lookup
self.value = value
parts = lookup.split(LOOKUP_SEP)
field = self.opts.get_field_by_name(parts[0])[0]
if not hasattr(field, 'rel') and not isinstance(field, ForeignObjectRel):
raise Exception(u'Relate Lookup field must a related field')
if hasattr(field, 'rel'):
self.to_model = field.rel.to
self.rel_name = field.rel.get_related_field().name
self.is_m2m = isinstance(field.rel, models.ManyToManyRel)
else:
self.to_model = field.model
self.rel_name = self.to_model._meta.pk.name
self.is_m2m = False
to_qs = self.to_model._default_manager.get_queryset()
self.to_objs = to_qs.filter(**{self.rel_name: value}).all()
self.field = field
def filter(self, queryset):
return queryset.filter(**{self.lookup: self.value})
def get_brand_name(self):
if len(self.to_objs) == 1:
to_model_name = str(self.to_objs[0])
else:
to_model_name = force_str(self.to_model._meta.verbose_name)
return mark_safe(u"<span class='rel-brand'>%s <i class='fa fa-caret-right'></i></span> %s" % (to_model_name, force_str(self.opts.verbose_name_plural)))
class BaseRelateDisplayPlugin(BaseAdminPlugin):
def init_request(self, *args, **kwargs):
self.relate_obj = None
for k, v in self.request.REQUEST.items():
if smart_str(k).startswith(RELATE_PREFIX):
self.relate_obj = RelateObject(
self.admin_view, smart_str(k)[len(RELATE_PREFIX):], v)
break
return bool(self.relate_obj)
def _get_relate_params(self):
return RELATE_PREFIX + self.relate_obj.lookup, self.relate_obj.value
def _get_input(self):
return '<input type="hidden" name="%s" value="%s" />' % self._get_relate_params()
def _get_url(self, url):
return url + ('&' if url.find('?') > 0 else '?') + ('%s=%s' % self._get_relate_params())
class ListRelateDisplayPlugin(BaseRelateDisplayPlugin):
def get_list_queryset(self, queryset):
if self.relate_obj:
queryset = self.relate_obj.filter(queryset)
return queryset
def url_for_result(self, url, result):
return self._get_url(url)
def get_context(self, context):
context['brand_name'] = self.relate_obj.get_brand_name()
context['rel_objs'] = self.relate_obj.to_objs
if 'add_url' in context:
context['add_url'] = self._get_url(context['add_url'])
return context
def get_list_display(self, list_display):
if not self.relate_obj.is_m2m:
try:
list_display.remove(self.relate_obj.field.name)
except Exception:
pass
return list_display
class EditRelateDisplayPlugin(BaseRelateDisplayPlugin):
def get_form_datas(self, datas):
if self.admin_view.org_obj is None and self.admin_view.request_method == 'get':
datas['initial'][
self.relate_obj.field.name] = self.relate_obj.value
return datas
def post_response(self, response):
if isinstance(response, basestring) and response != self.get_admin_url('index'):
return self._get_url(response)
return response
def get_context(self, context):
if 'delete_url' in context:
context['delete_url'] = self._get_url(context['delete_url'])
return context
def block_after_fieldsets(self, context, nodes):
return self._get_input()
class DeleteRelateDisplayPlugin(BaseRelateDisplayPlugin):
def post_response(self, response):
if isinstance(response, basestring) and response != self.get_admin_url('index'):
return self._get_url(response)
return response
def block_form_fields(self, context, nodes):
return self._get_input()
site.register_plugin(RelateMenuPlugin, ListAdminView)
site.register_plugin(ListRelateDisplayPlugin, ListAdminView)
site.register_plugin(EditRelateDisplayPlugin, CreateAdminView)
site.register_plugin(EditRelateDisplayPlugin, UpdateAdminView)
site.register_plugin(DeleteRelateDisplayPlugin, DeleteAdminView)
| bsd-3-clause |
code-sauce/tensorflow | tensorflow/contrib/learn/python/learn/estimators/dynamic_rnn_estimator_test.py | 2 | 35140 | # 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.
# ==============================================================================
"""Tests for learn.estimators.dynamic_rnn_estimator."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import tempfile
# TODO: #6568 Remove this hack that makes dlopen() not crash.
if hasattr(sys, 'getdlopenflags') and hasattr(sys, 'setdlopenflags'):
import ctypes
sys.setdlopenflags(sys.getdlopenflags() | ctypes.RTLD_GLOBAL)
import numpy as np
from tensorflow.contrib import rnn
from tensorflow.contrib.layers.python.layers import feature_column
from tensorflow.contrib.layers.python.layers import target_column as target_column_lib
from tensorflow.contrib.learn.python.learn.estimators import constants
from tensorflow.contrib.learn.python.learn.estimators import dynamic_rnn_estimator
from tensorflow.contrib.learn.python.learn.estimators import model_fn as model_fn_lib
from tensorflow.contrib.learn.python.learn.estimators import prediction_key
from tensorflow.contrib.learn.python.learn.estimators import run_config
from tensorflow.contrib.rnn.python.ops import core_rnn_cell_impl
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import random_seed
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import data_flow_ops
from tensorflow.python.ops import functional_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
class IdentityRNNCell(rnn.RNNCell):
def __init__(self, state_size, output_size):
self._state_size = state_size
self._output_size = output_size
@property
def state_size(self):
return self._state_size
@property
def output_size(self):
return self._output_size
def __call__(self, inputs, state):
return array_ops.identity(inputs), array_ops.ones(
[array_ops.shape(inputs)[0], self.state_size])
class MockTargetColumn(object):
def __init__(self, num_label_columns=None):
self._num_label_columns = num_label_columns
def get_eval_ops(self, features, activations, labels, metrics):
raise NotImplementedError(
'MockTargetColumn.get_eval_ops called unexpectedly.')
def logits_to_predictions(self, flattened_activations, proba=False):
raise NotImplementedError(
'MockTargetColumn.logits_to_predictions called unexpectedly.')
def loss(self, activations, labels, features):
raise NotImplementedError('MockTargetColumn.loss called unexpectedly.')
@property
def num_label_columns(self):
if self._num_label_columns is None:
raise ValueError('MockTargetColumn.num_label_columns has not been set.')
return self._num_label_columns
def set_num_label_columns(self, n):
self._num_label_columns = n
def sequence_length_mask(values, lengths):
masked = values
for i, length in enumerate(lengths):
masked[i, length:, :] = np.zeros_like(masked[i, length:, :])
return masked
class DynamicRnnEstimatorTest(test.TestCase):
NUM_RNN_CELL_UNITS = 8
NUM_LABEL_COLUMNS = 6
INPUTS_COLUMN = feature_column.real_valued_column(
'inputs', dimension=NUM_LABEL_COLUMNS)
def setUp(self):
super(DynamicRnnEstimatorTest, self).setUp()
self.rnn_cell = core_rnn_cell_impl.BasicRNNCell(self.NUM_RNN_CELL_UNITS)
self.mock_target_column = MockTargetColumn(
num_label_columns=self.NUM_LABEL_COLUMNS)
location = feature_column.sparse_column_with_keys(
'location', keys=['west_side', 'east_side', 'nyc'])
location_onehot = feature_column.one_hot_column(location)
self.context_feature_columns = [location_onehot]
wire_cast = feature_column.sparse_column_with_keys(
'wire_cast', ['marlo', 'omar', 'stringer'])
wire_cast_embedded = feature_column.embedding_column(wire_cast, dimension=8)
measurements = feature_column.real_valued_column(
'measurements', dimension=2)
self.sequence_feature_columns = [measurements, wire_cast_embedded]
def GetColumnsToTensors(self):
"""Get columns_to_tensors matching setUp(), in the current default graph."""
return {
'location':
sparse_tensor.SparseTensor(
indices=[[0, 0], [1, 0], [2, 0]],
values=['west_side', 'west_side', 'nyc'],
dense_shape=[3, 1]),
'wire_cast':
sparse_tensor.SparseTensor(
indices=[[0, 0, 0], [0, 1, 0],
[1, 0, 0], [1, 1, 0], [1, 1, 1],
[2, 0, 0]],
values=[b'marlo', b'stringer',
b'omar', b'stringer', b'marlo',
b'marlo'],
dense_shape=[3, 2, 2]),
'measurements':
random_ops.random_uniform(
[3, 2, 2], seed=4711)
}
def GetClassificationTargetsOrNone(self, mode):
"""Get targets matching setUp() and mode, in the current default graph."""
return (random_ops.random_uniform(
[3, 2, 1], 0, 2, dtype=dtypes.int64, seed=1412) if
mode != model_fn_lib.ModeKeys.INFER else None)
def testBuildSequenceInputInput(self):
sequence_input = dynamic_rnn_estimator.build_sequence_input(
self.GetColumnsToTensors(), self.sequence_feature_columns,
self.context_feature_columns)
with self.test_session() as sess:
sess.run(variables.global_variables_initializer())
sess.run(data_flow_ops.tables_initializer())
sequence_input_val = sess.run(sequence_input)
expected_shape = np.array([
3, # expected batch size
2, # padded sequence length
3 + 8 + 2 # location keys + embedding dim + measurement dimension
])
self.assertAllEqual(expected_shape, sequence_input_val.shape)
def testConstructRNN(self):
initial_state = None
sequence_input = dynamic_rnn_estimator.build_sequence_input(
self.GetColumnsToTensors(), self.sequence_feature_columns,
self.context_feature_columns)
activations_t, final_state_t = dynamic_rnn_estimator.construct_rnn(
initial_state, sequence_input, self.rnn_cell,
self.mock_target_column.num_label_columns)
# Obtain values of activations and final state.
with session.Session() as sess:
sess.run(variables.global_variables_initializer())
sess.run(data_flow_ops.tables_initializer())
activations, final_state = sess.run([activations_t, final_state_t])
expected_activations_shape = np.array([3, 2, self.NUM_LABEL_COLUMNS])
self.assertAllEqual(expected_activations_shape, activations.shape)
expected_state_shape = np.array([3, self.NUM_RNN_CELL_UNITS])
self.assertAllEqual(expected_state_shape, final_state.shape)
def testMaskActivationsAndLabels(self):
"""Test `mask_activations_and_labels`."""
batch_size = 4
padded_length = 6
num_classes = 4
np.random.seed(1234)
sequence_length = np.random.randint(0, padded_length + 1, batch_size)
activations = np.random.rand(batch_size, padded_length, num_classes)
labels = np.random.randint(0, num_classes, [batch_size, padded_length])
(activations_masked_t,
labels_masked_t) = dynamic_rnn_estimator.mask_activations_and_labels(
constant_op.constant(
activations, dtype=dtypes.float32),
constant_op.constant(
labels, dtype=dtypes.int32),
constant_op.constant(
sequence_length, dtype=dtypes.int32))
with session.Session() as sess:
activations_masked, labels_masked = sess.run(
[activations_masked_t, labels_masked_t])
expected_activations_shape = [sum(sequence_length), num_classes]
np.testing.assert_equal(
expected_activations_shape, activations_masked.shape,
'Wrong activations shape. Expected {}; got {}.'.format(
expected_activations_shape, activations_masked.shape))
expected_labels_shape = [sum(sequence_length)]
np.testing.assert_equal(expected_labels_shape, labels_masked.shape,
'Wrong labels shape. Expected {}; got {}.'.format(
expected_labels_shape, labels_masked.shape))
masked_index = 0
for i in range(batch_size):
for j in range(sequence_length[i]):
actual_activations = activations_masked[masked_index]
expected_activations = activations[i, j, :]
np.testing.assert_almost_equal(
expected_activations,
actual_activations,
err_msg='Unexpected logit value at index [{}, {}, :].'
' Expected {}; got {}.'.format(i, j, expected_activations,
actual_activations))
actual_labels = labels_masked[masked_index]
expected_labels = labels[i, j]
np.testing.assert_almost_equal(
expected_labels,
actual_labels,
err_msg='Unexpected logit value at index [{}, {}].'
' Expected {}; got {}.'.format(i, j, expected_labels,
actual_labels))
masked_index += 1
def testSelectLastActivations(self):
"""Test `select_last_activations`."""
batch_size = 4
padded_length = 6
num_classes = 4
np.random.seed(4444)
sequence_length = np.random.randint(0, padded_length + 1, batch_size)
activations = np.random.rand(batch_size, padded_length, num_classes)
last_activations_t = dynamic_rnn_estimator.select_last_activations(
constant_op.constant(
activations, dtype=dtypes.float32),
constant_op.constant(
sequence_length, dtype=dtypes.int32))
with session.Session() as sess:
last_activations = sess.run(last_activations_t)
expected_activations_shape = [batch_size, num_classes]
np.testing.assert_equal(
expected_activations_shape, last_activations.shape,
'Wrong activations shape. Expected {}; got {}.'.format(
expected_activations_shape, last_activations.shape))
for i in range(batch_size):
actual_activations = last_activations[i, :]
expected_activations = activations[i, sequence_length[i] - 1, :]
np.testing.assert_almost_equal(
expected_activations,
actual_activations,
err_msg='Unexpected logit value at index [{}, :].'
' Expected {}; got {}.'.format(i, expected_activations,
actual_activations))
# testGetDynamicRnnModelFn{Train,Eval,Infer}() test which fields
# of ModelFnOps are set depending on mode.
def testGetDynamicRnnModelFnTrain(self):
model_fn_ops = self._GetModelFnOpsForMode(model_fn_lib.ModeKeys.TRAIN)
self.assertIsNotNone(model_fn_ops.predictions)
self.assertIsNotNone(model_fn_ops.loss)
self.assertIsNotNone(model_fn_ops.train_op)
# None may get normalized to {}; we accept neither.
self.assertNotEqual(len(model_fn_ops.eval_metric_ops), 0)
def testGetDynamicRnnModelFnEval(self):
model_fn_ops = self._GetModelFnOpsForMode(model_fn_lib.ModeKeys.EVAL)
self.assertIsNotNone(model_fn_ops.predictions)
self.assertIsNotNone(model_fn_ops.loss)
self.assertIsNone(model_fn_ops.train_op)
# None may get normalized to {}; we accept neither.
self.assertNotEqual(len(model_fn_ops.eval_metric_ops), 0)
def testGetDynamicRnnModelFnInfer(self):
model_fn_ops = self._GetModelFnOpsForMode(model_fn_lib.ModeKeys.INFER)
self.assertIsNotNone(model_fn_ops.predictions)
self.assertIsNone(model_fn_ops.loss)
self.assertIsNone(model_fn_ops.train_op)
# None may get normalized to {}; we accept both.
self.assertFalse(model_fn_ops.eval_metric_ops)
def _GetModelFnOpsForMode(self, mode):
"""Helper for testGetDynamicRnnModelFn{Train,Eval,Infer}()."""
model_fn = dynamic_rnn_estimator._get_dynamic_rnn_model_fn(
cell_type='basic_rnn',
num_units=[10],
target_column=target_column_lib.multi_class_target(n_classes=2),
# Only CLASSIFICATION yields eval metrics to test for.
problem_type=constants.ProblemType.CLASSIFICATION,
prediction_type=dynamic_rnn_estimator.PredictionType.MULTIPLE_VALUE,
optimizer='SGD',
sequence_feature_columns=self.sequence_feature_columns,
context_feature_columns=self.context_feature_columns,
learning_rate=0.1)
labels = self.GetClassificationTargetsOrNone(mode)
model_fn_ops = model_fn(
features=self.GetColumnsToTensors(), labels=labels, mode=mode)
return model_fn_ops
def testExport(self):
input_feature_key = 'magic_input_feature_key'
def get_input_fn(mode):
def input_fn():
features = self.GetColumnsToTensors()
if mode == model_fn_lib.ModeKeys.INFER:
input_examples = array_ops.placeholder(dtypes.string)
features[input_feature_key] = input_examples
# Real code would now parse features out of input_examples,
# but this test can just stick to the constants above.
return features, self.GetClassificationTargetsOrNone(mode)
return input_fn
model_dir = tempfile.mkdtemp()
def estimator_fn():
return dynamic_rnn_estimator.DynamicRnnEstimator(
problem_type=constants.ProblemType.CLASSIFICATION,
prediction_type=dynamic_rnn_estimator.PredictionType.MULTIPLE_VALUE,
num_classes=2,
num_units=self.NUM_RNN_CELL_UNITS,
sequence_feature_columns=self.sequence_feature_columns,
context_feature_columns=self.context_feature_columns,
predict_probabilities=True,
model_dir=model_dir)
# Train a bit to create an exportable checkpoint.
estimator_fn().fit(input_fn=get_input_fn(model_fn_lib.ModeKeys.TRAIN),
steps=100)
# Now export, but from a fresh estimator instance, like you would
# in an export binary. That means .export() has to work without
# .fit() being called on the same object.
export_dir = tempfile.mkdtemp()
print('Exporting to', export_dir)
estimator_fn().export(
export_dir,
input_fn=get_input_fn(model_fn_lib.ModeKeys.INFER),
use_deprecated_input_fn=False,
input_feature_key=input_feature_key)
def testStateTupleDictConversion(self):
"""Test `state_tuple_to_dict` and `dict_to_state_tuple`."""
cell_sizes = [5, 3, 7]
# A MultiRNNCell of LSTMCells is both a common choice and an interesting
# test case, because it has two levels of nesting, with an inner class that
# is not a plain tuple.
cell = core_rnn_cell_impl.MultiRNNCell(
[core_rnn_cell_impl.LSTMCell(i) for i in cell_sizes])
state_dict = {
dynamic_rnn_estimator._get_state_name(i):
array_ops.expand_dims(math_ops.range(cell_size), 0)
for i, cell_size in enumerate([5, 5, 3, 3, 7, 7])
}
expected_state = (core_rnn_cell_impl.LSTMStateTuple(
np.reshape(np.arange(5), [1, -1]), np.reshape(np.arange(5), [1, -1])),
core_rnn_cell_impl.LSTMStateTuple(
np.reshape(np.arange(3), [1, -1]),
np.reshape(np.arange(3), [1, -1])),
core_rnn_cell_impl.LSTMStateTuple(
np.reshape(np.arange(7), [1, -1]),
np.reshape(np.arange(7), [1, -1])))
actual_state = dynamic_rnn_estimator.dict_to_state_tuple(state_dict, cell)
flattened_state = dynamic_rnn_estimator.state_tuple_to_dict(actual_state)
with self.test_session() as sess:
(state_dict_val, actual_state_val, flattened_state_val) = sess.run(
[state_dict, actual_state, flattened_state])
def _recursive_assert_equal(x, y):
self.assertEqual(type(x), type(y))
if isinstance(x, (list, tuple)):
self.assertEqual(len(x), len(y))
for i, _ in enumerate(x):
_recursive_assert_equal(x[i], y[i])
elif isinstance(x, np.ndarray):
np.testing.assert_array_equal(x, y)
else:
self.fail('Unexpected type: {}'.format(type(x)))
for k in state_dict_val.keys():
np.testing.assert_array_almost_equal(
state_dict_val[k],
flattened_state_val[k],
err_msg='Wrong value for state component {}.'.format(k))
_recursive_assert_equal(expected_state, actual_state_val)
def testMultiRNNState(self):
"""Test that state flattening/reconstruction works for `MultiRNNCell`."""
batch_size = 11
sequence_length = 16
train_steps = 5
cell_sizes = [4, 8, 7]
learning_rate = 0.1
def get_shift_input_fn(batch_size, sequence_length, seed=None):
def input_fn():
random_sequence = random_ops.random_uniform(
[batch_size, sequence_length + 1],
0,
2,
dtype=dtypes.int32,
seed=seed)
labels = array_ops.slice(random_sequence, [0, 0],
[batch_size, sequence_length])
inputs = array_ops.expand_dims(
math_ops.to_float(
array_ops.slice(random_sequence, [0, 1],
[batch_size, sequence_length])), 2)
input_dict = {
dynamic_rnn_estimator._get_state_name(i): random_ops.random_uniform(
[batch_size, cell_size], seed=((i + 1) * seed))
for i, cell_size in enumerate([4, 4, 8, 8, 7, 7])
}
input_dict['inputs'] = inputs
return input_dict, labels
return input_fn
seq_columns = [feature_column.real_valued_column('inputs', dimension=1)]
config = run_config.RunConfig(tf_random_seed=21212)
cell = core_rnn_cell_impl.MultiRNNCell(
[core_rnn_cell_impl.BasicLSTMCell(size) for size in cell_sizes])
sequence_estimator = dynamic_rnn_estimator.DynamicRnnEstimator(
problem_type=constants.ProblemType.CLASSIFICATION,
prediction_type=dynamic_rnn_estimator.PredictionType.MULTIPLE_VALUE,
num_classes=2,
sequence_feature_columns=seq_columns,
cell_type=cell,
learning_rate=learning_rate,
config=config,
predict_probabilities=True)
train_input_fn = get_shift_input_fn(batch_size, sequence_length, seed=12321)
eval_input_fn = get_shift_input_fn(batch_size, sequence_length, seed=32123)
sequence_estimator.fit(input_fn=train_input_fn, steps=train_steps)
prediction_dict = sequence_estimator.predict(
input_fn=eval_input_fn, as_iterable=False)
for i, state_size in enumerate([4, 4, 8, 8, 7, 7]):
state_piece = prediction_dict[dynamic_rnn_estimator._get_state_name(i)]
self.assertListEqual(list(state_piece.shape), [batch_size, state_size])
def testLegacyConstructor(self):
"""Exercise legacy constructor function."""
num_units = 16
num_layers = 6
output_keep_prob = 0.9
input_keep_prob = 0.7
batch_size = 11
learning_rate = 0.1
train_sequence_length = 21
train_steps = 121
def get_input_fn(batch_size, sequence_length, state_dict, starting_step=0):
def input_fn():
sequence = constant_op.constant(
[[(starting_step + i + j) % 2 for j in range(sequence_length + 1)]
for i in range(batch_size)],
dtype=dtypes.int32)
labels = array_ops.slice(sequence, [0, 0],
[batch_size, sequence_length])
inputs = array_ops.expand_dims(
math_ops.to_float(
array_ops.slice(sequence, [0, 1], [batch_size, sequence_length
])), 2)
input_dict = state_dict
input_dict['inputs'] = inputs
return input_dict, labels
return input_fn
seq_columns = [feature_column.real_valued_column('inputs', dimension=1)]
config = run_config.RunConfig(tf_random_seed=21212)
model_dir = tempfile.mkdtemp()
sequence_estimator = dynamic_rnn_estimator.multi_value_rnn_classifier(
num_classes=2,
num_units=num_units,
num_rnn_layers=num_layers,
input_keep_probability=input_keep_prob,
output_keep_probability=output_keep_prob,
sequence_feature_columns=seq_columns,
learning_rate=learning_rate,
config=config,
model_dir=model_dir)
train_input_fn = get_input_fn(
batch_size, train_sequence_length, state_dict={})
sequence_estimator.fit(input_fn=train_input_fn, steps=train_steps)
def testMultipleRuns(self):
"""Tests resuming training by feeding state."""
cell_sizes = [4, 7]
batch_size = 11
learning_rate = 0.1
train_sequence_length = 21
train_steps = 121
dropout_keep_probabilities = [0.5, 0.5, 0.5]
prediction_steps = [3, 2, 5, 11, 6]
def get_input_fn(batch_size, sequence_length, state_dict, starting_step=0):
def input_fn():
sequence = constant_op.constant(
[[(starting_step + i + j) % 2 for j in range(sequence_length + 1)]
for i in range(batch_size)],
dtype=dtypes.int32)
labels = array_ops.slice(sequence, [0, 0],
[batch_size, sequence_length])
inputs = array_ops.expand_dims(
math_ops.to_float(
array_ops.slice(sequence, [0, 1], [batch_size, sequence_length
])), 2)
input_dict = state_dict
input_dict['inputs'] = inputs
return input_dict, labels
return input_fn
seq_columns = [feature_column.real_valued_column('inputs', dimension=1)]
config = run_config.RunConfig(tf_random_seed=21212)
model_dir = tempfile.mkdtemp()
sequence_estimator = dynamic_rnn_estimator.DynamicRnnEstimator(
problem_type=constants.ProblemType.CLASSIFICATION,
prediction_type=dynamic_rnn_estimator.PredictionType.MULTIPLE_VALUE,
num_classes=2,
sequence_feature_columns=seq_columns,
num_units=cell_sizes,
cell_type='lstm',
dropout_keep_probabilities=dropout_keep_probabilities,
learning_rate=learning_rate,
config=config,
model_dir=model_dir)
train_input_fn = get_input_fn(
batch_size, train_sequence_length, state_dict={})
sequence_estimator.fit(input_fn=train_input_fn, steps=train_steps)
def incremental_predict(estimator, increments):
"""Run `estimator.predict` for `i` steps for `i` in `increments`."""
step = 0
incremental_state_dict = {}
for increment in increments:
input_fn = get_input_fn(
batch_size,
increment,
state_dict=incremental_state_dict,
starting_step=step)
prediction_dict = estimator.predict(
input_fn=input_fn, as_iterable=False)
step += increment
incremental_state_dict = {
k: v
for (k, v) in prediction_dict.items()
if k.startswith(dynamic_rnn_estimator.RNNKeys.STATE_PREFIX)
}
return prediction_dict
pred_all_at_once = incremental_predict(sequence_estimator,
[sum(prediction_steps)])
pred_step_by_step = incremental_predict(sequence_estimator,
prediction_steps)
# Check that the last `prediction_steps[-1]` steps give the same
# predictions.
np.testing.assert_array_equal(
pred_all_at_once[prediction_key.PredictionKey.CLASSES]
[:, -1 * prediction_steps[-1]:],
pred_step_by_step[prediction_key.PredictionKey.CLASSES],
err_msg='Mismatch on last {} predictions.'.format(prediction_steps[-1]))
# Check that final states are identical.
for k, v in pred_all_at_once.items():
if k.startswith(dynamic_rnn_estimator.RNNKeys.STATE_PREFIX):
np.testing.assert_array_equal(
v, pred_step_by_step[k], err_msg='Mismatch on state {}.'.format(k))
# TODO(jamieas): move all tests below to a benchmark test.
class DynamicRNNEstimatorLearningTest(test.TestCase):
"""Learning tests for dynamic RNN Estimators."""
def testLearnSineFunction(self):
"""Tests learning a sine function."""
batch_size = 8
sequence_length = 64
train_steps = 200
eval_steps = 20
cell_size = [4]
learning_rate = 0.1
loss_threshold = 0.02
def get_sin_input_fn(batch_size, sequence_length, increment, seed=None):
def _sin_fn(x):
ranger = math_ops.linspace(
array_ops.reshape(x[0], []), (sequence_length - 1) * increment,
sequence_length + 1)
return math_ops.sin(ranger)
def input_fn():
starts = random_ops.random_uniform(
[batch_size], maxval=(2 * np.pi), seed=seed)
sin_curves = functional_ops.map_fn(
_sin_fn, (starts,), dtype=dtypes.float32)
inputs = array_ops.expand_dims(
array_ops.slice(sin_curves, [0, 0], [batch_size, sequence_length]),
2)
labels = array_ops.slice(sin_curves, [0, 1],
[batch_size, sequence_length])
return {'inputs': inputs}, labels
return input_fn
seq_columns = [
feature_column.real_valued_column(
'inputs', dimension=cell_size[0])
]
config = run_config.RunConfig(tf_random_seed=1234)
sequence_estimator = dynamic_rnn_estimator.DynamicRnnEstimator(
problem_type=constants.ProblemType.LINEAR_REGRESSION,
prediction_type=dynamic_rnn_estimator.PredictionType.MULTIPLE_VALUE,
num_units=cell_size,
sequence_feature_columns=seq_columns,
learning_rate=learning_rate,
dropout_keep_probabilities=[0.9, 0.9],
config=config)
train_input_fn = get_sin_input_fn(
batch_size, sequence_length, np.pi / 32, seed=1234)
eval_input_fn = get_sin_input_fn(
batch_size, sequence_length, np.pi / 32, seed=4321)
sequence_estimator.fit(input_fn=train_input_fn, steps=train_steps)
loss = sequence_estimator.evaluate(
input_fn=eval_input_fn, steps=eval_steps)['loss']
self.assertLess(loss, loss_threshold,
'Loss should be less than {}; got {}'.format(loss_threshold,
loss))
def testLearnShiftByOne(self):
"""Tests that learning a 'shift-by-one' example.
Each label sequence consists of the input sequence 'shifted' by one place.
The RNN must learn to 'remember' the previous input.
"""
batch_size = 16
sequence_length = 32
train_steps = 200
eval_steps = 20
cell_size = 4
learning_rate = 0.3
accuracy_threshold = 0.9
def get_shift_input_fn(batch_size, sequence_length, seed=None):
def input_fn():
random_sequence = random_ops.random_uniform(
[batch_size, sequence_length + 1],
0,
2,
dtype=dtypes.int32,
seed=seed)
labels = array_ops.slice(random_sequence, [0, 0],
[batch_size, sequence_length])
inputs = array_ops.expand_dims(
math_ops.to_float(
array_ops.slice(random_sequence, [0, 1],
[batch_size, sequence_length])), 2)
return {'inputs': inputs}, labels
return input_fn
seq_columns = [
feature_column.real_valued_column(
'inputs', dimension=cell_size)
]
config = run_config.RunConfig(tf_random_seed=21212)
sequence_estimator = dynamic_rnn_estimator.DynamicRnnEstimator(
problem_type=constants.ProblemType.CLASSIFICATION,
prediction_type=dynamic_rnn_estimator.PredictionType.MULTIPLE_VALUE,
num_classes=2,
num_units=cell_size,
sequence_feature_columns=seq_columns,
learning_rate=learning_rate,
config=config,
predict_probabilities=True)
train_input_fn = get_shift_input_fn(batch_size, sequence_length, seed=12321)
eval_input_fn = get_shift_input_fn(batch_size, sequence_length, seed=32123)
sequence_estimator.fit(input_fn=train_input_fn, steps=train_steps)
evaluation = sequence_estimator.evaluate(
input_fn=eval_input_fn, steps=eval_steps)
accuracy = evaluation['accuracy']
self.assertGreater(accuracy, accuracy_threshold,
'Accuracy should be higher than {}; got {}'.format(
accuracy_threshold, accuracy))
# Testing `predict` when `predict_probabilities=True`.
prediction_dict = sequence_estimator.predict(
input_fn=eval_input_fn, as_iterable=False)
self.assertListEqual(
sorted(list(prediction_dict.keys())),
sorted([
prediction_key.PredictionKey.CLASSES,
prediction_key.PredictionKey.PROBABILITIES,
dynamic_rnn_estimator._get_state_name(0)
]))
predictions = prediction_dict[prediction_key.PredictionKey.CLASSES]
probabilities = prediction_dict[
prediction_key.PredictionKey.PROBABILITIES]
self.assertListEqual(list(predictions.shape), [batch_size, sequence_length])
self.assertListEqual(
list(probabilities.shape), [batch_size, sequence_length, 2])
def testLearnMean(self):
"""Test learning to calculate a mean."""
batch_size = 16
sequence_length = 3
train_steps = 200
eval_steps = 20
cell_type = 'basic_rnn'
cell_size = 8
optimizer_type = 'Momentum'
learning_rate = 0.1
momentum = 0.9
loss_threshold = 0.1
def get_mean_input_fn(batch_size, sequence_length, seed=None):
def input_fn():
# Create examples by choosing 'centers' and adding uniform noise.
centers = math_ops.matmul(
random_ops.random_uniform(
[batch_size, 1], -0.75, 0.75, dtype=dtypes.float32, seed=seed),
array_ops.ones([1, sequence_length]))
noise = random_ops.random_uniform(
[batch_size, sequence_length],
-0.25,
0.25,
dtype=dtypes.float32,
seed=seed)
sequences = centers + noise
inputs = array_ops.expand_dims(sequences, 2)
labels = math_ops.reduce_mean(sequences, reduction_indices=[1])
return {'inputs': inputs}, labels
return input_fn
seq_columns = [
feature_column.real_valued_column(
'inputs', dimension=cell_size)
]
config = run_config.RunConfig(tf_random_seed=6)
sequence_estimator = dynamic_rnn_estimator.DynamicRnnEstimator(
problem_type=constants.ProblemType.LINEAR_REGRESSION,
prediction_type=dynamic_rnn_estimator.PredictionType.SINGLE_VALUE,
num_units=cell_size,
sequence_feature_columns=seq_columns,
cell_type=cell_type,
optimizer=optimizer_type,
learning_rate=learning_rate,
momentum=momentum,
config=config)
train_input_fn = get_mean_input_fn(batch_size, sequence_length, 121)
eval_input_fn = get_mean_input_fn(batch_size, sequence_length, 212)
sequence_estimator.fit(input_fn=train_input_fn, steps=train_steps)
evaluation = sequence_estimator.evaluate(
input_fn=eval_input_fn, steps=eval_steps)
loss = evaluation['loss']
self.assertLess(loss, loss_threshold,
'Loss should be less than {}; got {}'.format(loss_threshold,
loss))
def testLearnMajority(self):
"""Test learning the 'majority' function."""
batch_size = 16
sequence_length = 7
train_steps = 200
eval_steps = 20
cell_type = 'lstm'
cell_size = 4
optimizer_type = 'Momentum'
learning_rate = 2.0
momentum = 0.9
accuracy_threshold = 0.9
def get_majority_input_fn(batch_size, sequence_length, seed=None):
random_seed.set_random_seed(seed)
def input_fn():
random_sequence = random_ops.random_uniform(
[batch_size, sequence_length], 0, 2, dtype=dtypes.int32, seed=seed)
inputs = array_ops.expand_dims(math_ops.to_float(random_sequence), 2)
labels = math_ops.to_int32(
array_ops.squeeze(
math_ops.reduce_sum(
inputs, reduction_indices=[1]) > (sequence_length / 2.0)))
return {'inputs': inputs}, labels
return input_fn
seq_columns = [
feature_column.real_valued_column(
'inputs', dimension=cell_size)
]
config = run_config.RunConfig(tf_random_seed=77)
sequence_estimator = dynamic_rnn_estimator.DynamicRnnEstimator(
problem_type=constants.ProblemType.CLASSIFICATION,
prediction_type=dynamic_rnn_estimator.PredictionType.SINGLE_VALUE,
num_classes=2,
num_units=cell_size,
sequence_feature_columns=seq_columns,
cell_type=cell_type,
optimizer=optimizer_type,
learning_rate=learning_rate,
momentum=momentum,
config=config,
predict_probabilities=True)
train_input_fn = get_majority_input_fn(batch_size, sequence_length, 1111)
eval_input_fn = get_majority_input_fn(batch_size, sequence_length, 2222)
sequence_estimator.fit(input_fn=train_input_fn, steps=train_steps)
evaluation = sequence_estimator.evaluate(
input_fn=eval_input_fn, steps=eval_steps)
accuracy = evaluation['accuracy']
self.assertGreater(accuracy, accuracy_threshold,
'Accuracy should be higher than {}; got {}'.format(
accuracy_threshold, accuracy))
# Testing `predict` when `predict_probabilities=True`.
prediction_dict = sequence_estimator.predict(
input_fn=eval_input_fn, as_iterable=False)
self.assertListEqual(
sorted(list(prediction_dict.keys())),
sorted([
prediction_key.PredictionKey.CLASSES,
prediction_key.PredictionKey.PROBABILITIES,
dynamic_rnn_estimator._get_state_name(0),
dynamic_rnn_estimator._get_state_name(1)
]))
predictions = prediction_dict[prediction_key.PredictionKey.CLASSES]
probabilities = prediction_dict[
prediction_key.PredictionKey.PROBABILITIES]
self.assertListEqual(list(predictions.shape), [batch_size])
self.assertListEqual(list(probabilities.shape), [batch_size, 2])
if __name__ == '__main__':
test.main()
| apache-2.0 |
imbasimba/astroquery | astroquery/exoplanet_orbit_database/exoplanet_orbit_database.py | 2 | 4218 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import json
import os
from astropy.utils.data import download_file
from astropy.io import ascii
from astropy.table import QTable
import astropy.units as u
from astropy.coordinates import SkyCoord
__all__ = ['ExoplanetOrbitDatabase']
EXOPLANETS_CSV_URL = 'http://exoplanets.org/csv-files/exoplanets.csv'
TIME_ATTRS = {'TT': 'jd', 'T0': 'jd'}
BOOL_ATTRS = ('ASTROMETRY', 'BINARY', 'EOD', 'KDE', 'MICROLENSING', 'MULT',
'SE', 'TIMING', 'TRANSIT', 'TREND')
class ExoplanetOrbitDatabaseClass:
"""
Exoplanet Orbit Database querying object. Use the ``get_table`` or
``query_planet`` methods to get information about exoplanets via the
Exoplanet Orbit Database.
"""
def __init__(self):
self._param_units = None
self._table = None
@property
def param_units(self):
if self._param_units is None:
module_dir = os.path.dirname(os.path.abspath(__file__))
units_file = open(os.path.join(module_dir, 'data',
'exoplanet_orbit_database_units.json'))
self._param_units = json.load(units_file)
return self._param_units
def get_table(self, cache=True, show_progress=True, table_path=None):
"""
Download (and optionally cache) the `Exoplanet Orbit Database planets
table <http://www.exoplanets.org>`_.
Parameters
----------
cache : bool (optional)
Cache exoplanet table to local astropy cache? Default is `True`.
show_progress : bool (optional)
Show progress of exoplanet table download (if no cached copy is
available). Default is `True`.
table_path : str (optional)
Path to a local table file. Default `None` will trigger a
download of the table from the internet.
Returns
-------
table : `~astropy.table.QTable`
Table of exoplanet properties.
"""
if self._table is None:
if table_path is None:
table_path = download_file(EXOPLANETS_CSV_URL, cache=cache,
show_progress=show_progress)
exoplanets_table = ascii.read(table_path, fast_reader=False)
# Store column of lowercase names for indexing:
lowercase_names = [i.lower().replace(" ", "")
for i in exoplanets_table['NAME'].data]
exoplanets_table['NAME_LOWERCASE'] = lowercase_names
exoplanets_table.add_index('NAME_LOWERCASE')
# Create sky coordinate mixin column
exoplanets_table['sky_coord'] = SkyCoord(ra=exoplanets_table['RA'] * u.hourangle,
dec=exoplanets_table['DEC'] * u.deg)
# Assign units to columns where possible
for col in exoplanets_table.colnames:
if col in self.param_units:
# Check that unit is implemented in this version of astropy
try:
exoplanets_table[col].unit = u.Unit(self.param_units[col])
except ValueError:
print(f"WARNING: Unit {self.param_units[col]} not recognised")
self._table = QTable(exoplanets_table)
return self._table
def query_planet(self, planet_name, table_path=None):
"""
Get table of exoplanet properties.
Parameters
----------
planet_name : str
Name of planet
table_path : str (optional)
Path to a local table file. Default `None` will trigger a
download of the table from the internet.
Returns
-------
table : `~astropy.table.QTable`
Table of one exoplanet's properties.
"""
exoplanet_table = self.get_table(table_path=table_path)
return exoplanet_table.loc[planet_name.strip().lower().replace(' ', '')]
ExoplanetOrbitDatabase = ExoplanetOrbitDatabaseClass()
| bsd-3-clause |
hugobranquinho/ines | ines/__init__.py | 1 | 1198 | # -*- coding: utf-8 -*-
import datetime
import errno
from os import getpid, linesep, uname
from os.path import join as os_join
import sys
from tempfile import gettempdir
from time import time as _now_time
APPLICATIONS = {}
CAMELCASE_UPPER_WORDS = {'CSV'}
MARKER = object()
API_CONFIGURATION_EXTENSIONS = {}
DEFAULT_RENDERERS = {}
DEFAULT_METHODS = ['GET', 'PUT', 'POST', 'DELETE']
IGNORE_FULL_NAME_WORDS = ['de', 'da', 'e', 'do']
PROCESS_ID = getpid()
SYSTEM_NAME, DOMAIN_NAME, SYSTEM_RELEASE, SYSTEM_VERSION, MACHINE = uname()
DEFAULT_CACHE_DIRPATH = os_join(gettempdir(), 'ines-cache')
DEFAULT_RETRY_ERRNO = {errno.ESTALE}
DEFAULT_RETRY_ERRNO.add(116) # Stale NFS file handle
OPEN_BLOCK_SIZE = 2**18
# datetime now without microseconds
_now = datetime.datetime.now
NOW = lambda: _now().replace(microsecond=0)
# timestamp without microseconds
NOW_TIME = lambda: int(_now_time())
TODAY_DATE = datetime.date.today
HTML_NEW_LINE = '<br/>'
NEW_LINE = linesep
NEW_LINE_AS_BYTES = NEW_LINE.encode()
def lazy_import_module(name):
module = sys.modules.get(name, MARKER)
if module is not MARKER:
return module
else:
__import__(name)
return sys.modules[name]
| mit |
ikottman/alexa-skills | office_hours/dependencies/requests/packages/chardet/sjisprober.py | 1777 | 3764 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# 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 #########################
import sys
from .mbcharsetprober import MultiByteCharSetProber
from .codingstatemachine import CodingStateMachine
from .chardistribution import SJISDistributionAnalysis
from .jpcntx import SJISContextAnalysis
from .mbcssm import SJISSMModel
from . import constants
class SJISProber(MultiByteCharSetProber):
def __init__(self):
MultiByteCharSetProber.__init__(self)
self._mCodingSM = CodingStateMachine(SJISSMModel)
self._mDistributionAnalyzer = SJISDistributionAnalysis()
self._mContextAnalyzer = SJISContextAnalysis()
self.reset()
def reset(self):
MultiByteCharSetProber.reset(self)
self._mContextAnalyzer.reset()
def get_charset_name(self):
return self._mContextAnalyzer.get_charset_name()
def feed(self, aBuf):
aLen = len(aBuf)
for i in range(0, aLen):
codingState = self._mCodingSM.next_state(aBuf[i])
if codingState == constants.eError:
if constants._debug:
sys.stderr.write(self.get_charset_name()
+ ' prober hit error at byte ' + str(i)
+ '\n')
self._mState = constants.eNotMe
break
elif codingState == constants.eItsMe:
self._mState = constants.eFoundIt
break
elif codingState == constants.eStart:
charLen = self._mCodingSM.get_current_charlen()
if i == 0:
self._mLastChar[1] = aBuf[0]
self._mContextAnalyzer.feed(self._mLastChar[2 - charLen:],
charLen)
self._mDistributionAnalyzer.feed(self._mLastChar, charLen)
else:
self._mContextAnalyzer.feed(aBuf[i + 1 - charLen:i + 3
- charLen], charLen)
self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1],
charLen)
self._mLastChar[0] = aBuf[aLen - 1]
if self.get_state() == constants.eDetecting:
if (self._mContextAnalyzer.got_enough_data() and
(self.get_confidence() > constants.SHORTCUT_THRESHOLD)):
self._mState = constants.eFoundIt
return self.get_state()
def get_confidence(self):
contxtCf = self._mContextAnalyzer.get_confidence()
distribCf = self._mDistributionAnalyzer.get_confidence()
return max(contxtCf, distribCf)
| unlicense |
Dwolla/arbalest | examples/s3_json_object_to_redshift.py | 1 | 2379 | #!/usr/bin/env python
import psycopg2
from arbalest.configuration import env
from arbalest.redshift import S3CopyPipeline
from arbalest.redshift.schema import JsonObject, Property
"""
**Example: Bulk copy JSON objects from S3 bucket to Redshift table**
Arbalest orchestrates data loading using pipelines. Each `Pipeline`
can have one or many steps that are made up of three parts:
metadata: Path in an S3 bucket to store information needed for the copy process.
`s3://{BUCKET_NAME}/path_to_save_pipeline_metadata`
source: Path in an S3 bucket where data to be copied from is located.
`s3://{BUCKET_NAME}/path_of_source_data` consisting of JSON files:
```
{
"id": "66bc8153-d6d9-4351-bada-803330f22db7",
"someNumber": 1
}
```
schema: Definition of JSON objects to map into Redshift rows using a
`JsonObject` mapper which consists of one or many `Property` declarations.
By default the name of the JSON property is used as the column, but can be set
to a custom column name.
"""
if __name__ == '__main__':
pipeline = S3CopyPipeline(
aws_access_key_id=env('AWS_ACCESS_KEY_ID'),
aws_secret_access_key=env('AWS_SECRET_ACCESS_KEY'),
bucket=env('BUCKET_NAME'),
db_connection=psycopg2.connect(env('REDSHIFT_CONNECTION')))
pipeline.bulk_copy(metadata='path_to_save_pipeline_metadata',
source='path_of_source_data',
schema=JsonObject('destination_table_name',
Property('id', 'VARCHAR(36)'),
Property('someNumber', 'INTEGER',
'custom_column_name')))
pipeline.manifest_copy(metadata='path_to_save_pipeline_metadata',
source='path_of_incremental_source_data',
schema=JsonObject('incremental_destination_table_name',
Property('id', 'VARCHAR(36)'),
Property('someNumber', 'INTEGER',
'custom_column_name')))
pipeline.sql(('SELECT someNumber + %s '
'INTO some_olap_table FROM destination_table_name', 1),
('SELECT * INTO destination_table_name_copy '
'FROM destination_table_name'))
pipeline.run()
| mit |
anryko/ansible | lib/ansible/module_utils/facts/hardware/hurd.py | 232 | 1753 | # 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/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.module_utils.facts.timeout import TimeoutError
from ansible.module_utils.facts.hardware.base import HardwareCollector
from ansible.module_utils.facts.hardware.linux import LinuxHardware
class HurdHardware(LinuxHardware):
"""
GNU Hurd specific subclass of Hardware. Define memory and mount facts
based on procfs compatibility translator mimicking the interface of
the Linux kernel.
"""
platform = 'GNU'
def populate(self, collected_facts=None):
hardware_facts = {}
uptime_facts = self.get_uptime_facts()
memory_facts = self.get_memory_facts()
mount_facts = {}
try:
mount_facts = self.get_mount_facts()
except TimeoutError:
pass
hardware_facts.update(uptime_facts)
hardware_facts.update(memory_facts)
hardware_facts.update(mount_facts)
return hardware_facts
class HurdHardwareCollector(HardwareCollector):
_fact_class = HurdHardware
_platform = 'GNU'
| gpl-3.0 |
migonzalvar/rs232-obd-sim | lib/utils.py | 6 | 2017 | import random
import string
def debug(msg):
pass #print('-- ' + msg)
def sample(var):
if var == 'VSS':
self = hex (int(random.randrange(40,90)))[2:].upper()
elif var == 'RPM':
self = hex (int(random.randrange(750,4500)))[2:].upper()
else:
self = hex (int(random.randrange(0,255)))[2:].upper()
if len(self)%2 == 1:
self = '0' + self
return self
def hex_to_str(x, chars = 1):
if x == None:
return ''
else:
if bytes == 0:
mask = '%x'
else:
mask = '%0.' + str(chars) + 'x'
return (mask % x).upper()
##TODO Add unittest
##assertEqual(hex_to_str(0,1), '0')
##assertEqual(hex_to_str(0,2), '00')
##assertEqual(hex_to_str(0xFF,2), 'FF')
import binascii
def calculate_crc(hexstr):
crc_reg = 0xff
poly, i, j, checksum = 0, 0, 0, 0
msg_buf = binascii.unhexlify(hexstr)
for i in range(0, len(msg_buf)):
byte_point = ord(msg_buf[i])
bit_point = 0x80
for j in range(0,8):
if bit_point & byte_point:
if crc_reg & 0x80:
poly = 1
else:
poly = 0x1c
crc_reg = ( (crc_reg << 1) | 1) ^ poly;
else:
poly = 0
if crc_reg & 0x80:
poly = 0x1d
crc_reg= (crc_reg << 1) ^ poly
bit_point >>= 1
checksum += byte_point
checksum = checksum % 256
checksum_hexstr = hex_to_str(checksum, 2)
# For SAE ~crc_reg
return checksum_hexstr.upper()
if __name__ == '__main__':
# Test calculate_crc
test = [
{'m': '486B104100BE3EA811', 'r':'B9'},
{'m': '486B10412080001000', 'r':'B4'},
]
for t in test:
print "Testing ",t['m'],
checksum_hexstr = calculate_crc(t['m'])
assert t['r'] == checksum_hexstr
print t['r']," == ", checksum_hexstr," ...OK"
| gpl-3.0 |
hedaoyuan/Paddle | v1_api_demo/sequence_tagging/dataprovider.py | 13 | 7451 | # Copyright (c) 2016 PaddlePaddle 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 paddle.trainer.PyDataProvider2 import *
import gzip
import logging
logging.basicConfig(
format='[%(levelname)s %(asctime)s %(filename)s:%(lineno)s] %(message)s', )
logger = logging.getLogger('paddle')
logger.setLevel(logging.INFO)
OOV_POLICY_IGNORE = 0
OOV_POLICY_USE = 1
OOV_POLICY_ERROR = 2
num_original_columns = 3
# Feature combination patterns.
# [[-1,0], [0,0]] means previous token at column 0 and current token at
# column 0 are combined as one feature.
patterns = [
[[-2, 0]],
[[-1, 0]],
[[0, 0]],
[[1, 0]],
[[2, 0]],
[[-1, 0], [0, 0]],
[[0, 0], [1, 0]],
[[-2, 1]],
[[-1, 1]],
[[0, 1]],
[[1, 1]],
[[2, 1]],
[[-2, 1], [-1, 1]],
[[-1, 1], [0, 1]],
[[0, 1], [1, 1]],
[[1, 1], [2, 1]],
[[-2, 1], [-1, 1], [0, 1]],
[[-1, 1], [0, 1], [1, 1]],
[[0, 1], [1, 1], [2, 1]],
]
dict_label = {
'B-ADJP': 0,
'I-ADJP': 1,
'B-ADVP': 2,
'I-ADVP': 3,
'B-CONJP': 4,
'I-CONJP': 5,
'B-INTJ': 6,
'I-INTJ': 7,
'B-LST': 8,
'I-LST': 9,
'B-NP': 10,
'I-NP': 11,
'B-PP': 12,
'I-PP': 13,
'B-PRT': 14,
'I-PRT': 15,
'B-SBAR': 16,
'I-SBAR': 17,
'B-UCP': 18,
'I-UCP': 19,
'B-VP': 20,
'I-VP': 21,
'O': 22
}
def make_features(sequence):
length = len(sequence)
num_features = len(sequence[0])
def get_features(pos):
if pos < 0:
return ['#B%s' % -pos] * num_features
if pos >= length:
return ['#E%s' % (pos - length + 1)] * num_features
return sequence[pos]
for i in xrange(length):
for pattern in patterns:
fname = '/'.join([get_features(i + pos)[f] for pos, f in pattern])
sequence[i].append(fname)
'''
Source file format:
Each line is for one timestep. The features are separated by space.
An empty line indicates end of a sequence.
cutoff: a list of numbers. If count of a feature is smaller than this,
it will be ignored.
if oov_policy[i] is OOV_POLICY_USE, id 0 is reserved for OOV features of
i-th column.
return a list of dict for each column
'''
def create_dictionaries(filename, cutoff, oov_policy):
def add_to_dict(sequence, dicts):
num_features = len(dicts)
for features in sequence:
l = len(features)
assert l == num_features, "Wrong number of features " + line
for i in xrange(l):
if features[i] in dicts[i]:
dicts[i][features[i]] += 1
else:
dicts[i][features[i]] = 1
num_features = len(cutoff)
dicts = []
for i in xrange(num_features):
dicts.append(dict())
f = gzip.open(filename, 'rb')
sequence = []
for line in f:
line = line.strip()
if not line:
make_features(sequence)
add_to_dict(sequence, dicts)
sequence = []
continue
features = line.split(' ')
sequence.append(features)
for i in xrange(num_features):
dct = dicts[i]
n = 1 if oov_policy[i] == OOV_POLICY_USE else 0
todo = []
for k, v in dct.iteritems():
if v < cutoff[i]:
todo.append(k)
else:
dct[k] = n
n += 1
if oov_policy[i] == OOV_POLICY_USE:
# placeholder so that len(dct) will be the number of features
# including OOV
dct['#OOV#'] = 0
logger.info('column %d dict size=%d, ignored %d' % (i, n, len(todo)))
for k in todo:
del dct[k]
f.close()
return dicts
def initializer(settings, **xargs):
cutoff = [3, 1, 0]
cutoff += [3] * len(patterns)
oov_policy = [OOV_POLICY_IGNORE, OOV_POLICY_ERROR, OOV_POLICY_ERROR]
oov_policy += [OOV_POLICY_IGNORE] * len(patterns)
dicts = create_dictionaries('data/train.txt.gz', cutoff, oov_policy)
dicts[2] = dict_label
settings.dicts = dicts
settings.oov_policy = oov_policy
input_types = []
num_features = len(dicts)
for i in xrange(num_original_columns):
input_types.append(integer_sequence(len(dicts[i])))
logger.info("slot %s size=%s" % (i, len(dicts[i])))
if patterns:
dim = 0
for i in xrange(num_original_columns, num_features):
dim += len(dicts[i])
input_types.append(sparse_binary_vector_sequence(dim))
logger.info("feature size=%s" % dim)
settings.input_types = input_types
'''
if oov_policy[i] == OOV_POLICY_USE, features in i-th column which are not
existed in dicts[i] will be assigned to id 0.
if oov_policy[i] == OOV_POLICY_ERROR, all features in i-th column MUST exist
in dicts[i].
'''
@provider(init_hook=initializer, cache=CacheType.CACHE_PASS_IN_MEM)
def process(settings, filename):
input_file = filename
dicts = settings.dicts
oov_policy = settings.oov_policy
def gen_sample(sequence):
num_features = len(dicts)
sample = [list() for i in xrange(num_original_columns)]
if patterns:
sample.append([])
for features in sequence:
assert len(features) == num_features, \
"Wrong number of features: " + line
for i in xrange(num_original_columns):
id = dicts[i].get(features[i], -1)
if id != -1:
sample[i].append(id)
elif oov_policy[i] == OOV_POLICY_IGNORE:
sample[i].append(0xffffffff)
elif oov_policy[i] == OOV_POLICY_ERROR:
logger.fatal("Unknown token: %s" % features[i])
else:
sample[i].append(0)
if patterns:
dim = 0
vec = []
for i in xrange(num_original_columns, num_features):
id = dicts[i].get(features[i], -1)
if id != -1:
vec.append(dim + id)
elif oov_policy[i] == OOV_POLICY_IGNORE:
pass
elif oov_policy[i] == OOV_POLICY_ERROR:
logger.fatal("Unknown token: %s" % features[i])
else:
vec.ids.append(dim + 0)
dim += len(dicts[i])
sample[-1].append(vec)
return sample
num_features = len(dicts)
f = gzip.open(input_file, 'rb')
num_sequences = 0
sequence = []
for line in f:
line = line.strip()
if not line:
make_features(sequence)
yield gen_sample(sequence)
sequence = []
num_sequences += 1
continue
features = line.split(' ')
sequence.append(features)
f.close()
logger.info("num_sequences=%s" % num_sequences)
| apache-2.0 |
fighterCui/L4ReFiascoOC | l4/pkg/python/contrib/Lib/lib2to3/pgen2/tokenize.py | 52 | 16184 | # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation.
# All rights reserved.
"""Tokenization help for Python programs.
generate_tokens(readline) is a generator that breaks a stream of
text into Python tokens. It accepts a readline-like method which is called
repeatedly to get the next line of input (or "" for EOF). It generates
5-tuples with these members:
the token type (see token.py)
the token (a string)
the starting (row, column) indices of the token (a 2-tuple of ints)
the ending (row, column) indices of the token (a 2-tuple of ints)
the original line (string)
It is designed to match the working of the Python tokenizer exactly, except
that it produces COMMENT tokens for comments and gives type OP for all
operators
Older entry points
tokenize_loop(readline, tokeneater)
tokenize(readline, tokeneater=printtoken)
are the same, except instead of generating tokens, tokeneater is a callback
function to which the 5 fields described above are passed as 5 arguments,
each time a new token is found."""
__author__ = 'Ka-Ping Yee <ping@lfw.org>'
__credits__ = \
'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro'
import string, re
from lib2to3.pgen2.token import *
from . import token
__all__ = [x for x in dir(token) if x[0] != '_'] + ["tokenize",
"generate_tokens", "untokenize"]
del token
def group(*choices): return '(' + '|'.join(choices) + ')'
def any(*choices): return group(*choices) + '*'
def maybe(*choices): return group(*choices) + '?'
Whitespace = r'[ \f\t]*'
Comment = r'#[^\r\n]*'
Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
Name = r'[a-zA-Z_]\w*'
Binnumber = r'0[bB][01]*'
Hexnumber = r'0[xX][\da-fA-F]*[lL]?'
Octnumber = r'0[oO]?[0-7]*[lL]?'
Decnumber = r'[1-9]\d*[lL]?'
Intnumber = group(Binnumber, Hexnumber, Octnumber, Decnumber)
Exponent = r'[eE][-+]?\d+'
Pointfloat = group(r'\d+\.\d*', r'\.\d+') + maybe(Exponent)
Expfloat = r'\d+' + Exponent
Floatnumber = group(Pointfloat, Expfloat)
Imagnumber = group(r'\d+[jJ]', Floatnumber + r'[jJ]')
Number = group(Imagnumber, Floatnumber, Intnumber)
# Tail end of ' string.
Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
# Tail end of " string.
Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
# Tail end of ''' string.
Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
# Tail end of """ string.
Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
Triple = group("[ubUB]?[rR]?'''", '[ubUB]?[rR]?"""')
# Single-line ' or " string.
String = group(r"[uU]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
r'[uU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
# Because of leftmost-then-longest match semantics, be sure to put the
# longest operators first (e.g., if = came before ==, == would get
# recognized as two instances of =).
Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=",
r"//=?", r"->",
r"[+\-*/%&|^=<>]=?",
r"~")
Bracket = '[][(){}]'
Special = group(r'\r?\n', r'[:;.,`@]')
Funny = group(Operator, Bracket, Special)
PlainToken = group(Number, Funny, String, Name)
Token = Ignore + PlainToken
# First (or only) line of ' or " string.
ContStr = group(r"[uUbB]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
group("'", r'\\\r?\n'),
r'[uUbB]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
group('"', r'\\\r?\n'))
PseudoExtras = group(r'\\\r?\n', Comment, Triple)
PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
tokenprog, pseudoprog, single3prog, double3prog = map(
re.compile, (Token, PseudoToken, Single3, Double3))
endprogs = {"'": re.compile(Single), '"': re.compile(Double),
"'''": single3prog, '"""': double3prog,
"r'''": single3prog, 'r"""': double3prog,
"u'''": single3prog, 'u"""': double3prog,
"b'''": single3prog, 'b"""': double3prog,
"ur'''": single3prog, 'ur"""': double3prog,
"br'''": single3prog, 'br"""': double3prog,
"R'''": single3prog, 'R"""': double3prog,
"U'''": single3prog, 'U"""': double3prog,
"B'''": single3prog, 'B"""': double3prog,
"uR'''": single3prog, 'uR"""': double3prog,
"Ur'''": single3prog, 'Ur"""': double3prog,
"UR'''": single3prog, 'UR"""': double3prog,
"bR'''": single3prog, 'bR"""': double3prog,
"Br'''": single3prog, 'Br"""': double3prog,
"BR'''": single3prog, 'BR"""': double3prog,
'r': None, 'R': None,
'u': None, 'U': None,
'b': None, 'B': None}
triple_quoted = {}
for t in ("'''", '"""',
"r'''", 'r"""', "R'''", 'R"""',
"u'''", 'u"""', "U'''", 'U"""',
"b'''", 'b"""', "B'''", 'B"""',
"ur'''", 'ur"""', "Ur'''", 'Ur"""',
"uR'''", 'uR"""', "UR'''", 'UR"""',
"br'''", 'br"""', "Br'''", 'Br"""',
"bR'''", 'bR"""', "BR'''", 'BR"""',):
triple_quoted[t] = t
single_quoted = {}
for t in ("'", '"',
"r'", 'r"', "R'", 'R"',
"u'", 'u"', "U'", 'U"',
"b'", 'b"', "B'", 'B"',
"ur'", 'ur"', "Ur'", 'Ur"',
"uR'", 'uR"', "UR'", 'UR"',
"br'", 'br"', "Br'", 'Br"',
"bR'", 'bR"', "BR'", 'BR"', ):
single_quoted[t] = t
tabsize = 8
class TokenError(Exception): pass
class StopTokenizing(Exception): pass
def printtoken(type, token, (srow, scol), (erow, ecol), line): # for testing
print "%d,%d-%d,%d:\t%s\t%s" % \
(srow, scol, erow, ecol, tok_name[type], repr(token))
def tokenize(readline, tokeneater=printtoken):
"""
The tokenize() function accepts two parameters: one representing the
input stream, and one providing an output mechanism for tokenize().
The first parameter, readline, must be a callable object which provides
the same interface as the readline() method of built-in file objects.
Each call to the function should return one line of input as a string.
The second parameter, tokeneater, must also be a callable object. It is
called once for each token, with five arguments, corresponding to the
tuples generated by generate_tokens().
"""
try:
tokenize_loop(readline, tokeneater)
except StopTokenizing:
pass
# backwards compatible interface
def tokenize_loop(readline, tokeneater):
for token_info in generate_tokens(readline):
tokeneater(*token_info)
class Untokenizer:
def __init__(self):
self.tokens = []
self.prev_row = 1
self.prev_col = 0
def add_whitespace(self, start):
row, col = start
assert row <= self.prev_row
col_offset = col - self.prev_col
if col_offset:
self.tokens.append(" " * col_offset)
def untokenize(self, iterable):
for t in iterable:
if len(t) == 2:
self.compat(t, iterable)
break
tok_type, token, start, end, line = t
self.add_whitespace(start)
self.tokens.append(token)
self.prev_row, self.prev_col = end
if tok_type in (NEWLINE, NL):
self.prev_row += 1
self.prev_col = 0
return "".join(self.tokens)
def compat(self, token, iterable):
startline = False
indents = []
toks_append = self.tokens.append
toknum, tokval = token
if toknum in (NAME, NUMBER):
tokval += ' '
if toknum in (NEWLINE, NL):
startline = True
for tok in iterable:
toknum, tokval = tok[:2]
if toknum in (NAME, NUMBER):
tokval += ' '
if toknum == INDENT:
indents.append(tokval)
continue
elif toknum == DEDENT:
indents.pop()
continue
elif toknum in (NEWLINE, NL):
startline = True
elif startline and indents:
toks_append(indents[-1])
startline = False
toks_append(tokval)
def untokenize(iterable):
"""Transform tokens back into Python source code.
Each element returned by the iterable must be a token sequence
with at least two elements, a token number and token value. If
only two tokens are passed, the resulting output is poor.
Round-trip invariant for full input:
Untokenized source will match input source exactly
Round-trip invariant for limited intput:
# Output text will tokenize the back to the input
t1 = [tok[:2] for tok in generate_tokens(f.readline)]
newcode = untokenize(t1)
readline = iter(newcode.splitlines(1)).next
t2 = [tok[:2] for tokin generate_tokens(readline)]
assert t1 == t2
"""
ut = Untokenizer()
return ut.untokenize(iterable)
def generate_tokens(readline):
"""
The generate_tokens() generator requires one argment, readline, which
must be a callable object which provides the same interface as the
readline() method of built-in file objects. Each call to the function
should return one line of input as a string. Alternately, readline
can be a callable function terminating with StopIteration:
readline = open(myfile).next # Example of alternate readline
The generator produces 5-tuples with these members: the token type; the
token string; a 2-tuple (srow, scol) of ints specifying the row and
column where the token begins in the source; a 2-tuple (erow, ecol) of
ints specifying the row and column where the token ends in the source;
and the line on which the token was found. The line passed is the
logical line; continuation lines are included.
"""
lnum = parenlev = continued = 0
namechars, numchars = string.ascii_letters + '_', '0123456789'
contstr, needcont = '', 0
contline = None
indents = [0]
while 1: # loop over lines in stream
try:
line = readline()
except StopIteration:
line = ''
lnum = lnum + 1
pos, max = 0, len(line)
if contstr: # continued string
if not line:
raise TokenError, ("EOF in multi-line string", strstart)
endmatch = endprog.match(line)
if endmatch:
pos = end = endmatch.end(0)
yield (STRING, contstr + line[:end],
strstart, (lnum, end), contline + line)
contstr, needcont = '', 0
contline = None
elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
yield (ERRORTOKEN, contstr + line,
strstart, (lnum, len(line)), contline)
contstr = ''
contline = None
continue
else:
contstr = contstr + line
contline = contline + line
continue
elif parenlev == 0 and not continued: # new statement
if not line: break
column = 0
while pos < max: # measure leading whitespace
if line[pos] == ' ': column = column + 1
elif line[pos] == '\t': column = (column/tabsize + 1)*tabsize
elif line[pos] == '\f': column = 0
else: break
pos = pos + 1
if pos == max: break
if line[pos] in '#\r\n': # skip comments or blank lines
if line[pos] == '#':
comment_token = line[pos:].rstrip('\r\n')
nl_pos = pos + len(comment_token)
yield (COMMENT, comment_token,
(lnum, pos), (lnum, pos + len(comment_token)), line)
yield (NL, line[nl_pos:],
(lnum, nl_pos), (lnum, len(line)), line)
else:
yield ((NL, COMMENT)[line[pos] == '#'], line[pos:],
(lnum, pos), (lnum, len(line)), line)
continue
if column > indents[-1]: # count indents or dedents
indents.append(column)
yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
while column < indents[-1]:
if column not in indents:
raise IndentationError(
"unindent does not match any outer indentation level",
("<tokenize>", lnum, pos, line))
indents = indents[:-1]
yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
else: # continued statement
if not line:
raise TokenError, ("EOF in multi-line statement", (lnum, 0))
continued = 0
while pos < max:
pseudomatch = pseudoprog.match(line, pos)
if pseudomatch: # scan for tokens
start, end = pseudomatch.span(1)
spos, epos, pos = (lnum, start), (lnum, end), end
token, initial = line[start:end], line[start]
if initial in numchars or \
(initial == '.' and token != '.'): # ordinary number
yield (NUMBER, token, spos, epos, line)
elif initial in '\r\n':
newline = NEWLINE
if parenlev > 0:
newline = NL
yield (newline, token, spos, epos, line)
elif initial == '#':
assert not token.endswith("\n")
yield (COMMENT, token, spos, epos, line)
elif token in triple_quoted:
endprog = endprogs[token]
endmatch = endprog.match(line, pos)
if endmatch: # all on one line
pos = endmatch.end(0)
token = line[start:pos]
yield (STRING, token, spos, (lnum, pos), line)
else:
strstart = (lnum, start) # multiple lines
contstr = line[start:]
contline = line
break
elif initial in single_quoted or \
token[:2] in single_quoted or \
token[:3] in single_quoted:
if token[-1] == '\n': # continued string
strstart = (lnum, start)
endprog = (endprogs[initial] or endprogs[token[1]] or
endprogs[token[2]])
contstr, needcont = line[start:], 1
contline = line
break
else: # ordinary string
yield (STRING, token, spos, epos, line)
elif initial in namechars: # ordinary name
yield (NAME, token, spos, epos, line)
elif initial == '\\': # continued stmt
# This yield is new; needed for better idempotency:
yield (NL, token, spos, (lnum, pos), line)
continued = 1
else:
if initial in '([{': parenlev = parenlev + 1
elif initial in ')]}': parenlev = parenlev - 1
yield (OP, token, spos, epos, line)
else:
yield (ERRORTOKEN, line[pos],
(lnum, pos), (lnum, pos+1), line)
pos = pos + 1
for indent in indents[1:]: # pop remaining indent levels
yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
if __name__ == '__main__': # testing
import sys
if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline)
else: tokenize(sys.stdin.readline)
| gpl-2.0 |
Tagar/incubator-airflow | airflow/operators/postgres_operator.py | 3 | 2439 | # -*- coding: 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.
from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class PostgresOperator(BaseOperator):
"""
Executes sql code in a specific Postgres database
:param postgres_conn_id: reference to a specific postgres database
:type postgres_conn_id: string
:param sql: the sql code to be executed
:type sql: Can receive a str representing a sql statement,
a list of str (sql statements), or reference to a template file.
Template reference are recognized by str ending in '.sql'
:param database: name of database which overwrite defined one in connection
:type database: string
"""
template_fields = ('sql',)
template_ext = ('.sql',)
ui_color = '#ededed'
@apply_defaults
def __init__(
self, sql,
postgres_conn_id='postgres_default', autocommit=False,
parameters=None,
database=None,
*args, **kwargs):
super(PostgresOperator, self).__init__(*args, **kwargs)
self.sql = sql
self.postgres_conn_id = postgres_conn_id
self.autocommit = autocommit
self.parameters = parameters
self.database = database
def execute(self, context):
self.log.info('Executing: %s', self.sql)
self.hook = PostgresHook(postgres_conn_id=self.postgres_conn_id,
schema=self.database)
self.hook.run(self.sql, self.autocommit, parameters=self.parameters)
for output in self.hook.conn.notices:
self.log.info(output)
| apache-2.0 |
BigBrother1984/android_external_chromium_org | tools/deep_memory_profiler/subcommands/upload.py | 123 | 2545 | # Copyright 2013 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 logging
import os
import subprocess
import tempfile
import zipfile
from lib.subcommand import SubCommand
from lib.symbol import SymbolDataSources
LOGGER = logging.getLogger('dmprof')
class UploadCommand(SubCommand):
def __init__(self):
super(UploadCommand, self).__init__(
'Usage: %prog upload [--gsutil path/to/gsutil] '
'<first-dump> <destination-gs-path>')
self._parser.add_option('--gsutil', default='gsutil',
help='path to GSUTIL', metavar='GSUTIL')
def do(self, sys_argv):
options, args = self._parse_args(sys_argv, 2)
dump_path = args[1]
gs_path = args[2]
dump_files = SubCommand._find_all_dumps(dump_path)
bucket_files = SubCommand._find_all_buckets(dump_path)
prefix = SubCommand._find_prefix(dump_path)
symbol_data_sources = SymbolDataSources(prefix)
symbol_data_sources.prepare()
symbol_path = symbol_data_sources.path()
handle_zip, filename_zip = tempfile.mkstemp('.zip', 'dmprof')
os.close(handle_zip)
try:
file_zip = zipfile.ZipFile(filename_zip, 'w', zipfile.ZIP_DEFLATED)
for filename in dump_files:
file_zip.write(filename, os.path.basename(os.path.abspath(filename)))
for filename in bucket_files:
file_zip.write(filename, os.path.basename(os.path.abspath(filename)))
symbol_basename = os.path.basename(os.path.abspath(symbol_path))
for filename in os.listdir(symbol_path):
if not filename.startswith('.'):
file_zip.write(os.path.join(symbol_path, filename),
os.path.join(symbol_basename, os.path.basename(
os.path.abspath(filename))))
file_zip.close()
returncode = UploadCommand._run_gsutil(
options.gsutil, 'cp', '-a', 'public-read', filename_zip, gs_path)
finally:
os.remove(filename_zip)
return returncode
@staticmethod
def _run_gsutil(gsutil, *args):
"""Run gsutil as a subprocess.
Args:
*args: Arguments to pass to gsutil. The first argument should be an
operation such as ls, cp or cat.
Returns:
The return code from the process.
"""
command = [gsutil] + list(args)
LOGGER.info("Running: %s", command)
try:
return subprocess.call(command)
except OSError, e:
LOGGER.error('Error to run gsutil: %s', e)
| bsd-3-clause |
hlmnrmr/superdesk-core | superdesk/tests/steps.py | 1 | 91099 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import time
import shutil
from base64 import b64encode
from datetime import datetime, timedelta
from os.path import basename
from re import findall
from unittest.mock import patch
from urllib.parse import urlparse
import arrow
from behave import given, when, then # @UnresolvedImport
from bson import ObjectId
from eve.io.mongo import MongoJSONEncoder
from eve.methods.common import parse
from eve.utils import ParsedRequest, config
from flask import json
from wooper.assertions import (
assert_in, assert_equal, assertions
)
from wooper.general import (
fail_and_print_body, apply_path, parse_json_response,
WooperAssertionError
)
from wooper.expect import (
expect_status, expect_status_in,
expect_json, expect_json_length,
expect_json_contains, expect_json_not_contains,
expect_headers_contain,
)
import superdesk
from superdesk import tests
from superdesk.io import registered_feeding_services
from superdesk.io.commands.update_ingest import LAST_ITEM_UPDATE
from superdesk import default_user_preferences, get_resource_service, utc, etree
from superdesk.io.feed_parsers import XMLFeedParser, EMailRFC822FeedParser
from superdesk.utc import utcnow, get_expiry_date
from superdesk.tests import get_prefixed_url, set_placeholder
from apps.dictionaries.resource import DICTIONARY_FILE
from superdesk.filemeta import get_filemeta
external_url = 'http://thumbs.dreamstime.com/z/digital-nature-10485007.jpg'
DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S%z"
ANALYTICS_DATETIME_FORMAT = "%Y-%m-%d %H:00:00"
def test_json(context):
try:
response_data = json.loads(context.response.get_data())
except Exception:
fail_and_print_body(context.response, 'response is not valid json')
context_data = json.loads(apply_placeholders(context, context.text))
assert_equal(json_match(context_data, response_data), True,
msg=str(context_data) + '\n != \n' + str(response_data))
return response_data
def test_json_with_string_field_value(context, field):
try:
response_data = json.loads(context.response.get_data())
except Exception:
fail_and_print_body(context.response, 'response is not valid json')
context_data = json.loads(apply_placeholders(context, context.text))
assert_equal(json_match(context_data[field], response_data[field]), True,
msg=str(context_data) + '\n != \n' + str(response_data))
return response_data
def test_key_is_present(key, context, response):
"""Test if given key is present in response.
In case the context value is empty - "", {}, [] - it checks if it's non empty in response.
If it's set in context to false, it will check that it's falsy/empty in response too.
:param key
:param context
:param response
"""
assert not isinstance(context[key], bool) or not response[key], \
'"%s" should be empty or false, but it was "%s" in (%s)' % (key, response[key], response)
def test_key_is_not_present(key, response):
"""Test if given key is not present in response.
:param key
:param response
"""
assert key not in response, \
'"%s" should not be present, but it was "%s" in (%s)' % (key, response[key], response)
def assert_is_now(val, key):
"""Assert that given datetime value is now (with 2s tolerance).
:param val: datetime
:param key: val label - used for error reporting
"""
now = arrow.get()
val = arrow.get(val)
assert val + timedelta(seconds=2) > now, '%s should be now, it is %s' % (key, val)
def json_match(context_data, response_data):
if isinstance(context_data, dict):
if (not isinstance(response_data, dict)):
return False
for key in context_data:
if context_data[key] == "__none__":
assert response_data[key] is None
continue
if context_data[key] == "__no_value__":
test_key_is_not_present(key, response_data)
continue
if key not in response_data:
print(key, ' not in ', response_data)
return False
if context_data[key] == "__any_value__":
test_key_is_present(key, context_data, response_data)
continue
if context_data[key] == "__now__":
assert_is_now(response_data[key], key)
continue
if context_data[key] == "__empty__":
assert len(response_data[key]) == 0, '%s is not empty' % key
continue
if not json_match(context_data[key], response_data[key]):
return False
return True
elif isinstance(context_data, list):
for item_context in context_data:
found = False
for item_response in response_data:
if json_match(item_context, item_response):
found = True
break
if not found:
print(item_context, ' not in ', json.dumps(response_data, indent=2))
return False
return True
elif not isinstance(context_data, dict):
if context_data != response_data:
print('---' + str(context_data) + '---\n', ' != \n', '---' + str(response_data) + '---\n')
return context_data == response_data
def get_fixture_path(context, fixture):
path = context.app.settings['BEHAVE_TESTS_FIXTURES_PATH']
return os.path.join(path, fixture)
def get_macro_path(macro):
abspath = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
return os.path.join(abspath, 'macros', macro)
def get_self_href(resource, context):
assert '_links' in resource, 'expted "_links", but got only %s' % (resource)
return resource['_links']['self']['href']
def get_res(url, context):
response = context.client.get(get_prefixed_url(context.app, url), headers=context.headers)
expect_status(response, 200)
return json.loads(response.get_data())
def parse_date(datestr):
return datetime.strptime(datestr, DATETIME_FORMAT)
def format_date(date_to_format):
return date_to_format.strftime(DATETIME_FORMAT)
def format_date_analytics(date_to_format):
return date_to_format.strftime(ANALYTICS_DATETIME_FORMAT)
def assert_200(response):
"""Assert we get status code 200."""
expect_status_in(response, (200, 201, 204))
def assert_404(response):
"""Assert we get status code 404."""
assert response.status_code == 404, 'Expected 404, got %d' % (response.status_code)
def assert_ok(response):
"""Assert we get ok status within api response."""
expect_status_in(response, (200, 201))
expect_json_contains(response, {'_status': 'OK'})
def get_json_data(response):
return json.loads(response.get_data())
def get_it(context):
it = context.data[0]
res = get_res('/%s/%s' % (context.resource, it['_id']), context)
return get_self_href(res, context), res.get('_etag')
def if_match(context, etag):
headers = []
if etag:
headers = [('If-Match', etag)]
headers = unique_headers(headers, context.headers)
return headers
def unique_headers(headers_to_add, old_headers):
headers = dict(old_headers)
for item in headers_to_add:
headers.update({item[0]: item[1]})
unique_headers = [(k, v) for k, v in headers.items()]
return unique_headers
def patch_current_user(context, data):
response = context.client.get(get_prefixed_url(context.app, '/users/%s' % context.user['_id']),
headers=context.headers)
user = json.loads(response.get_data())
headers = if_match(context, user.get('_etag'))
response = context.client.patch(get_prefixed_url(context.app, '/users/%s' % context.user['_id']),
data=data, headers=headers)
assert_ok(response)
return response
def apply_placeholders(context, text):
placeholders = getattr(context, 'placeholders', {})
for placeholder in findall('#([^#"]+)#', text):
if placeholder.startswith('DATE'):
value = utcnow()
unit = placeholder.find('+')
if unit != -1:
value += timedelta(days=int(placeholder[unit + 1]))
else:
unit = placeholder.find('-')
if unit != -1:
value -= timedelta(days=int(placeholder[unit + 1]))
if placeholder == 'ANALYTICS_DATE_FORMATTED':
value = format_date_analytics(value)
else:
value = format_date(value)
placeholders['LAST_DATE_VALUE'] = value
elif placeholder not in placeholders:
try:
resource_name, field_name = placeholder.split('.', maxsplit=1)
except Exception:
continue
resource = getattr(context, resource_name, None)
for name in field_name.split('.'):
if not resource:
break
resource = resource.get(name, None)
if not resource:
continue
if isinstance(resource, datetime):
value = format_date(resource)
else:
value = str(resource)
else:
value = placeholders[placeholder]
text = text.replace('#%s#' % placeholder, value)
return text
def get_resource_name(url):
parsed_url = urlparse(url)
return basename(parsed_url.path)
def format_items(items):
output = [''] # insert empty line
for item in items:
if item.get('formatted_item'):
item['formatted_item'] = json.loads(item['formatted_item'])
output.append(json.dumps(item, indent=4, sort_keys=True))
return ',\n'.join(output)
@given('empty "{resource}"')
def step_impl_given_empty(context, resource):
if not is_user_resource(resource):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
get_resource_service(resource).delete_action()
@given('"{resource}"')
def step_impl_given_(context, resource):
data = apply_placeholders(context, context.text)
with context.app.test_request_context(context.app.config['URL_PREFIX']):
if not is_user_resource(resource):
get_resource_service(resource).delete_action()
items = [parse(item, resource) for item in json.loads(data)]
if is_user_resource(resource):
for item in items:
item.setdefault('needs_activation', False)
get_resource_service(resource).post(items)
context.data = items
context.resource = resource
try:
setattr(context, resource, items[-1])
except KeyError:
pass
@given('"{resource}" with objectid')
def step_impl_given_with_objectid(context, resource):
data = apply_placeholders(context, context.text)
with context.app.test_request_context(context.app.config['URL_PREFIX']):
items = [parse(item, resource) for item in json.loads(data)]
for item in items:
if '_id' in item:
item['_id'] = ObjectId(item['_id'])
get_resource_service(resource).post(items)
context.data = items
context.resource = resource
setattr(context, resource, items[-1])
@given('the "{resource}"')
def step_impl_given_the(context, resource):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
if not is_user_resource(resource):
get_resource_service(resource).delete_action()
orig_items = {}
items = [parse(item, resource) for item in json.loads(context.text)]
get_resource_service(resource).post(items)
context.data = orig_items or items
context.resource = resource
@given('ingest from "{provider}"')
def step_impl_given_resource_with_provider(context, provider):
resource = 'ingest'
with context.app.test_request_context(context.app.config['URL_PREFIX']):
get_resource_service(resource).delete_action()
items = [parse(item, resource) for item in json.loads(context.text)]
ingest_provider = get_resource_service('ingest_providers').find_one(req=None,
_id=context.providers[provider])
for item in items:
item['ingest_provider'] = context.providers[provider]
item['source'] = ingest_provider.get('source')
get_resource_service(resource).post(items)
context.data = items
context.resource = resource
@given('config update')
def given_config_update(context):
diff = json.loads(context.text)
context.app.config.update(diff)
if 'AMAZON_CONTAINER_NAME' in diff:
from superdesk.storage import AmazonMediaStorage
context.app.media = AmazonMediaStorage(context.app)
m = patch.object(context.app.media, 'client')
m.start()
@given('config')
def step_impl_given_config(context):
tests.setup(context, json.loads(context.text))
tests.setup_auth_user(context)
@given('we have "{role_name}" role')
def step_impl_given_role(context, role_name):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
role = get_resource_service('roles').find_one(name=role_name, req=None)
data = MongoJSONEncoder().encode({'role': role.get('_id')})
response = patch_current_user(context, data)
assert_ok(response)
@given('we have "{user_type}" as type of user')
def step_impl_given_user_type(context, user_type):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
data = json.dumps({'user_type': user_type})
response = patch_current_user(context, data)
assert_ok(response)
@when('we post to auth_db')
def step_impl_when_auth(context):
data = context.text
context.response = context.client.post(
get_prefixed_url(context.app, '/auth_db'), data=data, headers=context.headers)
if context.response.status_code == 200 or context.response.status_code == 201:
item = json.loads(context.response.get_data())
if item.get('_id'):
set_placeholder(context, 'AUTH_ID', item['_id'])
context.headers.append(('Authorization', b'basic ' + b64encode(item['token'].encode('ascii') + b':')))
context.user = item['user']
@when('we sleep for {limit}s')
def when_we_sleep_for(context, limit):
time.sleep(int(limit))
@given('we create a new macro "{macro_name}"')
def step_create_new_macro(context, macro_name):
src = get_fixture_path(context, macro_name)
dst = get_macro_path(macro_name)
shutil.copyfile(src, dst)
@when('we fetch from "{provider_name}" ingest "{guid}"')
def step_impl_fetch_from_provider_ingest(context, provider_name, guid):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
fetch_from_provider(context, provider_name, guid)
def embed_routing_scheme_rules(scheme):
"""Fetch all content filters referenced by the given routing scheme and embed those into scheme.
:param dict scheme: routing scheme configuration
"""
filters_service = superdesk.get_resource_service('content_filters')
rules_filters = (
(rule, str(rule['filter']))
for rule in scheme['rules'] if rule.get('filter'))
for rule, filter_id in rules_filters:
content_filter = filters_service.find_one(_id=filter_id, req=None)
rule['filter'] = content_filter
@when('we fetch from "{provider_name}" ingest "{guid}" using routing_scheme')
def step_impl_fetch_from_provider_ingest_using_routing(context, provider_name, guid):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
_id = apply_placeholders(context, context.text)
routing_scheme = get_resource_service('routing_schemes').find_one(_id=_id, req=None)
embed_routing_scheme_rules(routing_scheme)
fetch_from_provider(context, provider_name, guid, routing_scheme)
@when('we ingest and fetch "{provider_name}" "{guid}" to desk "{desk}" stage "{stage}" using routing_scheme')
def step_impl_fetch_from_provider_ingest_using_routing_with_desk(context, provider_name, guid, desk, stage):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
_id = apply_placeholders(context, context.text)
desk_id = apply_placeholders(context, desk)
stage_id = apply_placeholders(context, stage)
routing_scheme = get_resource_service('routing_schemes').find_one(_id=_id, req=None)
embed_routing_scheme_rules(routing_scheme)
fetch_from_provider(context, provider_name, guid, routing_scheme, desk_id, stage_id)
@when('we ingest with routing scheme "{provider_name}" "{guid}"')
def step_impl_ingest_with_routing_scheme(context, provider_name, guid):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
_id = apply_placeholders(context, context.text)
routing_scheme = get_resource_service('routing_schemes').find_one(_id=_id, req=None)
embed_routing_scheme_rules(routing_scheme)
fetch_from_provider(context, provider_name, guid, routing_scheme)
def fetch_from_provider(context, provider_name, guid, routing_scheme=None, desk_id=None, stage_id=None):
ingest_provider_service = get_resource_service('ingest_providers')
provider = ingest_provider_service.find_one(name=provider_name, req=None)
provider['routing_scheme'] = routing_scheme
if 'rule_set' in provider:
rule_set = get_resource_service('rule_sets').find_one(_id=provider['rule_set'], req=None)
else:
rule_set = None
provider_service = registered_feeding_services[provider['feeding_service']]
provider_service = provider_service.__class__()
if provider.get('name', '').lower() in ('aap', 'dpa', 'ninjs', 'email'):
file_path = os.path.join(provider.get('config', {}).get('path', ''), guid)
feeding_parser = provider_service.get_feed_parser(provider)
if isinstance(feeding_parser, XMLFeedParser):
with open(file_path, 'rb') as f:
xml_string = etree.etree.fromstring(f.read())
items = [feeding_parser.parse(xml_string, provider)]
elif isinstance(feeding_parser, EMailRFC822FeedParser):
with open(file_path, 'rb') as f:
data = f.read()
items = feeding_parser.parse([(1, data)], provider)
else:
parsed = feeding_parser.parse(file_path, provider)
items = [parsed] if not isinstance(parsed, list) else parsed
else:
provider_service.provider = provider
provider_service.URL = provider.get('config', {}).get('url')
items = provider_service.fetch_ingest(guid)
for item in items:
item['versioncreated'] = utcnow()
item['expiry'] = utcnow() + timedelta(minutes=20)
if desk_id:
from bson.objectid import ObjectId
item['task'] = {'desk': ObjectId(desk_id), 'stage': ObjectId(stage_id)}
failed = context.ingest_items(items, provider, provider_service, rule_set=rule_set,
routing_scheme=provider.get('routing_scheme'))
assert len(failed) == 0, failed
provider = ingest_provider_service.find_one(name=provider_name, req=None)
ingest_provider_service.system_update(provider['_id'], {LAST_ITEM_UPDATE: utcnow()}, provider)
for item in items:
set_placeholder(context, '{}.{}'.format(provider_name, item['guid']), item['_id'])
@when('we post to "{url}"')
def step_impl_when_post_url(context, url):
post_data(context, url)
@when('we post to "{url}" with delay')
def step_impl_when_post_url_delay(context, url):
time.sleep(1)
post_data(context, url)
def set_user_default(url, data):
if is_user_resource(url):
user = json.loads(data)
user.setdefault('needs_activation', False)
data = json.dumps(user)
def get_response_etag(response):
return json.loads(response.get_data())['_etag']
@when('we save etag')
def step_when_we_save_etag(context):
context.etag = get_response_etag(context.response)
@then('we get same etag')
def step_then_we_get_same_etag(context):
assert context.etag == get_response_etag(context.response), 'etags not matching'
def store_placeholder(context, url):
if context.response.status_code in (200, 201):
item = json.loads(context.response.get_data())
if item['_status'] == 'OK' and item.get('_id'):
try:
setattr(context, get_resource_name(url), item)
except (IndexError, KeyError):
pass
def post_data(context, url, success=False):
with context.app.mail.record_messages() as outbox:
data = apply_placeholders(context, context.text)
url = apply_placeholders(context, url)
set_user_default(url, data)
context.response = context.client.post(get_prefixed_url(context.app, url),
data=data, headers=context.headers)
if success:
assert_ok(context.response)
item = json.loads(context.response.get_data())
context.outbox = outbox
store_placeholder(context, url)
return item
@when('we post to "{url}" with "{tag}" and success')
def step_impl_when_post_url_with_tag(context, url, tag):
item = post_data(context, url, True)
if item.get('_id'):
set_placeholder(context, tag, item.get('_id'))
@given('we have "{url}" with "{tag}" and success')
def step_impl_given_post_url_with_tag(context, url, tag):
item = post_data(context, url, True)
if item.get('_id'):
set_placeholder(context, tag, item.get('_id'))
@when('we post to "{url}" with success')
def step_impl_when_post_url_with_success(context, url):
post_data(context, url, True)
@when('we put to "{url}"')
def step_impl_when_put_url(context, url):
with context.app.mail.record_messages() as outbox:
data = apply_placeholders(context, context.text)
href = get_self_href(url)
context.response = context.client.put(get_prefixed_url(context.app, href), data=data, headers=context.headers)
assert_ok(context.response)
context.outbox = outbox
@when('we get "{url}"')
def when_we_get_url(context, url):
url = apply_placeholders(context, url).encode('ascii').decode('unicode-escape')
headers = []
if context.text:
for line in context.text.split('\n'):
key, val = line.split(': ')
headers.append((key, val))
headers = unique_headers(headers, context.headers)
url = apply_placeholders(context, url)
context.response = context.client.get(get_prefixed_url(context.app, url), headers=headers)
@when('we get dictionary "{dictionary_id}"')
def when_we_get_dictionary(context, dictionary_id):
dictionary_id = apply_placeholders(context, dictionary_id)
url = '/dictionaries/' + dictionary_id + '?projection={"content": 1}'
return when_we_get_url(context, url)
@then('we get latest')
def step_impl_we_get_latest(context):
data = get_json_data(context.response)
href = get_self_href(data, context)
headers = if_match(context, data.get('_etag'))
href = get_prefixed_url(context.app, href)
context.response = context.client.get(href, headers=headers)
assert_200(context.response)
@when('we find for "{resource}" the id as "{name}" by "{search_criteria}"')
def when_we_find_for_resource_the_id_as_name_by_search_criteria(context, resource, name, search_criteria):
url = '/' + resource + '?' + search_criteria
context.response = context.client.get(get_prefixed_url(context.app, url), headers=context.headers)
if context.response.status_code == 200:
expect_json_length(context.response, 1, path='_items')
item = json.loads(context.response.get_data())
item = item['_items'][0]
if item.get('_id'):
set_placeholder(context, name, item['_id'])
@when('we delete "{url}"')
def step_impl_when_delete_url(context, url):
with context.app.mail.record_messages() as outbox:
url = apply_placeholders(context, url)
res = get_res(url, context)
href = get_self_href(res, context)
headers = if_match(context, res.get('_etag'))
href = get_prefixed_url(context.app, href)
context.response = context.client.delete(href, headers=headers)
context.outbox = outbox
@when('we delete link "{url}"')
def step_impl_when_delete_link_url(context, url):
with context.app.mail.record_messages() as outbox:
url = apply_placeholders(context, url)
headers = context.headers
context.response = context.client.delete(get_prefixed_url(context.app, url), headers=headers)
context.outbox = outbox
@when('we delete all sessions "{url}"')
def step_impl_when_delete_all_url(context, url):
with context.app.mail.record_messages() as outbox:
url = apply_placeholders(context, url)
headers = context.headers
href = get_prefixed_url(context.app, url)
context.response = context.client.delete(href, headers=headers)
context.outbox = outbox
@when('we delete latest')
def when_we_delete_it(context):
with context.app.mail.record_messages() as outbox:
res = get_json_data(context.response)
href = get_self_href(res, context)
headers = if_match(context, res.get('_etag'))
href = get_prefixed_url(context.app, href)
context.response = context.client.delete(href, headers=headers)
context.email = outbox
@when('we patch "{url}"')
def step_impl_when_patch_url(context, url):
with context.app.mail.record_messages() as outbox:
url = apply_placeholders(context, url)
res = get_res(url, context)
href = get_self_href(res, context)
headers = if_match(context, res.get('_etag'))
data = apply_placeholders(context, context.text)
href = get_prefixed_url(context.app, href)
context.response = context.client.patch(href, data=data, headers=headers)
context.outbox = outbox
@when('we patch latest')
def step_impl_when_patch_again(context):
with context.app.mail.record_messages() as outbox:
data = get_json_data(context.response)
href = get_prefixed_url(context.app, get_self_href(data, context))
headers = if_match(context, data.get('_etag'))
data2 = apply_placeholders(context, context.text)
context.response = context.client.patch(href, data=data2, headers=headers)
if context.response.status_code in (200, 201):
item = json.loads(context.response.get_data())
if item['_status'] == 'OK' and item.get('_id'):
setattr(context, get_resource_name(href), item)
assert_ok(context.response)
context.outbox = outbox
@when('we patch latest without assert')
def step_impl_when_patch_without_assert(context):
data = get_json_data(context.response)
href = get_prefixed_url(context.app, get_self_href(data, context))
headers = if_match(context, data.get('_etag'))
data2 = apply_placeholders(context, context.text)
context.response = context.client.patch(href, data=data2, headers=headers)
@when('we patch routing scheme "{url}"')
def step_impl_when_patch_routing_scheme(context, url):
with context.app.mail.record_messages() as outbox:
url = apply_placeholders(context, url)
res = get_res(url, context)
href = get_self_href(res, context)
headers = if_match(context, res.get('_etag'))
data = json.loads(apply_placeholders(context, context.text))
res.get('rules', []).append(data)
context.response = context.client.patch(get_prefixed_url(context.app, href),
data=json.dumps({'rules': res.get('rules', [])}),
headers=headers)
context.outbox = outbox
@when('we patch given')
def step_impl_when_patch(context):
with context.app.mail.record_messages() as outbox:
href, etag = get_it(context)
headers = if_match(context, etag)
context.response = context.client.patch(get_prefixed_url(context.app, href), data=context.text, headers=headers)
assert_ok(context.response)
context.outbox = outbox
@when('we get given')
def step_impl_when_get(context):
href, _etag = get_it(context)
context.response = context.client.get(get_prefixed_url(context.app, href), headers=context.headers)
@when('we restore version {version}')
def step_impl_when_restore_version(context, version):
data = get_json_data(context.response)
href = get_self_href(data, context)
headers = if_match(context, data.get('_etag'))
text = '{"type": "text", "old_version": %s, "last_version": %s}' % (version, data.get('_current_version'))
context.response = context.client.put(get_prefixed_url(context.app, href), data=text, headers=headers)
assert_ok(context.response)
@when('we upload a file "{filename}" to "{dest}"')
def step_impl_when_upload_image(context, filename, dest):
upload_file(context, dest, filename, 'media')
@when('we upload a binary file with cropping')
def step_impl_when_upload_with_crop(context):
data = {'CropTop': '0', 'CropLeft': '0', 'CropBottom': '333', 'CropRight': '333'}
upload_file(context, '/upload', 'bike.jpg', 'media', data)
@when('upload a file "{file_name}" to "{destination}" with "{guid}"')
def step_impl_when_upload_image_with_guid(context, file_name, destination, guid):
upload_file(context, destination, file_name, 'media', {'guid': guid})
if destination == 'archive':
set_placeholder(context, 'original.href', context.archive['renditions']['original']['href'])
set_placeholder(context, 'original.media', context.archive['renditions']['original']['media'])
@when('we upload a new dictionary with success')
def when_upload_dictionary(context):
data = json.loads(apply_placeholders(context, context.text))
upload_file(context, '/dictionaries', 'test_dict.txt', DICTIONARY_FILE, data)
assert_ok(context.response)
@when('we upload to an existing dictionary with success')
def when_upload_patch_dictionary(context):
data = json.loads(apply_placeholders(context, context.text))
url = apply_placeholders(context, '/dictionaries/#dictionaries._id#')
etag = apply_placeholders(context, '#dictionaries._etag#')
upload_file(context, url, 'test_dict2.txt', DICTIONARY_FILE, data, 'patch', [('If-Match', etag)])
assert_ok(context.response)
def upload_file(context, dest, filename, file_field, extra_data=None, method='post', user_headers=[]):
with open(get_fixture_path(context, filename), 'rb') as f:
data = {file_field: f}
if extra_data:
data.update(extra_data)
headers = [('Content-Type', 'multipart/form-data')]
headers.extend(user_headers)
headers = unique_headers(headers, context.headers)
url = get_prefixed_url(context.app, dest)
context.response = getattr(context.client, method)(url, data=data, headers=headers)
assert_ok(context.response)
store_placeholder(context, url)
@when('we upload a file from URL')
def step_impl_when_upload_from_url(context):
data = {'URL': external_url}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
context.response = context.client.post(get_prefixed_url(context.app, '/upload'), data=data, headers=headers)
@when('we upload a file from URL with cropping')
def step_impl_when_upload_from_url_with_crop(context):
data = {'URL': external_url,
'CropTop': '0',
'CropLeft': '0',
'CropBottom': '333',
'CropRight': '333'}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
context.response = context.client.post(get_prefixed_url(context.app, '/upload'), data=data, headers=headers)
@when('we get user profile')
def step_impl_when_get_user(context):
profile_url = '/%s/%s' % ('users', context.user['_id'])
context.response = context.client.get(get_prefixed_url(context.app, profile_url), headers=context.headers)
@then('we get new resource')
def step_impl_then_get_new(context):
assert_ok(context.response)
expect_json_contains(context.response, 'self', path='_links')
if context.text is not None:
return test_json(context)
@then('we get error {code}')
def step_impl_then_get_error(context, code):
expect_status(context.response, int(code))
if context.text:
test_json(context)
@then('we get list with {total_count} items')
def step_impl_then_get_list(context, total_count):
assert_200(context.response)
data = get_json_data(context.response)
int_count = int(total_count.replace('+', '').replace('<', ''))
if '+' in total_count:
assert int_count <= data['_meta']['total'], '%d items is not enough' % data['_meta']['total']
elif total_count.startswith('<'):
assert int_count > data['_meta']['total'], '%d items is too much' % data['_meta']['total']
else:
assert int_count == data['_meta']['total'], 'got %d: %s' % (data['_meta']['total'],
format_items(data['_items']))
if context.text:
test_json(context)
@then('we get list ordered by {field} with {total_count} items')
def step_impl_ordered_list(context, field, total_count):
step_impl_then_get_list(context, total_count)
data = get_json_data(context.response)
fields = []
for i in data['_items']:
fields.append(i[field])
assert sorted(fields) == fields
@then('we get "{value}" in formatted output')
def step_impl_then_get_formatted_output(context, value):
assert_200(context.response)
value = apply_placeholders(context, value)
data = get_json_data(context.response)
for item in data['_items']:
if value in item['formatted_item']:
return
assert False
@then('we get "{value}" in formatted output as "{group}" story for subscriber "{sub}"')
def step_impl_then_get_formatted_output_as_story(context, value, group, sub):
assert_200(context.response)
value = apply_placeholders(context, value)
data = get_json_data(context.response)
for item in data['_items']:
if item['subscriber_id'] != sub:
continue
try:
formatted_data = json.loads(item['formatted_item'])
except Exception:
continue
associations = formatted_data.get('associations', {})
for assoc_group in associations:
if assoc_group.startswith(group) and associations[assoc_group].get('guid', '') == value:
return
assert False
@then('we get "{value}" as "{group}" story for subscriber "{sub}" in package "{pck}"')
def step_impl_then_get_formatted_output_pck(context, value, group, sub, pck):
assert_200(context.response)
value = apply_placeholders(context, value)
data = get_json_data(context.response)
for item in data['_items']:
if item['item_id'] != pck:
continue
if item['subscriber_id'] != sub:
continue
try:
formatted_data = json.loads(item['formatted_item'])
except Exception:
continue
associations = formatted_data.get('associations', {})
for assoc_group in associations:
if assoc_group.startswith(group) and associations[assoc_group].get('guid', '') == value:
return
assert False
@then('we get "{value}" as "{group}" story for subscriber "{sub}" not in package "{pck}" version "{v}"')
def step_impl_then_get_formatted_output_pck_version(context, value, group, sub, pck, v):
assert_200(context.response)
value = apply_placeholders(context, value)
data = get_json_data(context.response)
for item in data['_items']:
if item['item_id'] == pck:
if item['subscriber_id'] == sub and str(item['item_version']) == v:
try:
formatted_data = json.loads(item['formatted_item'])
except Exception:
continue
associations = formatted_data.get('associations', {})
for assoc_group in associations:
if assoc_group.startswith(group) \
and associations[assoc_group].get('guid', '') == value:
assert False
assert True
return
assert False
@then('we get "{value}" in formatted output as "{group}" newsml12 story')
def step_impl_then_get_formatted_output_newsml(context, value, group):
assert_200(context.response)
value = apply_placeholders(context, value)
data = get_json_data(context.response)
for item in data['_items']:
if '<' + group + '>' + value + '</' + group + '>' in item['formatted_item']:
return
assert False
@then('we get no "{field}"')
def step_impl_then_get_nofield(context, field):
assert_200(context.response)
expect_json_not_contains(context.response, field)
@then('expect json in "{path}"')
def step_impl_then_get_nofield_in_path(context, path):
assert_200(context.response)
expect_json(context.response, context.text, path)
@then('we get existing resource')
def step_impl_then_get_existing(context):
assert_200(context.response)
test_json(context)
@then('we get existing saved search')
def step_impl_then_get_existing_saved_search(context):
assert_200(context.response)
test_json_with_string_field_value(context, 'filter')
@then('we get OK response')
def step_impl_then_get_ok(context):
assert_200(context.response)
@then('we get response code {code}')
def step_impl_then_get_code(context, code):
expect_status(context.response, int(code))
@then('we get updated response')
def step_impl_then_get_updated(context):
assert_ok(context.response)
if context.text:
test_json(context)
@then('we get "{key}" in "{url}"')
def step_impl_then_get_key_in_url(context, key, url):
url = apply_placeholders(context, url)
res = context.client.get(get_prefixed_url(context.app, url), headers=context.headers)
assert_200(res)
expect_json_contains(res, key)
@then('we get file metadata')
def step_impl_then_get_file_meta(context):
assert len(
json.loads(apply_path(
parse_json_response(context.response),
'filemeta_json'
)).items()
) > 0
'expected non empty metadata dictionary'
@then('we get "{filename}" metadata')
def step_impl_then_get_given_file_meta(context, filename):
if filename == 'bike.jpg':
metadata = {
'ycbcrpositioning': 1,
'imagelength': 2448,
'exifimagewidth': 2448,
'meteringmode': 2,
'datetimedigitized': '2013:08:01 16:19:28',
'exposuremode': 0,
'flashpixversion': '0100',
'isospeedratings': 80,
'length': 469900,
'imageuniqueid': 'f3533c05daef2debe6257fd99e058eec',
'datetimeoriginal': '2013:08:01 16:19:28',
'whitebalance': 0,
'exposureprogram': 3,
'colorspace': 1,
'exifimageheight': 3264,
'software': 'Google',
'resolutionunit': 2,
'make': 'SAMSUNG',
'maxaperturevalue': [276, 100],
'aperturevalue': [276, 100],
'scenecapturetype': 0,
'exposuretime': [1, 2004],
'datetime': '2013:08:01 16:19:28',
'exifoffset': 216,
'yresolution': [72, 1],
'orientation': 1,
'componentsconfiguration': '0000',
'exifversion': '0220',
'focallength': [37, 10],
'flash': 0,
'model': 'GT-I9300',
'xresolution': [72, 1],
'fnumber': [26, 10],
'imagewidth': 3264,
'brightnessvalue': [2362, 256],
'exposurebiasvalue': [0, 10],
'shutterspeedvalue': [2808, 256]
}
elif filename == 'green.ogg':
metadata = {
'producer': 'Lavf54.59.103',
'music_genre': 'New Age',
'sample_rate': '44100',
'artist': 'Maxime Abbey',
'length': 368058,
'bit_rate': '160000',
'title': 'Green Hills',
'mime_type': 'audio/vorbis',
'format_version': 'Vorbis version 0',
'compression': 'Vorbis',
'duration': '0:00:20.088163',
'endian': 'Little endian',
'nb_channel': '2'
}
elif filename == 'this_week_nasa.mp4':
metadata = {
'mime_type': 'video/mp4',
'creation_date': '1904-01-01T00:00:00+00:00',
'duration': '0:00:10.224000',
'width': '480',
'length': 877869,
'comment': 'User volume: 100.0%',
'height': '270',
'endian': 'Big endian',
'last_modification': '1904-01-01T00:00:00+00:00'
}
else:
raise NotImplementedError("No metadata for file '{}'.".format(filename))
assertions.maxDiff = None
data = json.loads(context.response.get_data())
filemeta = get_filemeta(data)
json_match(filemeta, metadata)
@then('we get "{type}" renditions')
def step_impl_then_get_renditions(context, type):
expect_json_contains(context.response, 'renditions')
renditions = apply_path(parse_json_response(context.response), 'renditions')
assert isinstance(renditions, dict), 'expected dict for image renditions'
for rend_name in context.app.config['RENDITIONS'][type]:
desc = renditions[rend_name]
assert isinstance(desc, dict), 'expected dict for rendition description'
assert 'href' in desc, 'expected href in rendition description'
assert 'media' in desc, 'expected media identifier in rendition description'
we_can_fetch_a_file(context, desc['href'], 'image/jpeg')
@then('we get "{crop_name}" in renditions')
def step_impl_then_get_renditions(context, crop_name):
expect_json_contains(context.response, 'renditions')
renditions = apply_path(parse_json_response(context.response), 'renditions')
assert isinstance(renditions, dict), 'expected dict for image renditions'
desc = renditions[crop_name]
assert isinstance(desc, dict), 'expected dict for rendition description'
assert 'href' in desc, 'expected href in rendition description'
assert 'media' in desc, 'expected media identifier in rendition description'
we_can_fetch_a_file(context, desc['href'], 'image/jpeg')
@then('we get "{crop_name}" not in renditions')
def step_impl_then_get_renditions(context, crop_name):
expect_json_contains(context.response, 'renditions')
renditions = apply_path(parse_json_response(context.response), 'renditions')
assert isinstance(renditions, dict), 'expected dict for image renditions'
assert crop_name not in renditions, 'expected crop not in renditions'
@then('item "{item_id}" is unlocked')
def then_item_is_unlocked(context, item_id):
assert_200(context.response)
data = json.loads(context.response.get_data())
assert data.get('lock_user', None) is None, 'item is locked by user #{0}'.format(data.get('lock_user'))
@then('item "{item_id}" is locked')
def then_item_is_locked(context, item_id):
assert_200(context.response)
resp = parse_json_response(context.response)
assert resp['lock_user'] is not None
@then('item "{item_id}" is assigned')
def then_item_is_assigned(context, item_id):
resp = parse_json_response(context.response)
assert resp['task'].get('user', None) is not None, 'item is not assigned'
@then('we get rendition "{name}" with mimetype "{mimetype}"')
def step_impl_then_get_rendition_with_mimetype(context, name, mimetype):
expect_json_contains(context.response, 'renditions')
renditions = apply_path(parse_json_response(context.response), 'renditions')
assert isinstance(renditions, dict), 'expected dict for image renditions'
desc = renditions[name]
assert isinstance(desc, dict), 'expected dict for rendition description'
assert 'href' in desc, 'expected href in rendition description'
we_can_fetch_a_file(context, desc['href'], mimetype)
set_placeholder(context, "rendition.{}.href".format(name), desc['href'])
@when('we get updated media from archive')
def get_updated_media_from_archive(context):
url = 'archive/%s' % context._id
when_we_get_url(context, url)
assert_200(context.response)
@then('baseImage rendition is updated')
def check_base_image_rendition(context):
check_rendition(context, 'baseImage')
@then('original rendition is updated with link to file having mimetype "{mimetype}"')
def check_original_rendition(context, mimetype):
rv = parse_json_response(context.response)
link_to_file = rv['renditions']['original']['href']
assert link_to_file
we_can_fetch_a_file(context, link_to_file, mimetype)
@then('thumbnail rendition is updated')
def check_thumbnail_rendition(context):
check_rendition(context, 'thumbnail')
def check_rendition(context, rendition_name):
rv = parse_json_response(context.response)
assert rv['renditions'][rendition_name] != context.renditions[rendition_name], rv['renditions']
@then('we get "{key}"')
def step_impl_then_get_key(context, key):
assert_200(context.response)
expect_json_contains(context.response, key)
item = json.loads(context.response.get_data())
set_placeholder(context, '%s' % key, item[key])
@then('we store "{key}" with value "{value}" to context')
def step_impl_then_we_store_key_value_to_context(context, key, value):
set_placeholder(context, key, apply_placeholders(context, value))
@then('we get action in user activity')
def step_impl_then_get_action(context):
response = context.client.get(get_prefixed_url(context.app, '/activity'), headers=context.headers)
expect_json_contains(response, '_items')
@then('we get a file reference')
def step_impl_then_get_file(context):
assert_200(context.response)
expect_json_contains(context.response, 'renditions')
data = get_json_data(context.response)
url = '/upload/%s' % data['_id']
headers = [('Accept', 'application/json')]
headers = unique_headers(headers, context.headers)
response = context.client.get(get_prefixed_url(context.app, url), headers=headers)
assert_200(response)
assert len(response.get_data()), response
assert response.mimetype == 'application/json', response.mimetype
expect_json_contains(response, 'renditions')
expect_json_contains(response, {'mimetype': 'image/jpeg'})
fetched_data = get_json_data(context.response)
context.fetched_data = fetched_data
@then('we get cropped data smaller than "{max_size}"')
def step_impl_then_get_cropped_file(context, max_size):
assert int(get_filemeta(context.fetched_data, 'length')) < int(max_size), 'was expecting smaller image'
@then('we can fetch a data_uri')
def step_impl_we_fetch_data_uri(context):
we_can_fetch_a_file(context, context.fetched_data['renditions']['original']['href'], 'image/jpeg')
@then('we fetch a file "{url}"')
def step_impl_we_cannot_fetch_file(context, url):
url = apply_placeholders(context, url)
headers = [('Accept', 'application/json')]
headers = unique_headers(headers, context.headers)
context.response = context.client.get(get_prefixed_url(context.app, url), headers=headers)
def we_can_fetch_a_file(context, url, mimetype):
headers = [('Accept', 'application/json')]
headers = unique_headers(headers, context.headers)
response = context.client.get(get_prefixed_url(context.app, url), headers=headers)
assert_200(response)
assert len(response.get_data()), response
assert response.mimetype == mimetype, response.mimetype
@then('we can delete that file')
def step_impl_we_delete_file(context):
url = '/upload/%s' % context.fetched_data['_id']
context.headers.append(('Accept', 'application/json'))
headers = if_match(context, context.fetched_data.get('_etag'))
response = context.client.delete(get_prefixed_url(context.app, url), headers=headers)
assert_200(response)
response = context.client.get(get_prefixed_url(context.app, url), headers=headers)
assert_404(response)
@then('we get a picture url')
def step_impl_then_get_picture(context):
assert_ok(context.response)
expect_json_contains(context.response, 'picture_url')
@then('we get aggregations "{keys}"')
def step_impl_then_get_aggs(context, keys):
assert_200(context.response)
expect_json_contains(context.response, '_aggregations')
data = get_json_data(context.response)
aggs = data['_aggregations']
for key in keys.split(','):
assert_in(key, aggs)
@then('the file is stored localy')
def step_impl_then_file(context):
assert_200(context.response)
folder = context.app.config['UPLOAD_FOLDER']
assert os.path.exists(os.path.join(folder, context.filename))
@then('we get version {version}')
def step_impl_then_get_version(context, version):
assert_200(context.response)
expect_json_contains(context.response, {'_current_version': int(version)})
@then('the field "{field}" value is "{value}"')
def step_impl_then_get_field_value(context, field, value):
assert_200(context.response)
expect_json_contains(context.response, {field: value})
@then('we get etag matching "{url}"')
def step_impl_then_get_etag(context, url):
if context.app.config['IF_MATCH']:
assert_200(context.response)
expect_json_contains(context.response, '_etag')
etag = get_json_data(context.response).get('_etag')
response = context.client.get(get_prefixed_url(context.app, url), headers=context.headers)
expect_json_contains(response, {'_etag': etag})
@then('we get not modified response')
def step_impl_then_not_modified(context):
expect_status(context.response, 304)
@then('we get "{header}" header')
def step_impl_then_get_header(context, header):
expect_headers_contain(context.response, header)
@then('we get "{header}" header with "{type}" type')
def step_impl_then_get_header_with_type(context, header, type):
expect_headers_contain(context.response, header, type)
@then('we get link to "{resource}"')
def then_we_get_link_to_resource(context, resource):
doc = get_json_data(context.response)
self_link = doc.get('_links').get('self')
assert resource in self_link['href'], 'expect link to "%s", got %s' % (resource, self_link)
@then('we get deleted response')
def then_we_get_deleted_response(context):
assert_200(context.response)
@when('we post to reset_password we get email with token')
def we_post_to_reset_password(context):
data = {'email': 'foo@bar.org'}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
with context.app.mail.record_messages() as outbox:
context.response = context.client.post(get_prefixed_url(context.app, '/reset_user_password'),
data=data, headers=headers)
expect_status_in(context.response, (200, 201))
assert len(outbox) == 1
assert outbox[0].subject == "Reset password"
email_text = outbox[0].body
assert "24" in email_text
words = email_text.split()
url = urlparse(words[words.index("link") + 1])
token = url.fragment.split('token=')[-1]
assert token
context.token = token
@then('we can check if token is valid')
def we_can_check_token_is_valid(context):
data = {'token': context.token}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
context.response = context.client.post(get_prefixed_url(context.app, '/reset_user_password'),
data=data, headers=headers)
expect_status_in(context.response, (200, 201))
@then('we update token to be expired')
def we_update_token_to_expired(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
expiry = utc.utcnow() - timedelta(days=2)
reset_request = get_resource_service('reset_user_password').find_one(req=None, token=context.token)
reset_request['expire_time'] = expiry
id = reset_request.pop('_id')
get_resource_service('reset_user_password').patch(id, reset_request)
@then('token is invalid')
def check_token_invalid(context):
data = {'token': context.token}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
context.response = context.client.post(get_prefixed_url(context.app, '/reset_user_password'),
data=data, headers=headers)
expect_status_in(context.response, (403, 401))
@when('we post to reset_password we do not get email with token')
def we_post_to_reset_password_it_fails(context):
data = {'email': 'foo@bar.org'}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
with context.app.mail.record_messages() as outbox:
context.response = context.client.post(get_prefixed_url(context.app, '/reset_user_password'),
data=data, headers=headers)
expect_status_in(context.response, (200, 201))
assert len(outbox) == 0
def start_reset_password_for_user(context):
data = {'token': context.token, 'password': 'test_pass'}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
context.response = context.client.post(get_prefixed_url(context.app, '/reset_user_password'),
data=data, headers=headers)
@then('we fail to reset password for user')
def we_fail_to_reset_password_for_user(context):
start_reset_password_for_user(context)
step_impl_then_get_error(context, 403)
@then('we reset password for user')
def we_reset_password_for_user(context):
start_reset_password_for_user(context)
expect_status_in(context.response, (200, 201))
auth_data = {'username': 'foo', 'password': 'test_pass'}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
context.response = context.client.post(get_prefixed_url(context.app, '/auth_db'), data=auth_data, headers=headers)
expect_status_in(context.response, (200, 201))
@when('we switch user')
def when_we_switch_user(context):
user = {'username': 'test-user-2', 'password': 'pwd', 'is_active': True,
'needs_activation': False, 'sign_off': 'foo'}
tests.setup_auth_user(context, user)
set_placeholder(context, 'USERS_ID', str(context.user['_id']))
@when('we setup test user')
def when_we_setup_test_user(context):
tests.setup_auth_user(context, tests.test_user)
@when('we get my "{url}"')
def when_we_get_my_url(context, url):
user_id = str(context.user.get('_id'))
my_url = '{0}?where={1}'.format(url, json.dumps({'user': user_id}))
return when_we_get_url(context, my_url)
@when('we get user "{resource}"')
def when_we_get_user_resource(context, resource):
url = '/users/{0}/{1}'.format(str(context.user.get('_id')), resource)
return when_we_get_url(context, url)
@then('we get embedded items')
def we_get_embedded_items(context):
response_data = json.loads(context.response.get_data())
href = get_self_href(response_data, context)
url = href + '/?embedded={"items": 1}'
context.response = context.client.get(get_prefixed_url(context.app, url), headers=context.headers)
assert_200(context.response)
context.response_data = json.loads(context.response.get_data())
assert len(context.response_data['items']['view_items']) == 2
@when('we reset notifications')
def step_when_we_reset_notifications(context):
context.app.notification_client.reset()
@then('we get notifications')
def then_we_get_notifications(context):
assert hasattr(context.app.notification_client, 'messages'), 'no messages'
notifications = context.app.notification_client.messages
notifications_data = [json.loads(notification) for notification in notifications]
context_data = json.loads(apply_placeholders(context, context.text))
assert_equal(json_match(context_data, notifications_data), True,
msg=str(context_data) + '\n != \n' + str(notifications_data))
@then('we get default preferences')
def get_default_prefs(context):
response_data = json.loads(context.response.get_data())
assert_equal(response_data['user_preferences'], default_user_preferences)
@when('we spike "{item_id}"')
def step_impl_when_spike_url(context, item_id):
item_id = apply_placeholders(context, item_id)
res = get_res('/archive/' + item_id, context)
headers = if_match(context, res.get('_etag'))
context.response = context.client.patch(get_prefixed_url(context.app, '/archive/spike/' + item_id),
data='{"state": "spiked"}', headers=headers)
@when('we spike fetched item')
def step_impl_when_spike_fetched_item(context):
data = json.loads(apply_placeholders(context, context.text))
item_id = data["_id"]
res = get_res('/archive/' + item_id, context)
headers = if_match(context, res.get('_etag'))
context.response = context.client.patch(get_prefixed_url(context.app, '/archive/spike/' + item_id),
data='{"state": "spiked"}', headers=headers)
@when('we unspike "{item_id}"')
def step_impl_when_unspike_url(context, item_id):
item_id = apply_placeholders(context, item_id)
res = get_res('/archive/' + item_id, context)
headers = if_match(context, res.get('_etag'))
context.response = context.client.patch(get_prefixed_url(context.app, '/archive/unspike/' + item_id),
data=apply_placeholders(context, context.text or '{}'), headers=headers)
@then('we get spiked content "{item_id}"')
def get_spiked_content(context, item_id):
item_id = apply_placeholders(context, item_id)
url = 'archive/{0}'.format(item_id)
when_we_get_url(context, url)
assert_200(context.response)
response_data = json.loads(context.response.get_data())
assert_equal(response_data['state'], 'spiked')
assert_equal(response_data['operation'], 'spike')
@then('we get unspiked content "{id}"')
def get_unspiked_content(context, id):
text = context.text
context.text = ''
url = 'archive/{0}'.format(id)
when_we_get_url(context, url)
assert_200(context.response)
response_data = json.loads(context.response.get_data())
assert_equal(response_data['state'], 'draft')
assert_equal(response_data['operation'], 'unspike')
# Tolga Akin (05/11/14)
# Expiry value doesn't get set to None properly in Elastic.
# Discussed with Petr so we'll look into this later
# assert_equal(response_data['expiry'], None)
if text:
assert json_match(json.loads(apply_placeholders(context, text)), response_data)
@then('we get global content expiry')
def get_global_content_expiry(context):
validate_expired_content(context, context.app.config['CONTENT_EXPIRY_MINUTES'], utcnow())
@then('we get content expiry {minutes}')
def get_content_expiry(context, minutes):
validate_expired_content(context, minutes, utcnow())
@then('we get expiry for schedule and embargo content {minutes} minutes after "{future_date}"')
def get_content_expiry_schedule(context, minutes, future_date):
future_date = parse_date(apply_placeholders(context, future_date))
validate_expired_content(context, minutes, future_date)
@then('we get desk spike expiry after "{test_minutes}"')
def get_desk_spike_expiry(context, test_minutes):
validate_expired_content(context, test_minutes, utcnow())
def validate_expired_content(context, minutes, start_datetime):
response_data = json.loads(context.response.get_data())
assert response_data['expiry']
response_expiry = parse_date(response_data['expiry'])
expiry = start_datetime + timedelta(minutes=int(minutes))
assert response_expiry <= expiry
@when('we mention user in comment for "{url}"')
def we_mention_user_in_comment(context, url):
with context.app.mail.record_messages() as outbox:
step_impl_when_post_url(context, url)
assert len(outbox) == 1
assert_equal(outbox[0].subject, "You were mentioned in a comment by test_user")
email_text = outbox[0].body
assert email_text
@when('we change user status to "{status}" using "{url}"')
def we_change_user_status(context, status, url):
with context.app.mail.record_messages() as outbox:
step_impl_when_patch_url(context, url)
assert len(outbox) == 1
assert_equal(outbox[0].subject, "Your Superdesk account is " + status)
assert outbox[0].body
@when('we get the default incoming stage')
def we_get_default_incoming_stage(context):
data = json.loads(context.response.get_data())
incoming_stage = data['_items'][0]['incoming_stage'] if '_items' in data else data['incoming_stage']
assert incoming_stage
url = 'stages/{0}'.format(incoming_stage)
when_we_get_url(context, url)
assert_200(context.response)
data = json.loads(context.response.get_data())
assert data['default_incoming'] is True
assert data['name'] == 'Incoming Stage'
@then('we get stage filled in to default_incoming')
def we_get_stage_filled_in(context):
data = json.loads(context.response.get_data())
assert data['task']['stage']
@given('we have sessions "{url}"')
def we_have_sessions_get_id(context, url):
when_we_get_url(context, url)
item = json.loads(context.response.get_data())
context.session_id = item['_items'][0]['_id']
context.data = item
set_placeholder(context, 'SESSION_ID', item['_items'][0]['_id'])
setattr(context, 'users', item['_items'][0]['user'])
@then('we get session by id')
def we_get_session_by_id(context):
url = 'sessions/' + context.session_id
when_we_get_url(context, url)
item = json.loads(context.response.get_data())
returned_id = item["_id"]
assert context.session_id == returned_id
@then('we delete session by id')
def we_delete_session_by_id(context):
url = 'sessions/' + context.session_id
step_impl_when_delete_url(context, url)
assert_200(context.response)
@when('we create a new user')
def step_create_a_user(context):
data = apply_placeholders(context, context.text)
with context.app.mail.record_messages() as outbox:
context.response = context.client.post(get_prefixed_url(context.app, '/users'),
data=data, headers=context.headers)
expect_status_in(context.response, (200, 201))
assert len(outbox) == 1
context.email = outbox[0]
@then('we get activation email')
def step_get_activation_email(context):
assert context.email.subject == 'Superdesk account created'
email_text = context.email.body
words = email_text.split()
url = urlparse(words[words.index("to") + 1])
token = url.fragment.split('token=')[-1]
assert token
@then('we set elastic limit')
def step_set_limit(context):
context.app.settings['MAX_SEARCH_DEPTH'] = 1
@then('we get emails')
def step_we_get_email(context):
data = json.loads(context.text)
for email in data:
assert check_if_email_sent(context, email)
@then('we get {count} emails')
def step_we_get_no_email(context, count):
assert len(context.outbox) == int(count)
if context.text:
step_we_get_email(context)
def check_if_email_sent(context, spec):
if context.outbox:
for key in spec:
found = False
values = [getattr(email, key) for email in context.outbox]
for value in values:
if spec[key] in value:
found = True
if not found:
print('%s:%s not found in %s' % (key, spec[key], json.dumps(values, indent=2)))
return False
return True
print('no email sent')
return False
@then('we get activity')
def then_we_get_activity(context):
url = apply_placeholders(context, '/activity?where={"name": {"$in": ["notify", "user:mention" , "desk:mention"]}}')
context.response = context.client.get(get_prefixed_url(context.app, url), headers=context.headers)
if context.response.status_code == 200:
expect_json_length(context.response, 1, path='_items')
item = json.loads(context.response.get_data())
item = item['_items'][0]
if item.get('_id'):
setattr(context, 'activity', item)
set_placeholder(context, 'USERS_ID', item['user'])
def login_as(context, username, password, user_type):
user = {'username': username, 'password': password, 'is_active': True,
'is_enabled': True, 'needs_activation': False, user_type: user_type}
if context.text:
user.update(json.loads(context.text))
tests.setup_auth_user(context, user)
@given('we login as user "{username}" with password "{password}" and user type "{user_type}"')
def given_we_login_as_user(context, username, password, user_type):
login_as(context, username, password, user_type)
@when('we login as user "{username}" with password "{password}" and user type "{user_type}"')
def when_we_login_as_user(context, username, password, user_type):
login_as(context, username, password, user_type)
def is_user_resource(resource):
return resource in ('users', '/users')
@then('we get {no_of_stages} invisible stages')
def when_we_get_invisible_stages(context, no_of_stages):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
stages = get_resource_service('stages').get_stages_by_visibility(is_visible=False)
assert len(stages) == int(no_of_stages)
@then('we get {no_of_stages} visible stages')
def when_we_get_visible_stages(context, no_of_stages):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
stages = get_resource_service('stages').get_stages_by_visibility(is_visible=True)
assert len(stages) == int(no_of_stages)
@then('we get {no_of_stages} invisible stages for user')
def when_we_get_invisible_stages_for_user(context, no_of_stages):
data = json.loads(apply_placeholders(context, context.text))
with context.app.test_request_context(context.app.config['URL_PREFIX']):
stages = get_resource_service('users').get_invisible_stages(data['user'])
assert len(stages) == int(no_of_stages)
@then('we get "{field_name}" populated')
def then_field_is_populated(context, field_name):
resp = parse_json_response(context.response)
assert resp[field_name].get('user', None) is not None, 'item is not populated'
@then('we get "{field_name}" not populated')
def then_field_is_not_populated(context, field_name):
resp = parse_json_response(context.response)
assert resp[field_name] is None, 'item is not populated'
@then('the field "{field_name}" value is not "{field_value}"')
def then_field_value_is_not_same(context, field_name, field_value):
resp = parse_json_response(context.response)
assert resp[field_name] != field_value, 'values are the same'
@then('we get "{field_name}" not populated in results')
def then_field_is_not_populated_in_results(context, field_name):
resps = parse_json_response(context.response)
for resp in resps['_items']:
assert resp[field_name] is None, 'item is not populated'
@when('we delete content filter "{name}"')
def step_delete_content_filter(context, name):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
filter = get_resource_service('content_filters').find_one(req=None, name=name)
url = '/content_filters/{}'.format(filter['_id'])
headers = if_match(context, filter.get('_etag'))
context.response = context.client.delete(get_prefixed_url(context.app, url), headers=headers)
@when('we rewrite "{item_id}"')
def step_impl_when_rewrite(context, item_id):
context_data = {}
_id = apply_placeholders(context, item_id)
if context.text:
context_data.update(json.loads(apply_placeholders(context, context.text)))
data = json.dumps(context_data)
context.response = context.client.post(
get_prefixed_url(context.app, '/archive/{}/rewrite'.format(_id)),
data=data, headers=context.headers)
if context.response.status_code == 400:
return
resp = parse_json_response(context.response)
set_placeholder(context, 'REWRITE_OF', _id)
set_placeholder(context, 'REWRITE_ID', resp['_id'])
@then('we get "{field_name}" does not exist')
def then_field_is_not_populated_in_results(context, field_name):
resps = parse_json_response(context.response)
if '_items' in resps:
for resp in resps['_items']:
assert field_name not in resp, 'field exists'
else:
assert field_name not in resps, 'field exists'
@then('we get "{field_name}" does exist')
def then_field_is_not_populated_in_results(context, field_name):
resps = parse_json_response(context.response)
for resp in resps['_items']:
assert field_name in resp, 'field does not exist'
@when('we publish "{item_id}" with "{pub_type}" type and "{state}" state')
def step_impl_when_publish_url(context, item_id, pub_type, state):
item_id = apply_placeholders(context, item_id)
res = get_res('/archive/' + item_id, context)
headers = if_match(context, res.get('_etag'))
context_data = {"state": state}
if context.text:
data = apply_placeholders(context, context.text)
context_data.update(json.loads(data))
data = json.dumps(context_data)
context.response = context.client.patch(get_prefixed_url(context.app, '/archive/{}/{}'.format(pub_type, item_id)),
data=data, headers=headers)
store_placeholder(context, 'archive_{}'.format(pub_type))
@then('the ingest item is routed based on routing scheme and rule "{rule_name}"')
def then_ingest_item_is_routed_based_on_routing_scheme(context, rule_name):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
validate_routed_item(context, rule_name, True)
@then('the ingest item is routed and transformed based on routing scheme and rule "{rule_name}"')
def then_ingest_item_is_routed_transformed_based_on_routing_scheme(context, rule_name):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
validate_routed_item(context, rule_name, True, True)
@then('the ingest item is not routed based on routing scheme and rule "{rule_name}"')
def then_ingest_item_is_not_routed_based_on_routing_scheme(context, rule_name):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
validate_routed_item(context, rule_name, False)
def validate_routed_item(context, rule_name, is_routed, is_transformed=False):
data = json.loads(apply_placeholders(context, context.text))
def validate_rule(action, state):
for destination in rule.get('actions', {}).get(action, []):
query = {
'and': [
{'term': {'ingest_id': str(data['ingest'])}},
{'term': {'task.desk': str(destination['desk'])}},
{'term': {'task.stage': str(destination['stage'])}},
{'term': {'state': state}}
]
}
item = get_archive_items(query) + get_published_items(query)
if is_routed:
assert len(item) > 0, 'No routed items found for criteria: ' + str(query)
assert item[0]['ingest_id'] == data['ingest']
assert item[0]['task']['desk'] == str(destination['desk'])
assert item[0]['task']['stage'] == str(destination['stage'])
assert item[0]['state'] == state
if is_transformed:
assert item[0]['abstract'] == 'Abstract has been updated'
assert_items_in_package(item[0], state, str(destination['desk']), str(destination['stage']))
else:
assert len(item) == 0
scheme = get_resource_service('routing_schemes').find_one(_id=data['routing_scheme'], req=None)
rule = next((rule for rule in scheme['rules'] if rule['name'].lower() == rule_name.lower()), {})
validate_rule('fetch', 'routed')
validate_rule('publish', 'published')
@when('we schedule the routing scheme "{scheme_id}"')
def when_we_schedule_the_routing_scheme(context, scheme_id):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
scheme_id = apply_placeholders(context, scheme_id)
url = apply_placeholders(context, 'routing_schemes/%s' % scheme_id)
res = get_res(url, context)
href = get_self_href(res, context)
headers = if_match(context, res.get('_etag'))
rule = res.get('rules')[0]
now = utcnow()
from apps.rules.routing_rules import Weekdays
rule['schedule'] = {
'day_of_week': [
Weekdays.dayname(now + timedelta(days=1)),
Weekdays.dayname(now + timedelta(days=2))
],
'hour_of_day_from': '16:00:00',
'hour_of_day_to': '20:00:00'
}
if len(res.get('rules')) > 1:
rule = res.get('rules')[1]
rule['schedule'] = {
'day_of_week': [Weekdays.dayname(now)]
}
context.response = context.client.patch(get_prefixed_url(context.app, href),
data=json.dumps({'rules': res.get('rules', [])}),
headers=headers)
assert_200(context.response)
def get_archive_items(query):
req = ParsedRequest()
req.max_results = 100
req.args = {'filter': json.dumps(query)}
return list(get_resource_service('archive').get(lookup=None, req=req))
def get_published_items(query):
req = ParsedRequest()
req.max_results = 100
req.args = {'filter': json.dumps(query)}
return list(get_resource_service('published').get(lookup=None, req=req))
def assert_items_in_package(item, state, desk, stage):
if item.get('groups'):
terms = [{'term': {'_id': ref.get('residRef')}}
for ref in [ref for group in item.get('groups', [])
for ref in group.get('refs', []) if 'residRef' in ref]]
query = {'or': terms}
items = get_archive_items(query)
assert len(items) == len(terms)
for item in items:
assert item.get('state') == state
assert item.get('task', {}).get('desk') == desk
assert item.get('task', {}).get('stage') == stage
@given('I logout')
def logout(context):
we_have_sessions_get_id(context, '/sessions')
step_impl_when_delete_url(context, '/auth_db/{}'.format(context.session_id))
assert_200(context.response)
@then('we get "{url}" and match')
def we_get_and_match(context, url):
url = apply_placeholders(context, url)
response_data = get_res(url, context)
context_data = json.loads(apply_placeholders(context, context.text))
assert_equal(json_match(context_data, response_data), True,
msg=str(context_data) + '\n != \n' + str(response_data))
@then('there is no "{key}" in response')
def there_is_no_key_in_response(context, key):
data = get_json_data(context.response)
assert key not in data, 'key "%s" is in %s' % (key, data)
@then('there is no "{key}" in task')
def there_is_no_key_in_preferences(context, key):
data = get_json_data(context.response)['task']
assert key not in data, 'key "%s" is in task' % key
@then('there is no "{key}" in data')
def there_is_no_profile_in_data(context, key):
data = get_json_data(context.response)['_items'][0]['data']
assert key not in data, 'key "%s" is in data' % key
@then('broadcast "{key}" has value "{value}"')
def broadcast_key_has_value(context, key, value):
data = get_json_data(context.response).get('broadcast', {})
value = apply_placeholders(context, value)
if value.lower() == 'none':
assert data[key] is None, 'key "%s" is not none and has value "%s"' % (key, data[key])
else:
assert data[key] == value, 'key "%s" does not have valid value "%s"' % (key, data[key])
@then('there is no "{key}" preference')
def there_is_no_preference(context, key):
data = get_json_data(context.response)
assert key not in data['user_preferences'], '%s is in %s' % (key, data['user_preferences'].keys())
@then('there is no "{key}" in "{namespace}" preferences')
def there_is_no_key_in_namespace_preferences(context, key, namespace):
data = get_json_data(context.response)['user_preferences']
assert key not in data[namespace], 'key "%s" is in %s' % (key, data[namespace])
@then('we check if article has Embargo')
def step_impl_then_check_embargo(context):
assert_200(context.response)
try:
response_data = json.loads(context.response.get_data())
except Exception:
fail_and_print_body(context.response, 'response is not valid json')
if response_data.get('_meta') and response_data.get('_items'):
for item in response_data.get('_items'):
assert_embargo(context, item)
else:
assert_embargo(context, response_data)
def assert_embargo(context, item):
if not item.get('embargo'):
fail_and_print_body(context, context.response, 'Embargo not found')
@when('embargo lapses for "{item_id}"')
def embargo_lapses(context, item_id):
item_id = apply_placeholders(context, item_id)
item = get_res("/archive/%s" % item_id, context)
updates = {'embargo': (utcnow() - timedelta(minutes=10)),
'schedule_settings': {'utc_embargo': (utcnow() - timedelta(minutes=10))}}
with context.app.test_request_context(context.app.config['URL_PREFIX']):
get_resource_service('archive').system_update(id=item['_id'], original=item, updates=updates)
@then('we validate the published item expiry to be after publish expiry set in desk settings {publish_expiry_in_desk}')
def validate_published_item_expiry(context, publish_expiry_in_desk):
assert_200(context.response)
try:
response_data = json.loads(context.response.get_data())
except Exception:
fail_and_print_body(context.response, 'response is not valid json')
if response_data.get('_meta') and response_data.get('_items'):
for item in response_data.get('_items'):
assert_expiry(item, publish_expiry_in_desk)
else:
assert_expiry(response_data, publish_expiry_in_desk)
@then('we get updated timestamp "{field}"')
def step_we_get_updated_timestamp(context, field):
data = get_json_data(context.response)
timestamp = arrow.get(data[field])
now = utcnow()
assert timestamp + timedelta(seconds=5) > now, 'timestamp < now (%s, %s)' % (timestamp, now) # 5s tolerance
def assert_expiry(item, publish_expiry_in_desk):
embargo = item.get('embargo')
actual = parse_date(item.get('expiry'))
error_message = 'Published Item Expiry validation fails'
publish_expiry_in_desk = int(publish_expiry_in_desk)
if embargo:
expected = get_expiry_date(minutes=publish_expiry_in_desk,
offset=datetime.strptime(embargo, '%Y-%m-%dT%H:%M:%S%z'))
if actual != expected:
raise WooperAssertionError("{}. Expected: {}, Actual: {}".format(error_message, expected, actual))
else:
expected = get_expiry_date(minutes=publish_expiry_in_desk)
if expected < actual:
raise WooperAssertionError("{}. Expected: {}, Actual: {}".format(error_message, expected, actual))
@when('run import legal publish queue')
def run_import_legal_publish_queue(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
from apps.legal_archive import ImportLegalPublishQueueCommand
ImportLegalPublishQueueCommand().run()
@when('we expire items')
def expire_content(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
ids = json.loads(apply_placeholders(context, context.text))
expiry = utcnow() - timedelta(minutes=5)
for item_id in ids:
original = get_resource_service('archive').find_one(req=None, _id=item_id)
get_resource_service('archive').system_update(item_id, {'expiry': expiry}, original)
get_resource_service('published').update_published_items(item_id, 'expiry', expiry)
from apps.archive.commands import RemoveExpiredContent
RemoveExpiredContent().run()
@when('the publish schedule lapses')
def run_overdue_schedule_jobs(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
ids = json.loads(apply_placeholders(context, context.text))
lapse_time = utcnow() - timedelta(minutes=5)
updates = {
'publish_schedule': lapse_time,
'schedule_settings': {
'utc_publish_schedule': lapse_time,
'time_zone': None
}
}
for item_id in ids:
original = get_resource_service('archive').find_one(req=None, _id=item_id)
get_resource_service('archive').system_update(item_id, updates, original)
get_resource_service('published').update_published_items(item_id, 'publish_schedule', lapse_time)
get_resource_service('published').update_published_items(item_id, 'schedule_settings.utc_publish_schedule',
lapse_time)
@when('we transmit items')
def expire_content(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
from superdesk.publish.publish_content import PublishContent
PublishContent().run()
@when('we remove item "{_id}" from mongo')
def remove_item_from_mongo(context, _id):
with context.app.app_context():
context.app.data.mongo.remove('archive', {'_id': _id})
@then('we get text "{text}" in response field "{field}"')
def we_get_text_in_field(context, text, field):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
resp = parse_json_response(context.response)
assert field in resp, 'Field {} not found in response.'.format(field)
assert isinstance(resp.get(field), str), 'Invalid type'
assert text in resp.get(field, ''), '{} contains text: {}. Text To find: {}'.format(field,
resp.get(field, ''),
text)
@then('we reset priority flag for updated articles')
def we_get_reset_default_priority_for_updated_articles(context):
context.app.config['RESET_PRIORITY_VALUE_FOR_UPDATE_ARTICLES'] = True
@then('we mark the items not moved to legal')
def we_mark_the_items_not_moved_to_legal(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
ids = json.loads(apply_placeholders(context, context.text))
for item_id in ids:
get_resource_service('published').update_published_items(item_id, 'moved_to_legal', False)
@when('we run import legal archive command')
def we_run_import_legal_archive_command(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
from apps.legal_archive.commands import ImportLegalArchiveCommand
ImportLegalArchiveCommand().run()
@then('we find no reference of package "{reference}" in item')
def we_find_no_reference_of_package_in_item(context, reference):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
reference = apply_placeholders(context, reference)
resp = parse_json_response(context.response)
linked_in_packages = resp.get('linked_in_packages', [])
assert reference not in [p.get('package') for p in linked_in_packages], \
'Package reference {} found in item'.format(reference)
@then('we set spike exipry "{expiry}"')
def we_set_spike_exipry(context, expiry):
context.app.settings['SPIKE_EXPIRY_MINUTES'] = int(expiry)
@then('we set published item expiry {expiry}')
def we_set_published_item_expiry(context, expiry):
context.app.settings['PUBLISHED_CONTENT_EXPIRY_MINUTES'] = int(expiry)
@then('we set copy metadata from parent flag')
def we_set_copy_metadata_from_parent(context):
context.app.settings['COPY_METADATA_FROM_PARENT'] = True
@then('we assert the content api item "{item_id}" is published to subscriber "{subscriber}"')
def we_assert_content_api_item_is_published_to_subscriber(context, item_id, subscriber):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
item_id = apply_placeholders(context, item_id)
subscriber = apply_placeholders(context, subscriber)
req = ParsedRequest()
req.projection = json.dumps({'subscribers': 1})
cursor = get_resource_service('items').get_from_mongo(req, {'_id': item_id})
assert cursor.count() > 0, 'Item not found'
item = cursor[0]
subscriber = apply_placeholders(context, subscriber)
assert len(item.get('subscribers', [])) > 0, 'No subscribers found.'
assert subscriber in item.get('subscribers', []), 'Subscriber with Id: {} not found.'.format(subscriber)
@then('we assert the content api item "{item_id}" is not published to subscriber "{subscriber}"')
def we_assert_content_api_item_is_not_published_to_subscriber(context, item_id, subscriber):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
item_id = apply_placeholders(context, item_id)
subscriber = apply_placeholders(context, subscriber)
req = ParsedRequest()
req.projection = json.dumps({'subscribers': 1})
cursor = get_resource_service('items').get_from_mongo(req, {'_id': item_id})
assert cursor.count() > 0, 'Item not found'
item = cursor[0]
subscriber = apply_placeholders(context, subscriber)
assert subscriber not in item.get('subscribers', []), \
'Subscriber with Id: {} found for the item. '.format(subscriber)
@then('we assert the content api item "{item_id}" is not published to any subscribers')
def we_assert_content_api_item_is_not_published(context, item_id):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
item_id = apply_placeholders(context, item_id)
req = ParsedRequest()
req.projection = json.dumps({'subscribers': 1})
cursor = get_resource_service('items').get_from_mongo(req, {'_id': item_id})
assert cursor.count() > 0, 'Item not found'
item = cursor[0]
assert len(item.get('subscribers', [])) == 0, \
'Item published to subscribers {}.'.format(item.get('subscribers', []))
@then('we ensure that archived schema extra fields are not present in duplicated item')
def we_ensure_that_archived_schema_extra_fields_are_not_present(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
eve_keys = set([config.ID_FIELD, config.LAST_UPDATED, config.DATE_CREATED, config.VERSION, config.ETAG])
archived_schema_keys = set(context.app.config['DOMAIN']['archived']['schema'].keys())
archived_schema_keys.union(eve_keys)
archive_schema_keys = set(context.app.config['DOMAIN']['archive']['schema'].keys())
archive_schema_keys.union(eve_keys)
extra_fields = [key for key in archived_schema_keys if key not in archive_schema_keys]
duplicate_item = json.loads(context.response.get_data())
for field in extra_fields:
assert field not in duplicate_item, 'Field {} found the duplicate item'.format(field)
@then('we assert content api item "{item_id}" with associated item "{embedded_id}" is published to "{subscriber}"')
def we_assert_that_associated_item_for_subscriber(context, item_id, embedded_id, subscriber):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
item_id = apply_placeholders(context, item_id)
subscriber = apply_placeholders(context, subscriber)
embedded_id = apply_placeholders(context, embedded_id)
req = ParsedRequest()
cursor = get_resource_service('items').get_from_mongo(req, {'_id': item_id})
assert cursor.count() > 0, 'Item not found'
item = cursor[0]
assert embedded_id in (item.get('associations') or {}), '{} association not found.'.format(embedded_id)
assert subscriber in (item['associations'][embedded_id] or {}).get('subscribers', []), \
'{} subscriber not found in associations {}'.format(subscriber, embedded_id)
@then('we assert content api item "{item_id}" with associated item "{embedded_id}" is not published to "{subscriber}"')
def we_assert_that_associated_item_for_subscriber(context, item_id, embedded_id, subscriber):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
item_id = apply_placeholders(context, item_id)
subscriber = apply_placeholders(context, subscriber)
embedded_id = apply_placeholders(context, embedded_id)
req = ParsedRequest()
cursor = get_resource_service('items').get_from_mongo(req, {'_id': item_id})
assert cursor.count() > 0, 'Item not found'
item = cursor[0]
assert embedded_id in (item.get('associations') or {}), '{} association not found.'.format(embedded_id)
assert subscriber not in (item['associations'][embedded_id] or {}).get('subscribers', []), \
'{} subscriber found in associations {}'.format(subscriber, embedded_id)
@then('file exists "{path}"')
def then_file_exists(context, path):
assert os.path.isfile(path), '{} is not a file'.format(path)
| agpl-3.0 |
ESS-LLP/erpnext-healthcare | erpnext/hr/doctype/payroll_entry/payroll_entry.py | 1 | 20575 | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from dateutil.relativedelta import relativedelta
from frappe.utils import cint, flt, nowdate, add_days, getdate, fmt_money, add_to_date, DATE_FORMAT, date_diff
from frappe import _
from erpnext.accounts.utils import get_fiscal_year
from erpnext.hr.doctype.employee.employee import get_holiday_list_for_employee
class PayrollEntry(Document):
def on_submit(self):
self.create_salary_slips()
def before_submit(self):
if self.validate_attendance:
if self.validate_employee_attendance():
frappe.throw(_("Cannot Submit, Employees left to mark attendance"))
def get_emp_list(self):
"""
Returns list of active employees based on selected criteria
and for which salary structure exists
"""
cond = self.get_filter_condition()
cond += self.get_joining_releiving_condition()
condition = ''
if self.payroll_frequency:
condition = """and payroll_frequency = '%(payroll_frequency)s'"""% {"payroll_frequency": self.payroll_frequency}
sal_struct = frappe.db.sql_list("""
select
name from `tabSalary Structure`
where
docstatus = 1 and
is_active = 'Yes'
and company = %(company)s and
ifnull(salary_slip_based_on_timesheet,0) = %(salary_slip_based_on_timesheet)s
{condition}""".format(condition=condition),
{"company": self.company, "salary_slip_based_on_timesheet":self.salary_slip_based_on_timesheet})
if sal_struct:
cond += "and t2.salary_structure IN %(sal_struct)s "
cond += "and %(from_date)s >= t2.from_date"
emp_list = frappe.db.sql("""
select
distinct t1.name as employee, t1.employee_name, t1.department, t1.designation
from
`tabEmployee` t1, `tabSalary Structure Assignment` t2
where
t1.name = t2.employee
and t2.docstatus = 1
%s order by t2.from_date desc
""" % cond, {"sal_struct": tuple(sal_struct), "from_date": self.end_date}, as_dict=True)
return emp_list
def fill_employee_details(self):
self.set('employees', [])
employees = self.get_emp_list()
if not employees:
frappe.throw(_("No employees for the mentioned criteria"))
for d in employees:
self.append('employees', d)
self.number_of_employees = len(employees)
if self.validate_attendance:
return self.validate_employee_attendance()
def get_filter_condition(self):
self.check_mandatory()
cond = ''
for f in ['company', 'branch', 'department', 'designation']:
if self.get(f):
cond += " and t1." + f + " = '" + self.get(f).replace("'", "\'") + "'"
return cond
def get_joining_releiving_condition(self):
cond = """
and ifnull(t1.date_of_joining, '0000-00-00') <= '%(end_date)s'
and ifnull(t1.relieving_date, '2199-12-31') >= '%(start_date)s'
""" % {"start_date": self.start_date, "end_date": self.end_date}
return cond
def check_mandatory(self):
for fieldname in ['company', 'start_date', 'end_date']:
if not self.get(fieldname):
frappe.throw(_("Please set {0}").format(self.meta.get_label(fieldname)))
def create_salary_slips(self):
"""
Creates salary slip for selected employees if already not created
"""
self.check_permission('write')
self.created = 1
emp_list = [d.employee for d in self.get_emp_list()]
if emp_list:
args = frappe._dict({
"salary_slip_based_on_timesheet": self.salary_slip_based_on_timesheet,
"payroll_frequency": self.payroll_frequency,
"start_date": self.start_date,
"end_date": self.end_date,
"company": self.company,
"posting_date": self.posting_date,
"deduct_tax_for_unclaimed_employee_benefits": self.deduct_tax_for_unclaimed_employee_benefits,
"deduct_tax_for_unsubmitted_tax_exemption_proof": self.deduct_tax_for_unsubmitted_tax_exemption_proof,
"payroll_entry": self.name
})
if len(emp_list) > 30:
frappe.enqueue(create_salary_slips_for_employees, timeout=600, employees=emp_list, args=args)
else:
create_salary_slips_for_employees(emp_list, args, publish_progress=False)
def get_sal_slip_list(self, ss_status, as_dict=False):
"""
Returns list of salary slips based on selected criteria
"""
cond = self.get_filter_condition()
ss_list = frappe.db.sql("""
select t1.name, t1.salary_structure from `tabSalary Slip` t1
where t1.docstatus = %s and t1.start_date >= %s and t1.end_date <= %s
and (t1.journal_entry is null or t1.journal_entry = "") and ifnull(salary_slip_based_on_timesheet,0) = %s %s
""" % ('%s', '%s', '%s','%s', cond), (ss_status, self.start_date, self.end_date, self.salary_slip_based_on_timesheet), as_dict=as_dict)
return ss_list
def submit_salary_slips(self):
self.check_permission('write')
ss_list = self.get_sal_slip_list(ss_status=0)
if len(ss_list) > 30:
frappe.enqueue(submit_salary_slips_for_employees, timeout=600, payroll_entry=self, salary_slips=ss_list)
else:
submit_salary_slips_for_employees(self, ss_list, publish_progress=False)
def email_salary_slip(self, submitted_ss):
if frappe.db.get_single_value("HR Settings", "email_salary_slip_to_employee"):
for ss in submitted_ss:
ss.email_salary_slip()
def get_loan_details(self):
"""
Get loan details from submitted salary slip based on selected criteria
"""
cond = self.get_filter_condition()
return frappe.db.sql(""" select eld.loan_account, eld.loan,
eld.interest_income_account, eld.principal_amount, eld.interest_amount, eld.total_payment
from
`tabSalary Slip` t1, `tabSalary Slip Loan` eld
where
t1.docstatus = 1 and t1.name = eld.parent and start_date >= %s and end_date <= %s %s
""" % ('%s', '%s', cond), (self.start_date, self.end_date), as_dict=True) or []
def get_salary_component_account(self, salary_component):
account = frappe.db.get_value("Salary Component Account",
{"parent": salary_component, "company": self.company}, "default_account")
if not account:
frappe.throw(_("Please set default account in Salary Component {0}")
.format(salary_component))
return account
def get_salary_components(self, component_type):
salary_slips = self.get_sal_slip_list(ss_status = 1, as_dict = True)
if salary_slips:
salary_components = frappe.db.sql("""select salary_component, amount, parentfield
from `tabSalary Detail` where parentfield = '%s' and parent in (%s)""" %
(component_type, ', '.join(['%s']*len(salary_slips))), tuple([d.name for d in salary_slips]), as_dict=True)
return salary_components
def get_salary_component_total(self, component_type = None):
salary_components = self.get_salary_components(component_type)
if salary_components:
component_dict = {}
for item in salary_components:
add_component_to_accrual_jv_entry = True
if component_type == "earnings":
is_flexible_benefit, only_tax_impact = frappe.db.get_value("Salary Component", item['salary_component'], ['is_flexible_benefit', 'only_tax_impact'])
if is_flexible_benefit == 1 and only_tax_impact ==1:
add_component_to_accrual_jv_entry = False
if add_component_to_accrual_jv_entry:
component_dict[item['salary_component']] = component_dict.get(item['salary_component'], 0) + item['amount']
account_details = self.get_account(component_dict = component_dict)
return account_details
def get_account(self, component_dict = None):
account_dict = {}
for s, a in component_dict.items():
account = self.get_salary_component_account(s)
account_dict[account] = account_dict.get(account, 0) + a
return account_dict
def get_default_payroll_payable_account(self):
payroll_payable_account = frappe.get_cached_value('Company',
{"company_name": self.company}, "default_payroll_payable_account")
if not payroll_payable_account:
frappe.throw(_("Please set Default Payroll Payable Account in Company {0}")
.format(self.company))
return payroll_payable_account
def make_accrual_jv_entry(self):
self.check_permission('write')
earnings = self.get_salary_component_total(component_type = "earnings") or {}
deductions = self.get_salary_component_total(component_type = "deductions") or {}
default_payroll_payable_account = self.get_default_payroll_payable_account()
loan_details = self.get_loan_details()
jv_name = ""
precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
if earnings or deductions:
journal_entry = frappe.new_doc('Journal Entry')
journal_entry.voucher_type = 'Journal Entry'
journal_entry.user_remark = _('Accrual Journal Entry for salaries from {0} to {1}')\
.format(self.start_date, self.end_date)
journal_entry.company = self.company
journal_entry.posting_date = self.posting_date
accounts = []
payable_amount = 0
# Earnings
for acc, amount in earnings.items():
payable_amount += flt(amount, precision)
accounts.append({
"account": acc,
"debit_in_account_currency": flt(amount, precision),
"cost_center": self.cost_center,
"project": self.project
})
# Deductions
for acc, amount in deductions.items():
payable_amount -= flt(amount, precision)
accounts.append({
"account": acc,
"credit_in_account_currency": flt(amount, precision),
"cost_center": self.cost_center,
"project": self.project
})
# Loan
for data in loan_details:
accounts.append({
"account": data.loan_account,
"credit_in_account_currency": data.principal_amount
})
if data.interest_amount and not data.interest_income_account:
frappe.throw(_("Select interest income account in loan {0}").format(data.loan))
if data.interest_income_account and data.interest_amount:
accounts.append({
"account": data.interest_income_account,
"credit_in_account_currency": data.interest_amount,
"cost_center": self.cost_center,
"project": self.project
})
payable_amount -= flt(data.total_payment, precision)
# Payable amount
accounts.append({
"account": default_payroll_payable_account,
"credit_in_account_currency": flt(payable_amount, precision)
})
journal_entry.set("accounts", accounts)
journal_entry.title = default_payroll_payable_account
journal_entry.save()
try:
journal_entry.submit()
jv_name = journal_entry.name
self.update_salary_slip_status(jv_name = jv_name)
except Exception as e:
frappe.msgprint(e)
return jv_name
def make_payment_entry(self):
self.check_permission('write')
cond = self.get_filter_condition()
salary_slip_name_list = frappe.db.sql(""" select t1.name from `tabSalary Slip` t1
where t1.docstatus = 1 and start_date >= %s and end_date <= %s %s
""" % ('%s', '%s', cond), (self.start_date, self.end_date), as_list = True)
if salary_slip_name_list and len(salary_slip_name_list) > 0:
salary_slip_total = 0
for salary_slip_name in salary_slip_name_list:
salary_slip = frappe.get_doc("Salary Slip", salary_slip_name[0])
for sal_detail in salary_slip.earnings:
is_flexible_benefit, only_tax_impact, creat_separate_je, statistical_component = frappe.db.get_value("Salary Component", sal_detail.salary_component,
['is_flexible_benefit', 'only_tax_impact', 'create_separate_payment_entry_against_benefit_claim', 'statistical_component'])
if only_tax_impact != 1 and statistical_component != 1:
if is_flexible_benefit == 1 and creat_separate_je == 1:
self.create_journal_entry(sal_detail.amount, sal_detail.salary_component)
else:
salary_slip_total += sal_detail.amount
for sal_detail in salary_slip.deductions:
statistical_component = frappe.db.get_value("Salary Component", sal_detail.salary_component, 'statistical_component')
if statistical_component != 1:
salary_slip_total -= sal_detail.amount
if salary_slip_total > 0:
self.create_journal_entry(salary_slip_total, "salary")
def create_journal_entry(self, je_payment_amount, user_remark):
default_payroll_payable_account = self.get_default_payroll_payable_account()
precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
journal_entry = frappe.new_doc('Journal Entry')
journal_entry.voucher_type = 'Bank Entry'
journal_entry.user_remark = _('Payment of {0} from {1} to {2}')\
.format(user_remark, self.start_date, self.end_date)
journal_entry.company = self.company
journal_entry.posting_date = self.posting_date
payment_amount = flt(je_payment_amount, precision)
journal_entry.set("accounts", [
{
"account": self.payment_account,
"credit_in_account_currency": payment_amount
},
{
"account": default_payroll_payable_account,
"debit_in_account_currency": payment_amount,
"reference_type": self.doctype,
"reference_name": self.name
}
])
journal_entry.save(ignore_permissions = True)
def update_salary_slip_status(self, jv_name = None):
ss_list = self.get_sal_slip_list(ss_status=1)
for ss in ss_list:
ss_obj = frappe.get_doc("Salary Slip",ss[0])
frappe.db.set_value("Salary Slip", ss_obj.name, "journal_entry", jv_name)
def set_start_end_dates(self):
self.update(get_start_end_dates(self.payroll_frequency,
self.start_date or self.posting_date, self.company))
def validate_employee_attendance(self):
employees_to_mark_attendance = []
days_in_payroll, days_holiday, days_attendance_marked = 0, 0, 0
for employee_detail in self.employees:
days_holiday = self.get_count_holidays_of_employee(employee_detail.employee)
days_attendance_marked = self.get_count_employee_attendance(employee_detail.employee)
days_in_payroll = date_diff(self.end_date, self.start_date) + 1
if days_in_payroll > days_holiday + days_attendance_marked:
employees_to_mark_attendance.append({
"employee": employee_detail.employee,
"employee_name": employee_detail.employee_name
})
return employees_to_mark_attendance
def get_count_holidays_of_employee(self, employee):
holiday_list = get_holiday_list_for_employee(employee)
holidays = 0
if holiday_list:
days = frappe.db.sql("""select count(*) from tabHoliday where
parent=%s and holiday_date between %s and %s""", (holiday_list,
self.start_date, self.end_date))
if days and days[0][0]:
holidays = days[0][0]
return holidays
def get_count_employee_attendance(self, employee):
marked_days = 0
attendances = frappe.db.sql("""select count(*) from tabAttendance where
employee=%s and docstatus=1 and attendance_date between %s and %s""",
(employee, self.start_date, self.end_date))
if attendances and attendances[0][0]:
marked_days = attendances[0][0]
return marked_days
@frappe.whitelist()
def get_start_end_dates(payroll_frequency, start_date=None, company=None):
'''Returns dict of start and end dates for given payroll frequency based on start_date'''
if payroll_frequency == "Monthly" or payroll_frequency == "Bimonthly" or payroll_frequency == "":
fiscal_year = get_fiscal_year(start_date, company=company)[0]
month = "%02d" % getdate(start_date).month
m = get_month_details(fiscal_year, month)
if payroll_frequency == "Bimonthly":
if getdate(start_date).day <= 15:
start_date = m['month_start_date']
end_date = m['month_mid_end_date']
else:
start_date = m['month_mid_start_date']
end_date = m['month_end_date']
else:
start_date = m['month_start_date']
end_date = m['month_end_date']
if payroll_frequency == "Weekly":
end_date = add_days(start_date, 6)
if payroll_frequency == "Fortnightly":
end_date = add_days(start_date, 13)
if payroll_frequency == "Daily":
end_date = start_date
return frappe._dict({
'start_date': start_date, 'end_date': end_date
})
def get_frequency_kwargs(frequency_name):
frequency_dict = {
'monthly': {'months': 1},
'fortnightly': {'days': 14},
'weekly': {'days': 7},
'daily': {'days': 1}
}
return frequency_dict.get(frequency_name)
@frappe.whitelist()
def get_end_date(start_date, frequency):
start_date = getdate(start_date)
frequency = frequency.lower() if frequency else 'monthly'
kwargs = get_frequency_kwargs(frequency) if frequency != 'bimonthly' else get_frequency_kwargs('monthly')
# weekly, fortnightly and daily intervals have fixed days so no problems
end_date = add_to_date(start_date, **kwargs) - relativedelta(days=1)
if frequency != 'bimonthly':
return dict(end_date=end_date.strftime(DATE_FORMAT))
else:
return dict(end_date='')
def get_month_details(year, month):
ysd = frappe.db.get_value("Fiscal Year", year, "year_start_date")
if ysd:
import calendar, datetime
diff_mnt = cint(month)-cint(ysd.month)
if diff_mnt<0:
diff_mnt = 12-int(ysd.month)+cint(month)
msd = ysd + relativedelta(months=diff_mnt) # month start date
month_days = cint(calendar.monthrange(cint(msd.year) ,cint(month))[1]) # days in month
mid_start = datetime.date(msd.year, cint(month), 16) # month mid start date
mid_end = datetime.date(msd.year, cint(month), 15) # month mid end date
med = datetime.date(msd.year, cint(month), month_days) # month end date
return frappe._dict({
'year': msd.year,
'month_start_date': msd,
'month_end_date': med,
'month_mid_start_date': mid_start,
'month_mid_end_date': mid_end,
'month_days': month_days
})
else:
frappe.throw(_("Fiscal Year {0} not found").format(year))
def get_payroll_entry_bank_entries(payroll_entry_name):
journal_entries = frappe.db.sql(
'select name from `tabJournal Entry Account` '
'where reference_type="Payroll Entry" '
'and reference_name=%s and docstatus=1',
payroll_entry_name,
as_dict=1
)
return journal_entries
@frappe.whitelist()
def payroll_entry_has_bank_entries(name):
response = {}
bank_entries = get_payroll_entry_bank_entries(name)
response['submitted'] = 1 if bank_entries else 0
return response
def create_salary_slips_for_employees(employees, args, publish_progress=True):
salary_slips_exists_for = get_existing_salary_slips(employees, args)
count=0
for emp in employees:
if emp not in salary_slips_exists_for:
args.update({
"doctype": "Salary Slip",
"employee": emp
})
ss = frappe.get_doc(args)
ss.insert()
count+=1
if publish_progress:
frappe.publish_progress(count*100/len(set(employees) - set(salary_slips_exists_for)),
title = _("Creating Salary Slips..."))
payroll_entry = frappe.get_doc("Payroll Entry", args.payroll_entry)
payroll_entry.db_set("salary_slips_created", 1)
payroll_entry.notify_update()
def get_existing_salary_slips(employees, args):
return frappe.db.sql_list("""
select distinct employee from `tabSalary Slip`
where docstatus!= 2 and company = %s
and start_date >= %s and end_date <= %s
and employee in (%s)
""" % ('%s', '%s', '%s', ', '.join(['%s']*len(employees))),
[args.company, args.start_date, args.end_date] + employees)
def submit_salary_slips_for_employees(payroll_entry, salary_slips, publish_progress=True):
submitted_ss = []
not_submitted_ss = []
frappe.flags.via_payroll_entry = True
count = 0
for ss in salary_slips:
ss_obj = frappe.get_doc("Salary Slip",ss[0])
if ss_obj.net_pay<0:
not_submitted_ss.append(ss[0])
else:
try:
ss_obj.submit()
submitted_ss.append(ss_obj)
except frappe.ValidationError:
not_submitted_ss.append(ss[0])
count += 1
if publish_progress:
frappe.publish_progress(count*100/len(salary_slips), title = _("Submitting Salary Slips..."))
if submitted_ss:
payroll_entry.make_accrual_jv_entry()
frappe.msgprint(_("Salary Slip submitted for period from {0} to {1}")
.format(ss_obj.start_date, ss_obj.end_date))
payroll_entry.email_salary_slip(submitted_ss)
payroll_entry.db_set("salary_slips_submitted", 1)
payroll_entry.notify_update()
if not submitted_ss and not not_submitted_ss:
frappe.msgprint(_("No salary slip found to submit for the above selected criteria OR salary slip already submitted"))
if not_submitted_ss:
frappe.msgprint(_("Could not submit some Salary Slips"))
def get_payroll_entries_for_jv(doctype, txt, searchfield, start, page_len, filters):
return frappe.db.sql("""
select name from `tabPayroll Entry`
where `{key}` LIKE %(txt)s
and name not in
(select reference_name from `tabJournal Entry Account`
where reference_type="Payroll Entry")
order by name limit %(start)s, %(page_len)s"""
.format(key=searchfield), {
'txt': "%%%s%%" % frappe.db.escape(txt),
'start': start, 'page_len': page_len
})
| gpl-3.0 |
alvin777/excelsior | sort/benchmark.py | 1 | 2909 | #!/usr/bin/python
import time
from simple_sorts import *
from shell_sort import *
from quick_sort import *
from external_merge_sort import *
from radix_sort import *
from merge_sort import *
from heap_sort import *
from intro_sort import *
from timsort import *
from list_generators import *
result = {}
def run_until(sort_func, max_duration = 1.0, generator = random_generator):
print sort_func
duration = 0
list_size = 100
while duration < max_duration:
randomList = [x for x in generator(list_size)]
time_start = time.time()
try:
sort_func(randomList)
except RuntimeError:
print 'failed on list size: %5d' % list_size
return
duration = time.time() - time_start
print 'list size: %7d, duration: %0.3f' % (list_size, duration)
if not generator in result:
result[generator] = {}
if not list_size in result[generator]:
result[generator][list_size] = {}
result[generator][list_size][sort_func] = duration
list_size *= 2
def test_run_benchmarks():
generators_list = [random_generator, almost_sorted_generator, reverse_sorted_generator, few_uniq_generator]
# generators_list = [random_generator, reverse_sorted_generator]
# generators_list = [few_uniq_generator]
# sort_func_list = [bubble_sort, insertion_sort, insertion_sort2]
sort_func_list = [bubble_sort, insertion_sort, insertion_sort2, selection_sort, shell_sort, \
merge_sort, quick_sort, lambda x: quick_sort(x, splitByMedian), heap_sort,
lambda x: radix_sort(x, 1000), intro_sort, timsort]
# sort_func_list = [quick_sort, \
# lambda x: quick_sort(x, partition_func=splitByMiddleElement), \
# lambda x: quick_sort(x, partition_func=splitByMedian), \
# lambda x: quick_sort(x, leaf_sort_func=leaf_insertion_sort)]
# sort_func_list = [radix_sort, \
# lambda x: radix_sort(x, 2), \
# lambda x: radix_sort(x, 100),
# lambda x: radix_sort(x, 1000),
# lambda x: radix_sort(x, 10000)
# ]
for generator in generators_list:
print generator
for sort_func in sort_func_list:
run_until(sort_func, 0.5, generator)
for generator in generators_list:
print generator
for list_size in sorted(result[generator]):
sys.stdout.write(str(list_size) + "\t")
for sort_func in sort_func_list:
if sort_func in result[generator][list_size]:
sys.stdout.write("{:.3f}\t".format(result[generator][list_size][sort_func]))
else:
sys.stdout.write("\t")
sys.stdout.write("\n")
test_run_benchmarks() | gpl-2.0 |
n0trax/ansible | lib/ansible/plugins/action/telnet.py | 29 | 3084 | # (c) 2017, Ansible Project
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import telnetlib
from time import sleep
from ansible.module_utils._text import to_native
from ansible.module_utils.six import text_type
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
TRANSFERS_FILES = False
def run(self, tmp=None, task_vars=None):
if self._task.environment and any(self._task.environment):
self._display.warning('The telnet task does not support the environment keyword')
result = super(ActionModule, self).run(tmp, task_vars)
if self._play_context.check_mode:
# in --check mode, always skip this module execution
result['skipped'] = True
result['msg'] = 'The telnet task does not support check mode'
else:
result['changed'] = True
result['failed'] = False
host = self._task.args.get('host', self._play_context.remote_addr)
user = self._task.args.get('user', self._play_context.remote_user)
password = self._task.args.get('password', self._play_context.password)
# FIXME, default to play_context?
port = self._task.args.get('port', '23')
timeout = self._task.args.get('timeout', 120)
pause = self._task.args.get('pause', 1)
login_prompt = self._task.args.get('login_prompt', "login: ")
password_prompt = self._task.args.get('password_prompt', "Password: ")
prompts = self._task.args.get('prompts', "$ ")
commands = self._task.args.get('command') or self._task.args.get('commands')
if isinstance(commands, text_type):
commands = commands.split(',')
if isinstance(commands, list) and commands:
tn = telnetlib.Telnet(host, port, timeout)
output = []
try:
tn.read_until(login_prompt)
tn.write('%s\n' % to_native(user))
if password:
tn.read_until(password_prompt)
tn.write('%s\n' % to_native(password))
tn.expect(prompts)
for cmd in commands:
tn.write('%s\n' % to_native(cmd))
index, match, out = tn.expect(prompts)
output.append(out)
sleep(pause)
tn.write("exit\n")
except EOFError as e:
result['failed'] = True
result['msg'] = 'Telnet action failed: %s' % to_native(e)
finally:
if tn:
tn.close()
result['output'] = output
else:
result['failed'] = True
result['msg'] = 'Telnet requires a command to execute'
return result
| gpl-3.0 |
chouseknecht/ansible | lib/ansible/modules/network/fortios/fortios_log_null_device_setting.py | 14 | 8723 | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, 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 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 <https://www.gnu.org/licenses/>.
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
DOCUMENTATION = '''
---
module: fortios_log_null_device_setting
short_description: Settings for null device logging in Fortinet's FortiOS and FortiGate.
description:
- This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
user to set and modify log_null_device feature and setting category.
Examples include all parameters and values need to be adjusted to datasources before usage.
Tested with FOS v6.0.5
version_added: "2.8"
author:
- Miguel Angel Munoz (@mamunozgonzalez)
- Nicolas Thomas (@thomnico)
notes:
- Requires fortiosapi library developed by Fortinet
- Run as a local_action in your playbook
requirements:
- fortiosapi>=0.9.8
options:
host:
description:
- FortiOS or FortiGate IP address.
type: str
required: false
username:
description:
- FortiOS or FortiGate username.
type: str
required: false
password:
description:
- FortiOS or FortiGate password.
type: str
default: ""
vdom:
description:
- Virtual domain, among those defined previously. A vdom is a
virtual instance of the FortiGate that can be configured and
used as a different unit.
type: str
default: root
https:
description:
- Indicates if the requests towards FortiGate must use HTTPS protocol.
type: bool
default: true
ssl_verify:
description:
- Ensures FortiGate certificate must be verified by a proper CA.
type: bool
default: true
version_added: 2.9
log_null_device_setting:
description:
- Settings for null device logging.
default: null
type: dict
suboptions:
status:
description:
- Enable/disable statistics collection for when no external logging destination, such as FortiAnalyzer, is present (data is not saved).
type: str
choices:
- enable
- disable
'''
EXAMPLES = '''
- hosts: localhost
vars:
host: "192.168.122.40"
username: "admin"
password: ""
vdom: "root"
ssl_verify: "False"
tasks:
- name: Settings for null device logging.
fortios_log_null_device_setting:
host: "{{ host }}"
username: "{{ username }}"
password: "{{ password }}"
vdom: "{{ vdom }}"
https: "False"
log_null_device_setting:
status: "enable"
'''
RETURN = '''
build:
description: Build number of the fortigate image
returned: always
type: str
sample: '1547'
http_method:
description: Last method used to provision the content into FortiGate
returned: always
type: str
sample: 'PUT'
http_status:
description: Last result given by FortiGate on last operation applied
returned: always
type: str
sample: "200"
mkey:
description: Master key (id) used in the last call to FortiGate
returned: success
type: str
sample: "id"
name:
description: Name of the table used to fulfill the request
returned: always
type: str
sample: "urlfilter"
path:
description: Path of the table used to fulfill the request
returned: always
type: str
sample: "webfilter"
revision:
description: Internal revision number
returned: always
type: str
sample: "17.0.2.10658"
serial:
description: Serial number of the unit
returned: always
type: str
sample: "FGVMEVYYQT3AB5352"
status:
description: Indication of the operation's result
returned: always
type: str
sample: "success"
vdom:
description: Virtual domain used
returned: always
type: str
sample: "root"
version:
description: Version of the FortiGate
returned: always
type: str
sample: "v5.6.3"
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.connection import Connection
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG
def login(data, fos):
host = data['host']
username = data['username']
password = data['password']
ssl_verify = data['ssl_verify']
fos.debug('on')
if 'https' in data and not data['https']:
fos.https('off')
else:
fos.https('on')
fos.login(host, username, password, verify=ssl_verify)
def filter_log_null_device_setting_data(json):
option_list = ['status']
dictionary = {}
for attribute in option_list:
if attribute in json and json[attribute] is not None:
dictionary[attribute] = json[attribute]
return dictionary
def underscore_to_hyphen(data):
if isinstance(data, list):
for elem in data:
elem = underscore_to_hyphen(elem)
elif isinstance(data, dict):
new_data = {}
for k, v in data.items():
new_data[k.replace('_', '-')] = underscore_to_hyphen(v)
data = new_data
return data
def log_null_device_setting(data, fos):
vdom = data['vdom']
log_null_device_setting_data = data['log_null_device_setting']
filtered_data = underscore_to_hyphen(filter_log_null_device_setting_data(log_null_device_setting_data))
return fos.set('log.null-device',
'setting',
data=filtered_data,
vdom=vdom)
def is_successful_status(status):
return status['status'] == "success" or \
status['http_method'] == "DELETE" and status['http_status'] == 404
def fortios_log_null_device(data, fos):
if data['log_null_device_setting']:
resp = log_null_device_setting(data, fos)
return not is_successful_status(resp), \
resp['status'] == "success", \
resp
def main():
fields = {
"host": {"required": False, "type": "str"},
"username": {"required": False, "type": "str"},
"password": {"required": False, "type": "str", "default": "", "no_log": True},
"vdom": {"required": False, "type": "str", "default": "root"},
"https": {"required": False, "type": "bool", "default": True},
"ssl_verify": {"required": False, "type": "bool", "default": True},
"log_null_device_setting": {
"required": False, "type": "dict", "default": None,
"options": {
"status": {"required": False, "type": "str",
"choices": ["enable", "disable"]}
}
}
}
module = AnsibleModule(argument_spec=fields,
supports_check_mode=False)
# legacy_mode refers to using fortiosapi instead of HTTPAPI
legacy_mode = 'host' in module.params and module.params['host'] is not None and \
'username' in module.params and module.params['username'] is not None and \
'password' in module.params and module.params['password'] is not None
if not legacy_mode:
if module._socket_path:
connection = Connection(module._socket_path)
fos = FortiOSHandler(connection)
is_error, has_changed, result = fortios_log_null_device(module.params, fos)
else:
module.fail_json(**FAIL_SOCKET_MSG)
else:
try:
from fortiosapi import FortiOSAPI
except ImportError:
module.fail_json(msg="fortiosapi module is required")
fos = FortiOSAPI()
login(module.params, fos)
is_error, has_changed, result = fortios_log_null_device(module.params, fos)
fos.logout()
if not is_error:
module.exit_json(changed=has_changed, meta=result)
else:
module.fail_json(msg="Error in repo", meta=result)
if __name__ == '__main__':
main()
| gpl-3.0 |
amitdhiman000/MyOffers | myadmin/views.py | 1 | 7396 | from myadmin.backenddb import (insert_default_areas, insert_custom_areas, insert_default_categories)
from offer.models import CategoryModel
from locus.models import (CountryModel ,StateModel, CityModel, AreaModel)
from mail.models import (PublicMessageModel)
from myadmin.preload_data import (gCountries, gCategories)
from base.apputil import (App_AdminRequired, App_Render)
# Create your views here.
@App_AdminRequired
def home(request):
data = {'title': 'MyAdmin'}
return App_Render(request, 'admin/admin_home_1.html', data)
@App_AdminRequired
def locus_area_view(request, country, state, city, area):
print(area)
areas = AreaModel.fetch_by_name(area, city, state, country)
data = {'title': 'MyAdmin', 'country': country, 'state': state, 'city': city, 'area': area, 'areas': areas}
return App_Render(request, 'admin/admin_locus_area_1.html', data)
@App_AdminRequired
def locus_city_view(request, country, state, city):
print(city)
filter = {'fk_city__name': city, 'fk_state__name': state, 'fk_country__name': country}
areas = AreaModel.fetch(filter)
data = {'title': 'MyAdmin', 'country': country, 'state': state, 'city': city, 'areas': areas}
return App_Render(request, 'admin/admin_locus_city_1.html', data)
@App_AdminRequired
def locus_state_view(request, country, state):
print(state)
filter = {'fk_state__name': state, 'fk_country__name': country}
cities = CityModel.fetch(filter)
data = {'title': 'MyAdmin', 'country': country, 'state': state, 'cities': cities}
return App_Render(request, 'admin/admin_locus_state_1.html', data)
@App_AdminRequired
def locus_country_view(request, country):
print(country)
states = StateModel.fetch({'fk_country__name': country})
data = {'title': 'MyAdmin', 'country': country, 'states': states}
return App_Render(request, 'admin/admin_locus_country_1.html', data)
@App_AdminRequired
def locus_view0(request):
countries = CountryModel.fetch_all()
states = StateModel.fetch({'fk_country__name': 'India'})
data = {'title': 'MyAdmin', 'countries': countries, 'states': states}
return App_Render(request, 'admin/admin_locus_view_1.html', data)
@App_AdminRequired
def locus_view(request, query=''):
print('query : '+query)
params = query.rstrip('/').split('/')
length = len(params)
print(params)
print('length : '+str(length))
if length == 1 and params[0] != '':
return locus_country_view(request, params[0])
elif length == 2:
return locus_state_view(request, params[0], params[1])
elif length == 3:
return locus_city_view(request, params[0], params[1], params[2])
elif length == 4:
return locus_area_view(request, params[0], params[1], params[2], params[3])
return locus_view0(request)
@App_AdminRequired
def locus_country_add_view(request, country):
states = {}
if country in gCountries:
states = gCountries[country]
data = {'title': 'MyAdmin', 'country': country, 'states': states}
return App_Render(request, 'admin/admin_locus_country_add_1.html', data)
@App_AdminRequired
def locus_add_view0(request):
countries = list(gCountries.keys())
data = {'title': 'MyAdmin', 'countries': countries}
return App_Render(request, 'admin/admin_locus_add_1.html', data)
@App_AdminRequired
def locus_add_view(request, query=''):
print('query : '+query)
params = query.rstrip('/').split('/')
length = len(params)
print(params)
print('length : '+str(length))
if length == 1 and params[0] != '':
return locus_country_add_view(request, params[0])
elif length == 2:
return locus_state_add_view(request, params[0], params[1])
elif length == 3:
return locus_city_add_view(request, params[0], params[1], params[2])
elif length == 4:
return locus_area_add_view(request, params[0], params[1], params[2], params[3])
return locus_add_view0(request)
@App_AdminRequired
def locus_auth(request, query=''):
print('query : '+query)
params = query.rstrip('/').split('/')
length = len(params)
print(params)
print('length : '+str(length))
if length < 3:
return None
country = params[0]
state = params[1]
city = params[2]
print(country, state, city)
if CityModel.fetch_by_name(city_name=city, state_name=state, country_name=country) is None:
insert_custom_areas(city, state, country)
areas = AreaModel.fetch_by_city(city)
data = {'title': 'Location', 'country': country, 'state': state, 'city': city, 'areas': areas}
return App_Render(request, 'admin/admin_locus_added_1.html', data)
@App_AdminRequired
def category_view(request, query=''):
print('query : '+query)
params = query.rstrip('/').split('/')
length = len(params)
print(params)
print('length : '+str(length))
name = "All"
if length > 0 and params[0] != '':
name = params[length - 1]
categories = CategoryModel.fetch_children(name)
data = {'title': 'MyAdmin', 'categories': categories}
return App_Render(request, 'admin/admin_category_1.html', data)
@App_AdminRequired
def category_add_view0(request):
base_cat = gCategories[0]['sub']
print(len(base_cat))
data = {'title': 'MyAdmin', 'categories': base_cat}
return App_Render(request, 'admin/admin_category_add_1.html', data)
@App_AdminRequired
def category_add_view1(request, params, length):
print(request)
index = 0
cat_list = gCategories
while index < length:
for cat in cat_list:
if cat['name'] == params[index]:
if 'sub' in cat:
cat_list = cat['sub']
else:
print('No more subcategories, jump to root')
cat_list = cat
index = length
break
index = index + 1
nav_links = []
url = '/myadmin/category-add/'
for param in params:
print('param : '+param)
url += param + "/"
nav_links.append({'text': param, 'href': url})
data = {}
if type(cat_list) is list:
categories = []
desired_attrs = ['name', 'desc']
for cat in cat_list:
categories.append({ key: value for key,value in cat.items() if key in desired_attrs })
print(len(categories))
print(categories)
data.update({'categories': categories})
else:
data.update({'category': cat_list})
data.update({'title': 'Add Category | MyAdmin', 'nav_links': nav_links, })
return App_Render(request, 'admin/admin_category_add_1.html', data)
@App_AdminRequired
def category_add(request, params):
insert_default_categories()
@App_AdminRequired
def category_add_view(request, query):
print('query : '+query)
params = query.rstrip('/').split('/')
length = len(params)
print(params)
print('length : '+str(length))
command = request.GET.get('command', '')
if command == 'Add':
category_add(request, params)
if params[0] == '':
params[0] = 'All';
return category_add_view1(request, params, length)
@App_AdminRequired
def messages_view(request):
print('chaum executing this')
messages = PublicMessageModel.fetch_all()
data = {'title': 'Messages', 'messages': messages}
return App_Render(request, 'admin/admin_message_1.html', data)
| apache-2.0 |
uqyge/combustionML | FPV_ANN_pureResNet/data_reader_2.py | 1 | 5981 | import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler, StandardScaler
class data_scaler(object):
def __init__(self):
self.norm = None
self.norm_1 = None
self.std = None
self.case = None
self.scale = 1
self.bias = 1e-20
# self.bias = 1
self.switcher = {
'min_std': 'min_std',
'std2': 'std2',
'std_min': 'std_min',
'min': 'min',
'no': 'no',
'log': 'log',
'log_min': 'log_min',
'log2': 'log2',
'tan': 'tan'
}
def fit_transform(self, input_data, case):
self.case = case
if self.switcher.get(self.case) == 'min_std':
self.norm = MinMaxScaler()
self.std = StandardScaler()
out = self.norm.fit_transform(input_data)
out = self.std.fit_transform(out)
if self.switcher.get(self.case) == 'std2':
self.std = StandardScaler()
out = self.std.fit_transform(input_data)
if self.switcher.get(self.case) == 'std_min':
self.norm = MinMaxScaler()
self.std = StandardScaler()
out = self.std.fit_transform(input_data)
out = self.norm.fit_transform(out)
if self.switcher.get(self.case) == 'min':
self.norm = MinMaxScaler()
out = self.norm.fit_transform(input_data)
if self.switcher.get(self.case) == 'no':
self.norm = MinMaxScaler()
self.std = StandardScaler()
out = input_data
if self.switcher.get(self.case) == 'log':
out = - np.log(np.asarray(input_data / self.scale) + self.bias)
self.std = StandardScaler()
out = self.std.fit_transform(out)
if self.switcher.get(self.case) == 'log_min':
out = - np.log(np.asarray(input_data / self.scale) + self.bias)
self.norm = MinMaxScaler()
out = self.norm.fit_transform(out)
if self.switcher.get(self.case) == 'log2':
self.norm = MinMaxScaler()
self.norm_1 = MinMaxScaler()
out = self.norm.fit_transform(input_data)
out = np.log(np.asarray(out) + self.bias)
out = self.norm_1.fit_transform(out)
if self.switcher.get(self.case) == 'tan':
self.norm = MaxAbsScaler()
self.std = StandardScaler()
out = self.std.fit_transform(input_data)
out = self.norm.fit_transform(out)
out = np.tan(out / (2 * np.pi + self.bias))
return out
def transform(self, input_data):
if self.switcher.get(self.case) == 'min_std':
out = self.norm.transform(input_data)
out = self.std.transform(out)
if self.switcher.get(self.case) == 'std2':
out = self.std.transform(input_data)
if self.switcher.get(self.case) == 'std_min':
out = self.std.transform(input_data)
out = self.norm.transform(out)
if self.switcher.get(self.case) == 'min':
out = self.norm.transform(input_data)
if self.switcher.get(self.case) == 'no':
out = input_data
if self.switcher.get(self.case) == 'log':
out = - np.log(np.asarray(input_data / self.scale) + self.bias)
out = self.std.transform(out)
if self.switcher.get(self.case) == 'log_min':
out = - np.log(np.asarray(input_data / self.scale) + self.bias)
out = self.norm.transform(out)
if self.switcher.get(self.case) == 'log2':
out = self.norm.transform(input_data)
out = np.log(np.asarray(out) + self.bias)
out = self.norm_1.transform(out)
if self.switcher.get(self.case) == 'tan':
out = self.std.transform(input_data)
out = self.norm.transform(out)
out = np.tan(out / (2 * np.pi + self.bias))
return out
def inverse_transform(self, input_data):
if self.switcher.get(self.case) == 'min_std':
out = self.std.inverse_transform(input_data)
out = self.norm.inverse_transform(out)
if self.switcher.get(self.case) == 'std2':
out = self.std.inverse_transform(input_data)
if self.switcher.get(self.case) == 'std_min':
out = self.norm.inverse_transform(input_data)
out = self.std.inverse_transform(out)
if self.switcher.get(self.case) == 'min':
out = self.norm.inverse_transform(input_data)
if self.switcher.get(self.case) == 'no':
out = input_data
if self.switcher.get(self.case) == 'log':
out = self.std.inverse_transform(input_data)
out = (np.exp(-out) - self.bias) * self.scale
if self.switcher.get(self.case) == 'log_min':
out = self.norm.inverse_transform(input_data)
out = (np.exp(-out) - self.bias) * self.scale
if self.switcher.get(self.case) == 'log2':
out = self.norm_1.inverse_transform(input_data)
out = np.exp(out) - self.bias
out = self.norm.inverse_transform(out)
if self.switcher.get(self.case) == 'tan':
out = (2 * np.pi + self.bias) * np.arctan(input_data)
out = self.norm.inverse_transform(out)
out = self.std.inverse_transform(out)
return out
def read_h5_data(fileName, input_features, labels):
df = pd.read_hdf(fileName)
df = df[df['f'] < 0.45]
input_df = df[input_features]
in_scaler = data_scaler()
input_np = in_scaler.fit_transform(input_df.values, 'no')
label_df = df[labels].clip(0)
# if 'PVs' in labels:
# label_df['PVs']=np.log(label_df['PVs']+1)
out_scaler = data_scaler()
label_np = out_scaler.fit_transform(label_df.values, 'std2')
return input_np, label_np, df, in_scaler, out_scaler | mit |
BaluDontu/docker-volume-vsphere | esx_service/vsan_policy_test.py | 1 | 2572 | # Copyright 2016 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import os, os.path
import vsan_policy
import vmdk_utils
import volume_kv
import vsan_info
class TestVsanPolicy(unittest.TestCase):
""" Test VSAN Policy code """
@unittest.skipIf(not vsan_info.get_vsan_datastore(),
"VSAN is not found - skipping vsan_info tests")
def setUp(self):
self.policy_path = os.path.join(vsan_info.get_vsan_dockvols_path(),
'policies/test_policy')
self.name = 'test_policy'
self.content = ('(("proportionalCapacity" i50) '
'("hostFailuresToTolerate" i0))')
def tearDown(self):
try:
os.remove(self.policy_path)
except:
pass
def assertPoliciesEqual(self):
with open(self.policy_path) as f:
content = f.read()
# Remove the added newline
self.assertEqual(content[:-1], self.content)
def test_create(self):
self.assertEqual(None, vsan_policy.create(self.name, self.content))
self.assertPoliciesEqual()
def test_double_create_fails(self):
self.assertEqual(None, vsan_policy.create(self.name, self.content))
self.assertNotEqual(None, vsan_policy.create(self.name, self.content))
self.assertPoliciesEqual()
def test_create_delete(self):
self.assertEqual(None, vsan_policy.create(self.name, self.content))
self.assertPoliciesEqual()
self.assertEqual(None, vsan_policy.delete(self.name))
self.assertFalse(os.path.isfile(self.policy_path))
def test_delete_nonexistent_policy_fails(self):
self.assertNotEqual(None, vsan_policy.delete(self.name))
def test_create_list(self):
self.assertEqual(None, vsan_policy.create(self.name, self.content))
policies = vsan_policy.get_policies()
self.assertTrue(self.content + '\n', policies[self.name])
if __name__ == '__main__':
volume_kv.init()
unittest.main()
| apache-2.0 |
jeffzheng1/tensorflow | tensorflow/python/kernel_tests/template_test.py | 6 | 9746 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for make_template."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import traceback
import tensorflow as tf
from tensorflow.python.ops import template
def var_scoped_function():
return tf.get_variable("dummy",
shape=[1],
initializer=tf.zeros_initializer)
def internally_var_scoped_function(scope_name):
with tf.variable_scope(scope_name):
return tf.get_variable("dummy",
shape=[1],
initializer=tf.zeros_initializer)
def function_with_create(trainable):
"""Creates a variable as a side effect using tf.Variable."""
tf.Variable(0, trainable=trainable)
return tf.get_variable("dummy",
shape=[1],
initializer=tf.zeros_initializer)
class TemplateTest(tf.test.TestCase):
def test_end_to_end(self):
"""This test shows a very simple line model with test_loss.
The template is used to share parameters between a training and test model.
"""
# y = 2x + 1
training_input, training_output = ([1., 2., 3., 4.], [2.8, 5.1, 7.2, 8.7])
test_input, test_output = ([5., 6., 7., 8.], [11, 13, 15, 17])
tf.set_random_seed(1234)
def test_line(x):
m = tf.get_variable("w", shape=[],
initializer=tf.truncated_normal_initializer())
b = tf.get_variable("b", shape=[],
initializer=tf.truncated_normal_initializer())
return x * m + b
line_template = template.make_template("line", test_line)
train_prediction = line_template(training_input)
test_prediction = line_template(test_input)
train_loss = tf.reduce_mean(tf.square(train_prediction - training_output))
test_loss = tf.reduce_mean(tf.square(test_prediction - test_output))
optimizer = tf.train.GradientDescentOptimizer(0.1)
train_op = optimizer.minimize(train_loss)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
initial_test_loss = sess.run(test_loss)
sess.run(train_op)
final_test_loss = sess.run(test_loss)
# Parameters are tied, so the loss should have gone down when we trained it.
self.assertLess(final_test_loss, initial_test_loss)
def test_skip_stack_frames(self):
first = traceback.format_stack()
second = traceback.format_stack()
result = template._skip_common_stack_elements(first, second)
self.assertEqual(1, len(result))
self.assertNotEqual(len(first), len(result))
def test_template_with_name(self):
tmpl1 = template.make_template("s1", var_scoped_function)
tmpl2 = template.make_template("s1", var_scoped_function)
v1 = tmpl1()
v2 = tmpl1()
v3 = tmpl2()
self.assertEqual(v1, v2)
self.assertNotEqual(v1, v3)
self.assertEqual("s1/dummy:0", v1.name)
self.assertEqual("s1_1/dummy:0", v3.name)
def test_unique_name_raise_error(self):
tmpl1 = template.make_template("_", var_scoped_function, unique_name_="s1")
tmpl1()
tmpl2 = template.make_template("_", var_scoped_function, unique_name_="s1")
with self.assertRaises(ValueError):
tmpl2()
def test_unique_name_and_reuse(self):
tmpl1 = template.make_template("_", var_scoped_function, unique_name_="s1")
v1 = tmpl1()
v2 = tmpl1()
tf.get_variable_scope().reuse_variables()
tmpl2 = template.make_template("_", var_scoped_function, unique_name_="s1")
v3 = tmpl2()
self.assertEqual(v1, v2)
self.assertEqual(v1, v3)
self.assertEqual("s1/dummy:0", v1.name)
def test_template_in_scope(self):
tmpl1 = template.make_template("s1", var_scoped_function)
tmpl2 = template.make_template("s1", var_scoped_function)
with tf.variable_scope("scope"):
v1 = tmpl1()
v3 = tmpl2()
# The template contract requires the following to ignore scope2.
with tf.variable_scope("scope2"):
v2 = tmpl1()
self.assertEqual(v1, v2)
self.assertNotEqual(v1, v3)
self.assertEqual("scope/s1/dummy:0", v1.name)
self.assertEqual("scope/s1_1/dummy:0", v3.name)
def test_template_with_internal_reuse(self):
tmpl1 = template.make_template("s1", internally_var_scoped_function)
tmpl2 = template.make_template("s1", internally_var_scoped_function)
v1 = tmpl1("test")
v2 = tmpl1("test")
v3 = tmpl2("test")
self.assertEqual(v1, v2)
self.assertNotEqual(v1, v3)
self.assertEqual("s1/test/dummy:0", v1.name)
self.assertEqual("s1_1/test/dummy:0", v3.name)
with self.assertRaises(ValueError):
tmpl1("not_test")
def test_template_without_name(self):
with self.assertRaises(ValueError):
template.make_template(None, var_scoped_function)
def test_make_template(self):
# Test both that we can call it with positional and keywords.
tmpl1 = template.make_template(
"s1", internally_var_scoped_function, scope_name="test")
tmpl2 = template.make_template(
"s1", internally_var_scoped_function, scope_name="test")
v1 = tmpl1()
v2 = tmpl1()
v3 = tmpl2()
self.assertEqual(v1, v2)
self.assertNotEqual(v1, v3)
self.assertEqual("s1/test/dummy:0", v1.name)
self.assertEqual("s1_1/test/dummy:0", v3.name)
def test_enforces_no_extra_trainable_variables(self):
tmpl = template.make_template("s", function_with_create, trainable=True)
tmpl()
with self.assertRaises(ValueError):
tmpl()
def test_permits_extra_non_trainable_variables(self):
tmpl = template.make_template("s", function_with_create, trainable=False)
self.assertEqual(tmpl(), tmpl())
def test_internal_variable_reuse(self):
def nested():
with tf.variable_scope("nested") as vs:
v1 = tf.get_variable("x", initializer=tf.zeros_initializer, shape=[])
with tf.variable_scope(vs, reuse=True):
v2 = tf.get_variable("x")
self.assertEqual(v1, v2)
return v1
tmpl1 = template.make_template("s1", nested)
tmpl2 = template.make_template("s1", nested)
v1 = tmpl1()
v2 = tmpl1()
v3 = tmpl2()
self.assertEqual(v1, v2)
self.assertNotEqual(v1, v3)
self.assertEqual("s1/nested/x:0", v1.name)
self.assertEqual("s1_1/nested/x:0", v3.name)
def test_nested_templates(self):
def nested_template():
nested1 = template.make_template("nested", var_scoped_function)
nested2 = template.make_template("nested", var_scoped_function)
v1 = nested1()
v2 = nested2()
self.assertNotEqual(v1, v2)
return v2
tmpl1 = template.make_template("s1", nested_template)
tmpl2 = template.make_template("s1", nested_template)
v1 = tmpl1()
v2 = tmpl1()
v3 = tmpl2()
self.assertEqual(v1, v2)
self.assertNotEqual(v1, v3)
self.assertEqual("s1/nested_1/dummy:0", v1.name)
self.assertEqual("s1_1/nested_1/dummy:0", v3.name)
def test_immediate_scope_creation(self):
# Create templates in scope a then call in scope b. make_template should
# capture the scope the first time it is called, and make_immediate_template
# should capture the scope at construction time.
with tf.variable_scope("ctor_scope"):
tmpl_immed = template.make_template(
"a", var_scoped_function, True) # create scope here
tmpl_defer = template.make_template(
"b", var_scoped_function, False) # default: create scope at __call__
with tf.variable_scope("call_scope"):
inner_imm_var = tmpl_immed()
inner_defer_var = tmpl_defer()
outer_imm_var = tmpl_immed()
outer_defer_var = tmpl_defer()
self.assertNotEqual(inner_imm_var, inner_defer_var)
self.assertEqual(outer_imm_var, inner_imm_var)
self.assertEqual(outer_defer_var, inner_defer_var)
self.assertEqual("ctor_scope/a/dummy:0", inner_imm_var.name)
self.assertEqual("call_scope/b/dummy:0", inner_defer_var.name)
def test_scope_access(self):
# Ensure that we can access the scope inside the template, because the name
# of that scope may be different from the name we pass to make_template, due
# to having been made unique by variable_scope.
with tf.variable_scope("foo"):
# Create two templates with the same name, ensure scopes are made unique.
ta = template.make_template("bar", var_scoped_function, True)
tb = template.make_template("bar", var_scoped_function, True)
# Ensure we can get the scopes before either template is actually called.
self.assertEqual(ta.var_scope.name, "foo/bar")
self.assertEqual(tb.var_scope.name, "foo/bar_1")
with tf.variable_scope("foo_2"):
# Create a template which defers scope creation.
tc = template.make_template("blah", var_scoped_function, False)
# Before we call the template, the scope property will be set to None.
self.assertEqual(tc.var_scope, None)
tc()
# Template is called at the top level, so there is no preceding "foo_2".
self.assertEqual(tc.var_scope.name, "blah")
if __name__ == "__main__":
tf.test.main()
| apache-2.0 |
xunmengfeng/engine | build/android/pylib/base/test_run_factory.py | 45 | 2028 | # 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.
from pylib.gtest import gtest_test_instance
from pylib.gtest import local_device_gtest_run
from pylib.instrumentation import instrumentation_test_instance
from pylib.local.device import local_device_environment
from pylib.local.device import local_device_instrumentation_test_run
from pylib.remote.device import remote_device_environment
from pylib.remote.device import remote_device_gtest_run
from pylib.remote.device import remote_device_instrumentation_test_run
from pylib.remote.device import remote_device_uirobot_test_run
from pylib.uirobot import uirobot_test_instance
def CreateTestRun(_args, env, test_instance, error_func):
if isinstance(env, local_device_environment.LocalDeviceEnvironment):
if isinstance(test_instance, gtest_test_instance.GtestTestInstance):
return local_device_gtest_run.LocalDeviceGtestRun(env, test_instance)
if isinstance(test_instance,
instrumentation_test_instance.InstrumentationTestInstance):
return (local_device_instrumentation_test_run
.LocalDeviceInstrumentationTestRun(env, test_instance))
if isinstance(env, remote_device_environment.RemoteDeviceEnvironment):
if isinstance(test_instance, gtest_test_instance.GtestTestInstance):
return remote_device_gtest_run.RemoteDeviceGtestTestRun(
env, test_instance)
if isinstance(test_instance,
instrumentation_test_instance.InstrumentationTestInstance):
return (remote_device_instrumentation_test_run
.RemoteDeviceInstrumentationTestRun(env, test_instance))
if isinstance(test_instance, uirobot_test_instance.UirobotTestInstance):
return remote_device_uirobot_test_run.RemoteDeviceUirobotTestRun(
env, test_instance)
error_func('Unable to create test run for %s tests in %s environment'
% (str(test_instance), str(env)))
| bsd-3-clause |
tsgit/invenio | modules/miscutil/lib/upgrades/invenio_2014_01_22_queue_table_virtual_index.py | 16 | 2740 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2012, 2013, 2014 CERN.
##
## Invenio 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.
##
## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
from invenio.dbquery import run_sql
depends_on = ['invenio_2013_09_30_indexer_interface']
def info():
return "New queue tables for virtual indexes: idxWORD/PAIR/PHRASExxQ"
def do_upgrade():
global_id = 1
run_sql("""CREATE TABLE IF NOT EXISTS idxWORD%02dQ (
id mediumint(10) unsigned NOT NULL auto_increment,
runtime datetime NOT NULL default '0000-00-00 00:00:00',
id_bibrec_low mediumint(9) unsigned NOT NULL,
id_bibrec_high mediumint(9) unsigned NOT NULL,
index_name varchar(50) NOT NULL default '',
mode varchar(50) NOT NULL default 'update',
PRIMARY KEY (id),
INDEX (index_name),
INDEX (runtime)
) ENGINE=MyISAM;""" % global_id)
run_sql("""CREATE TABLE IF NOT EXISTS idxPAIR%02dQ (
id mediumint(10) unsigned NOT NULL auto_increment,
runtime datetime NOT NULL default '0000-00-00 00:00:00',
id_bibrec_low mediumint(9) unsigned NOT NULL,
id_bibrec_high mediumint(9) unsigned NOT NULL,
index_name varchar(50) NOT NULL default '',
mode varchar(50) NOT NULL default 'update',
PRIMARY KEY (id),
INDEX (index_name),
INDEX (runtime)
) ENGINE=MyISAM;""" % global_id)
run_sql("""CREATE TABLE IF NOT EXISTS idxPHRASE%02dQ (
id mediumint(10) unsigned NOT NULL auto_increment,
runtime datetime NOT NULL default '0000-00-00 00:00:00',
id_bibrec_low mediumint(9) unsigned NOT NULL,
id_bibrec_high mediumint(9) unsigned NOT NULL,
index_name varchar(50) NOT NULL default '',
mode varchar(50) NOT NULL default 'update',
PRIMARY KEY (id),
INDEX (index_name),
INDEX (runtime)
) ENGINE=MyISAM;""" % global_id)
def estimate():
return 1
def pre_upgrade():
pass
def post_upgrade():
print "NOTE: If you plan to change some of your indexes " \
"to virtual type, please note that you need to run " \
"new separate bibindex process for them"
| gpl-2.0 |
informatik-mannheim/Moduro-CC3D | Simulation/Logger/ArrangementFitnessSteppable.py | 1 | 5298 | # Copyright 2016 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
__author__ = "Angelo Torelli, Markus Gumbel"
__copyright__ = "The authors"
__license__ = "Apache 2"
__email__ = "m.gumbel@hs-mannheim.de"
__status__ = "Production"
from Logger.TissueFitnessSteppable import TissueFitnessSteppable
class ArrangementFitnessSteppable(TissueFitnessSteppable):
def __init__(self, simulator, model, _frequency=1):
TissueFitnessSteppable.__init__(self, simulator, model,
"FitnessArrangement.dat", _frequency)
# step is overwritten
# TODO sizes do not scale yet!
def step(self, mcs):
if self.execConfig.interuptMCS(mcs):
deltaXPx = self.execConfig.calcPixelFromMuMeterMin1(20) # 20 mu m.
deltaZPx = deltaXPx
sumFitness_a = []
avgStemCellDiameterPx = \
self.execConfig.calcPixelFromMuMeterMin1(self.model.cellTypes[2].getAvgDiameter())
zRange = [0] if self.execConfig.zDimension == 1 else range(0, self.execConfig.zDimension, deltaZPx)
for z in zRange:
for x in xrange(1, self.execConfig.xDimension, deltaXPx):
cells_in_order = []
for y in xrange(3, self.execConfig.yDimension, int(avgStemCellDiameterPx / 2)):
# Gives the mode of a cell ID in a 3x3x3 pixels cube if 3D otherwise 3x3 rectangle
mode_of_cellIDs = []
for width in xrange(0, 2, 1):
for height in xrange(0, 2, 1):
depthRange = [0] if zRange.__len__() == 1 else range(0, 2, 1)
for depth in depthRange:
if self.cellField[x + width, y + height, z + depth] is not None:
mode_of_cellIDs.append(self.cellField[x + width, y + height, z + depth].id)
# If mode ID exists and in not already in cell_in_order list it will be added
if len(mode_of_cellIDs) > 0:
cellToCheck = self.attemptFetchingCellById(self.mode(mode_of_cellIDs))
exist = False
for cell in cells_in_order:
if cellToCheck.id == cell.id:
exist = True
if not exist:
cells_in_order.append(cellToCheck)
layers = len(cells_in_order)
if layers == 0:
fitness_a = 0
else:
optimumLayers = 1 if layers <= 7 and layers >= 3 else 0
if cells_in_order[layers - 1].type == self.UMBRELLA:
lastLayer = 1
layers -= 1
else:
lastLayer = 0
if cells_in_order[0].type == self.STEM or cells_in_order[0].type == self.BASAL:
firstLayer = 1
layers -= 1
else:
firstLayer = 0
layersInBetween = layers
for x in range(firstLayer, len(cells_in_order) - 1 - lastLayer, 1):
if cells_in_order[x].type != self.INTERMEDIATE:
layersInBetween -= 1
lib = 0 if layers == 0 else (layers - layersInBetween) / layers
fitness_a = 1.0 - (
(1.0 - float(firstLayer)) +
(1.0 - float(lastLayer)) +
lib +
(1.0 - float(optimumLayers))) / 4.0
sumFitness_a.append(fitness_a)
# print "!!!!!!!!!!!!!!!!! x: ", x, " steps: ", int(ratio * self.execConfig.xDimension), " fitness_a: ", fitness_a
fitness_a = sum(sumFitness_a) / len(sumFitness_a)
self._addLine(mcs, fitness_a)
def mode(self, IDs):
"""
Returns the mode of the IDs in a certain region.
:param IDs:
:return:
"""
corresponding = {}
occurances = []
for i in IDs:
count = IDs.count(i)
corresponding.update({i: count})
for i in corresponding:
freq = corresponding[i]
occurances.append(freq)
maxFreq = max(occurances)
keys = corresponding.keys()
values = corresponding.values()
index_v = values.index(maxFreq)
mode = keys[index_v]
return mode
| apache-2.0 |
dbussink/linux | tools/perf/util/setup.py | 766 | 1540 | #!/usr/bin/python2
from distutils.core import setup, Extension
from os import getenv
from distutils.command.build_ext import build_ext as _build_ext
from distutils.command.install_lib import install_lib as _install_lib
class build_ext(_build_ext):
def finalize_options(self):
_build_ext.finalize_options(self)
self.build_lib = build_lib
self.build_temp = build_tmp
class install_lib(_install_lib):
def finalize_options(self):
_install_lib.finalize_options(self)
self.build_dir = build_lib
cflags = getenv('CFLAGS', '').split()
# switch off several checks (need to be at the end of cflags list)
cflags += ['-fno-strict-aliasing', '-Wno-write-strings', '-Wno-unused-parameter' ]
build_lib = getenv('PYTHON_EXTBUILD_LIB')
build_tmp = getenv('PYTHON_EXTBUILD_TMP')
libtraceevent = getenv('LIBTRACEEVENT')
libapikfs = getenv('LIBAPI')
ext_sources = [f.strip() for f in file('util/python-ext-sources')
if len(f.strip()) > 0 and f[0] != '#']
perf = Extension('perf',
sources = ext_sources,
include_dirs = ['util/include'],
extra_compile_args = cflags,
extra_objects = [libtraceevent, libapikfs],
)
setup(name='perf',
version='0.1',
description='Interface with the Linux profiling infrastructure',
author='Arnaldo Carvalho de Melo',
author_email='acme@redhat.com',
license='GPLv2',
url='http://perf.wiki.kernel.org',
ext_modules=[perf],
cmdclass={'build_ext': build_ext, 'install_lib': install_lib})
| gpl-2.0 |
andyh616/mne-python | mne/tests/test_epochs.py | 1 | 71695 | # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
from copy import deepcopy
from nose.tools import (assert_true, assert_equal, assert_raises,
assert_not_equal)
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_allclose)
import numpy as np
import copy as cp
import warnings
from scipy import fftpack
import matplotlib
from mne import (io, Epochs, read_events, pick_events, read_epochs,
equalize_channels, pick_types, pick_channels, read_evokeds,
write_evokeds)
from mne.epochs import (
bootstrap, equalize_epoch_counts, combine_event_ids, add_channels_epochs,
EpochsArray, concatenate_epochs, _BaseEpochs)
from mne.utils import (_TempDir, requires_pandas, slow_test,
clean_warning_registry, run_tests_if_main,
requires_scipy_version)
from mne.io.meas_info import create_info
from mne.io.proj import _has_eeg_average_ref_proj
from mne.event import merge_events
from mne.io.constants import FIFF
from mne.externals.six import text_type
from mne.externals.six.moves import zip, cPickle as pickle
matplotlib.use('Agg') # for testing don't use X server
warnings.simplefilter('always') # enable b/c these tests throw warnings
base_dir = op.join(op.dirname(__file__), '..', 'io', 'tests', 'data')
raw_fname = op.join(base_dir, 'test_raw.fif')
event_name = op.join(base_dir, 'test-eve.fif')
evoked_nf_name = op.join(base_dir, 'test-nf-ave.fif')
event_id, tmin, tmax = 1, -0.2, 0.5
event_id_2 = 2
def _get_data():
raw = io.Raw(raw_fname, add_eeg_ref=False)
events = read_events(event_name)
picks = pick_types(raw.info, meg=True, eeg=True, stim=True,
ecg=True, eog=True, include=['STI 014'],
exclude='bads')
return raw, events, picks
reject = dict(grad=1000e-12, mag=4e-12, eeg=80e-6, eog=150e-6)
flat = dict(grad=1e-15, mag=1e-15)
clean_warning_registry() # really clean warning stack
def test_reject():
"""Test epochs rejection
"""
raw, events, picks = _get_data()
# cull the list just to contain the relevant event
events = events[events[:, 2] == event_id, :]
selection = np.arange(3)
drop_log = [[]] * 3 + [['MEG 2443']] * 4
assert_raises(TypeError, pick_types, raw)
picks_meg = pick_types(raw.info, meg=True, eeg=False)
assert_raises(TypeError, Epochs, raw, events, event_id, tmin, tmax,
picks=picks, preload=False, reject='foo')
assert_raises(ValueError, Epochs, raw, events, event_id, tmin, tmax,
picks=picks_meg, preload=False, reject=dict(eeg=1.))
assert_raises(KeyError, Epochs, raw, events, event_id, tmin, tmax,
picks=picks, preload=False, reject=dict(foo=1.))
data_7 = dict()
keep_idx = [0, 1, 2]
for preload in (True, False):
for proj in (True, False, 'delayed'):
# no rejection
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
preload=preload)
assert_raises(ValueError, epochs.drop_bad_epochs, reject='foo')
epochs.drop_bad_epochs()
assert_equal(len(epochs), len(events))
assert_array_equal(epochs.selection, np.arange(len(events)))
assert_array_equal(epochs.drop_log, [[]] * 7)
if proj not in data_7:
data_7[proj] = epochs.get_data()
assert_array_equal(epochs.get_data(), data_7[proj])
# with rejection
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
reject=reject, preload=preload)
epochs.drop_bad_epochs()
assert_equal(len(epochs), len(events) - 4)
assert_array_equal(epochs.selection, selection)
assert_array_equal(epochs.drop_log, drop_log)
assert_array_equal(epochs.get_data(), data_7[proj][keep_idx])
# rejection post-hoc
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
preload=preload)
epochs.drop_bad_epochs()
assert_equal(len(epochs), len(events))
assert_array_equal(epochs.get_data(), data_7[proj])
epochs.drop_bad_epochs(reject)
assert_equal(len(epochs), len(events) - 4)
assert_equal(len(epochs), len(epochs.get_data()))
assert_array_equal(epochs.selection, selection)
assert_array_equal(epochs.drop_log, drop_log)
assert_array_equal(epochs.get_data(), data_7[proj][keep_idx])
# rejection twice
reject_part = dict(grad=1100e-12, mag=4e-12, eeg=80e-6, eog=150e-6)
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
reject=reject_part, preload=preload)
epochs.drop_bad_epochs()
assert_equal(len(epochs), len(events) - 1)
epochs.drop_bad_epochs(reject)
assert_equal(len(epochs), len(events) - 4)
assert_array_equal(epochs.selection, selection)
assert_array_equal(epochs.drop_log, drop_log)
assert_array_equal(epochs.get_data(), data_7[proj][keep_idx])
# ensure that thresholds must become more stringent, not less
assert_raises(ValueError, epochs.drop_bad_epochs, reject_part)
assert_equal(len(epochs), len(events) - 4)
assert_array_equal(epochs.get_data(), data_7[proj][keep_idx])
epochs.drop_bad_epochs(flat=dict(mag=1.))
assert_equal(len(epochs), 0)
assert_raises(ValueError, epochs.drop_bad_epochs,
flat=dict(mag=0.))
# rejection of subset of trials (ensure array ownership)
reject_part = dict(grad=1100e-12, mag=4e-12, eeg=80e-6, eog=150e-6)
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
reject=None, preload=preload)
epochs = epochs[:-1]
epochs.drop_bad_epochs(reject=reject)
assert_equal(len(epochs), len(events) - 4)
assert_array_equal(epochs.get_data(), data_7[proj][keep_idx])
def test_decim():
"""Test epochs decimation
"""
# First with EpochsArray
n_epochs, n_channels, n_times = 5, 10, 20
dec_1, dec_2 = 2, 3
decim = dec_1 * dec_2
sfreq = 1000.
sfreq_new = sfreq / decim
data = np.random.randn(n_epochs, n_channels, n_times)
events = np.array([np.arange(n_epochs), [0] * n_epochs, [1] * n_epochs]).T
info = create_info(n_channels, sfreq, 'eeg')
info['lowpass'] = sfreq_new / float(decim)
epochs = EpochsArray(data, info, events)
data_epochs = epochs.decimate(decim, copy=True).get_data()
data_epochs_2 = epochs.decimate(dec_1).decimate(dec_2).get_data()
assert_array_equal(data_epochs, data[:, :, ::decim])
assert_array_equal(data_epochs, data_epochs_2)
# Now let's do it with some real data
raw, events, picks = _get_data()
sfreq_new = raw.info['sfreq'] / decim
raw.info['lowpass'] = sfreq_new / 4. # suppress aliasing warnings
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
preload=False)
assert_raises(ValueError, epochs.decimate, -1)
expected_data = epochs.get_data()[:, :, ::decim]
expected_times = epochs.times[::decim]
for preload in (True, False):
# at init
epochs = Epochs(raw, events, event_id, tmin, tmax, decim=decim,
preload=preload)
assert_allclose(epochs.get_data(), expected_data)
assert_allclose(epochs.get_data(), expected_data)
assert_equal(epochs.info['sfreq'], sfreq_new)
assert_array_equal(epochs.times, expected_times)
# split between init and afterward
epochs = Epochs(raw, events, event_id, tmin, tmax, decim=dec_1,
preload=preload).decimate(dec_2)
assert_allclose(epochs.get_data(), expected_data)
assert_allclose(epochs.get_data(), expected_data)
assert_equal(epochs.info['sfreq'], sfreq_new)
assert_array_equal(epochs.times, expected_times)
epochs = Epochs(raw, events, event_id, tmin, tmax, decim=dec_2,
preload=preload).decimate(dec_1)
assert_allclose(epochs.get_data(), expected_data)
assert_allclose(epochs.get_data(), expected_data)
assert_equal(epochs.info['sfreq'], sfreq_new)
assert_array_equal(epochs.times, expected_times)
# split between init and afterward, with preload in between
epochs = Epochs(raw, events, event_id, tmin, tmax, decim=dec_1,
preload=preload)
epochs.preload_data()
epochs = epochs.decimate(dec_2)
assert_allclose(epochs.get_data(), expected_data)
assert_allclose(epochs.get_data(), expected_data)
assert_equal(epochs.info['sfreq'], sfreq_new)
assert_array_equal(epochs.times, expected_times)
epochs = Epochs(raw, events, event_id, tmin, tmax, decim=dec_2,
preload=preload)
epochs.preload_data()
epochs = epochs.decimate(dec_1)
assert_allclose(epochs.get_data(), expected_data)
assert_allclose(epochs.get_data(), expected_data)
assert_equal(epochs.info['sfreq'], sfreq_new)
assert_array_equal(epochs.times, expected_times)
# decimate afterward
epochs = Epochs(raw, events, event_id, tmin, tmax,
preload=preload).decimate(decim)
assert_allclose(epochs.get_data(), expected_data)
assert_allclose(epochs.get_data(), expected_data)
assert_equal(epochs.info['sfreq'], sfreq_new)
assert_array_equal(epochs.times, expected_times)
# decimate afterward, with preload in between
epochs = Epochs(raw, events, event_id, tmin, tmax,
preload=preload)
epochs.preload_data()
epochs.decimate(decim)
assert_allclose(epochs.get_data(), expected_data)
assert_allclose(epochs.get_data(), expected_data)
assert_equal(epochs.info['sfreq'], sfreq_new)
assert_array_equal(epochs.times, expected_times)
def test_base_epochs():
"""Test base epochs class
"""
raw = _get_data()[0]
epochs = _BaseEpochs(raw.info, None, np.ones((1, 3), int),
event_id, tmin, tmax)
assert_raises(NotImplementedError, epochs.get_data)
# events with non integers
assert_raises(ValueError, _BaseEpochs, raw.info, None,
np.ones((1, 3), float), event_id, tmin, tmax)
assert_raises(ValueError, _BaseEpochs, raw.info, None,
np.ones((1, 3, 2), int), event_id, tmin, tmax)
@requires_scipy_version('0.14')
def test_savgol_filter():
"""Test savgol filtering
"""
h_freq = 10.
raw, events = _get_data()[:2]
epochs = Epochs(raw, events, event_id, tmin, tmax)
assert_raises(RuntimeError, epochs.savgol_filter, 10.)
epochs = Epochs(raw, events, event_id, tmin, tmax, preload=True)
freqs = fftpack.fftfreq(len(epochs.times), 1. / epochs.info['sfreq'])
data = np.abs(fftpack.fft(epochs.get_data()))
match_mask = np.logical_and(freqs >= 0, freqs <= h_freq / 2.)
mismatch_mask = np.logical_and(freqs >= h_freq * 2, freqs < 50.)
epochs.savgol_filter(h_freq)
data_filt = np.abs(fftpack.fft(epochs.get_data()))
# decent in pass-band
assert_allclose(np.mean(data[:, :, match_mask], 0),
np.mean(data_filt[:, :, match_mask], 0),
rtol=1e-4, atol=1e-2)
# suppression in stop-band
assert_true(np.mean(data[:, :, mismatch_mask]) >
np.mean(data_filt[:, :, mismatch_mask]) * 5)
def test_epochs_hash():
"""Test epoch hashing
"""
raw, events = _get_data()[:2]
epochs = Epochs(raw, events, event_id, tmin, tmax)
assert_raises(RuntimeError, epochs.__hash__)
epochs = Epochs(raw, events, event_id, tmin, tmax, preload=True)
assert_equal(hash(epochs), hash(epochs))
epochs_2 = Epochs(raw, events, event_id, tmin, tmax, preload=True)
assert_equal(hash(epochs), hash(epochs_2))
# do NOT use assert_equal here, failing output is terrible
assert_true(pickle.dumps(epochs) == pickle.dumps(epochs_2))
epochs_2._data[0, 0, 0] -= 1
assert_not_equal(hash(epochs), hash(epochs_2))
def test_event_ordering():
"""Test event order"""
raw, events = _get_data()[:2]
events2 = events.copy()
np.random.shuffle(events2)
for ii, eve in enumerate([events, events2]):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
Epochs(raw, eve, event_id, tmin, tmax,
baseline=(None, 0), reject=reject, flat=flat)
assert_equal(len(w), ii)
if ii > 0:
assert_true('chronologically' in '%s' % w[-1].message)
def test_epochs_bad_baseline():
"""Test Epochs initialization with bad baseline parameters
"""
raw, events = _get_data()[:2]
assert_raises(ValueError, Epochs, raw, events, None, -0.1, 0.3, (-0.2, 0))
assert_raises(ValueError, Epochs, raw, events, None, -0.1, 0.3, (0, 0.4))
def test_epoch_combine_ids():
"""Test combining event ids in epochs compared to events
"""
raw, events, picks = _get_data()
epochs = Epochs(raw, events, {'a': 1, 'b': 2, 'c': 3,
'd': 4, 'e': 5, 'f': 32},
tmin, tmax, picks=picks, preload=False)
events_new = merge_events(events, [1, 2], 12)
epochs_new = combine_event_ids(epochs, ['a', 'b'], {'ab': 12})
assert_equal(epochs_new['ab'].name, 'ab')
assert_array_equal(events_new, epochs_new.events)
# should probably add test + functionality for non-replacement XXX
def test_epoch_multi_ids():
"""Test epoch selection via multiple/partial keys
"""
raw, events, picks = _get_data()
epochs = Epochs(raw, events, {'a/b/a': 1, 'a/b/b': 2, 'a/c': 3,
'b/d': 4, 'a_b': 5},
tmin, tmax, picks=picks, preload=False)
epochs_regular = epochs[['a', 'b']]
epochs_multi = epochs[['a/b/a', 'a/b/b']]
assert_array_equal(epochs_regular.events, epochs_multi.events)
def test_read_epochs_bad_events():
"""Test epochs when events are at the beginning or the end of the file
"""
raw, events, picks = _get_data()
# Event at the beginning
epochs = Epochs(raw, np.array([[raw.first_samp, 0, event_id]]),
event_id, tmin, tmax, picks=picks, baseline=(None, 0))
with warnings.catch_warnings(record=True):
evoked = epochs.average()
epochs = Epochs(raw, np.array([[raw.first_samp, 0, event_id]]),
event_id, tmin, tmax, picks=picks, baseline=(None, 0))
assert_true(repr(epochs)) # test repr
epochs.drop_bad_epochs()
assert_true(repr(epochs))
with warnings.catch_warnings(record=True):
evoked = epochs.average()
# Event at the end
epochs = Epochs(raw, np.array([[raw.last_samp, 0, event_id]]),
event_id, tmin, tmax, picks=picks, baseline=(None, 0))
with warnings.catch_warnings(record=True):
evoked = epochs.average()
assert evoked
warnings.resetwarnings()
@slow_test
def test_read_write_epochs():
"""Test epochs from raw files with IO as fif file
"""
raw, events, picks = _get_data()
tempdir = _TempDir()
temp_fname = op.join(tempdir, 'test-epo.fif')
temp_fname_no_bl = op.join(tempdir, 'test_no_bl-epo.fif')
baseline = (None, 0)
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=baseline, preload=True)
epochs_no_bl = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=None, preload=True)
assert_true(epochs_no_bl.baseline is None)
evoked = epochs.average()
data = epochs.get_data()
# Bad tmin/tmax parameters
assert_raises(ValueError, Epochs, raw, events, event_id, tmax, tmin,
baseline=None)
epochs_no_id = Epochs(raw, pick_events(events, include=event_id),
None, tmin, tmax, picks=picks,
baseline=(None, 0))
assert_array_equal(data, epochs_no_id.get_data())
eog_picks = pick_types(raw.info, meg=False, eeg=False, stim=False,
eog=True, exclude='bads')
eog_ch_names = [raw.ch_names[k] for k in eog_picks]
epochs.drop_channels(eog_ch_names)
epochs_no_bl.drop_channels(eog_ch_names)
assert_true(len(epochs.info['chs']) == len(epochs.ch_names) ==
epochs.get_data().shape[1])
data_no_eog = epochs.get_data()
assert_true(data.shape[1] == (data_no_eog.shape[1] + len(eog_picks)))
# test decim kwarg
with warnings.catch_warnings(record=True) as w:
# decim with lowpass
warnings.simplefilter('always')
epochs_dec = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), decim=4)
assert_equal(len(w), 1)
# decim without lowpass
lowpass = raw.info['lowpass']
raw.info['lowpass'] = None
epochs_dec = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), decim=4)
assert_equal(len(w), 2)
raw.info['lowpass'] = lowpass
data_dec = epochs_dec.get_data()
assert_allclose(data[:, :, epochs_dec._decim_slice], data_dec, rtol=1e-7,
atol=1e-12)
evoked_dec = epochs_dec.average()
assert_allclose(evoked.data[:, epochs_dec._decim_slice],
evoked_dec.data, rtol=1e-12)
n = evoked.data.shape[1]
n_dec = evoked_dec.data.shape[1]
n_dec_min = n // 4
assert_true(n_dec_min <= n_dec <= n_dec_min + 1)
assert_true(evoked_dec.info['sfreq'] == evoked.info['sfreq'] / 4)
# test IO
epochs.save(temp_fname)
epochs_no_bl.save(temp_fname_no_bl)
epochs_read = read_epochs(temp_fname)
epochs_no_bl_read = read_epochs(temp_fname_no_bl)
assert_raises(ValueError, epochs.apply_baseline, baseline=[1, 2, 3])
epochs_no_bl_read.apply_baseline(baseline)
assert_true(epochs_no_bl_read.baseline == baseline)
assert_true(str(epochs_read).startswith('<Epochs'))
assert_array_equal(epochs_no_bl_read.times, epochs.times)
assert_array_almost_equal(epochs_read.get_data(), epochs.get_data())
assert_array_almost_equal(epochs.get_data(), epochs_no_bl_read.get_data())
assert_array_equal(epochs_read.times, epochs.times)
assert_array_almost_equal(epochs_read.average().data, evoked.data)
assert_equal(epochs_read.proj, epochs.proj)
bmin, bmax = epochs.baseline
if bmin is None:
bmin = epochs.times[0]
if bmax is None:
bmax = epochs.times[-1]
baseline = (bmin, bmax)
assert_array_almost_equal(epochs_read.baseline, baseline)
assert_array_almost_equal(epochs_read.tmin, epochs.tmin, 2)
assert_array_almost_equal(epochs_read.tmax, epochs.tmax, 2)
assert_equal(epochs_read.event_id, epochs.event_id)
epochs.event_id.pop('1')
epochs.event_id.update({'a:a': 1}) # test allow for ':' in key
epochs.save(op.join(tempdir, 'foo-epo.fif'))
epochs_read2 = read_epochs(op.join(tempdir, 'foo-epo.fif'))
assert_equal(epochs_read2.event_id, epochs.event_id)
# add reject here so some of the epochs get dropped
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), reject=reject)
epochs.save(temp_fname)
# ensure bad events are not saved
epochs_read3 = read_epochs(temp_fname)
assert_array_equal(epochs_read3.events, epochs.events)
data = epochs.get_data()
assert_true(epochs_read3.events.shape[0] == data.shape[0])
# test copying loaded one (raw property)
epochs_read4 = epochs_read3.copy()
assert_array_almost_equal(epochs_read4.get_data(), data)
# test equalizing loaded one (drop_log property)
epochs_read4.equalize_event_counts(epochs.event_id)
epochs.drop_epochs([1, 2], reason='can we recover orig ID?')
epochs.save(temp_fname)
epochs_read5 = read_epochs(temp_fname)
assert_array_equal(epochs_read5.selection, epochs.selection)
assert_equal(len(epochs_read5.selection), len(epochs_read5.events))
assert_array_equal(epochs_read5.drop_log, epochs.drop_log)
# Test that one can drop channels on read file
epochs_read5.drop_channels(epochs_read5.ch_names[:1])
# test warnings on bad filenames
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
epochs_badname = op.join(tempdir, 'test-bad-name.fif.gz')
epochs.save(epochs_badname)
read_epochs(epochs_badname)
assert_true(len(w) == 2)
# test loading epochs with missing events
epochs = Epochs(raw, events, dict(foo=1, bar=999), tmin, tmax, picks=picks,
on_missing='ignore')
epochs.save(temp_fname)
epochs_read = read_epochs(temp_fname)
assert_allclose(epochs.get_data(), epochs_read.get_data())
assert_array_equal(epochs.events, epochs_read.events)
assert_equal(set(epochs.event_id.keys()),
set(text_type(x) for x in epochs_read.event_id.keys()))
# test saving split epoch files
epochs.save(temp_fname, split_size='7MB')
epochs_read = read_epochs(temp_fname)
assert_allclose(epochs.get_data(), epochs_read.get_data())
assert_array_equal(epochs.events, epochs_read.events)
assert_array_equal(epochs.selection, epochs_read.selection)
assert_equal(epochs.drop_log, epochs_read.drop_log)
# Test that having a single time point works
epochs.preload_data()
epochs.crop(0, 0, copy=False)
assert_equal(len(epochs.times), 1)
assert_equal(epochs.get_data().shape[-1], 1)
epochs.save(temp_fname)
epochs_read = read_epochs(temp_fname)
assert_equal(len(epochs_read.times), 1)
assert_equal(epochs.get_data().shape[-1], 1)
def test_epochs_proj():
"""Test handling projection (apply proj in Raw or in Epochs)
"""
tempdir = _TempDir()
raw, events, picks = _get_data()
exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more
this_picks = pick_types(raw.info, meg=True, eeg=False, stim=True,
eog=True, exclude=exclude)
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=this_picks,
baseline=(None, 0), proj=True)
assert_true(all(p['active'] is True for p in epochs.info['projs']))
evoked = epochs.average()
assert_true(all(p['active'] is True for p in evoked.info['projs']))
data = epochs.get_data()
raw_proj = io.Raw(raw_fname, proj=True)
epochs_no_proj = Epochs(raw_proj, events[:4], event_id, tmin, tmax,
picks=this_picks, baseline=(None, 0), proj=False)
data_no_proj = epochs_no_proj.get_data()
assert_true(all(p['active'] is True for p in epochs_no_proj.info['projs']))
evoked_no_proj = epochs_no_proj.average()
assert_true(all(p['active'] is True for p in evoked_no_proj.info['projs']))
assert_true(epochs_no_proj.proj is True) # as projs are active from Raw
assert_array_almost_equal(data, data_no_proj, decimal=8)
# make sure we can exclude avg ref
this_picks = pick_types(raw.info, meg=True, eeg=True, stim=True,
eog=True, exclude=exclude)
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=this_picks,
baseline=(None, 0), proj=True, add_eeg_ref=True)
assert_true(_has_eeg_average_ref_proj(epochs.info['projs']))
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=this_picks,
baseline=(None, 0), proj=True, add_eeg_ref=False)
assert_true(not _has_eeg_average_ref_proj(epochs.info['projs']))
# make sure we don't add avg ref when a custom ref has been applied
raw.info['custom_ref_applied'] = True
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=this_picks,
baseline=(None, 0), proj=True)
assert_true(not _has_eeg_average_ref_proj(epochs.info['projs']))
# From GH#2200:
# This has no problem
proj = raw.info['projs']
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=this_picks,
baseline=(None, 0), proj=False)
epochs.info['projs'] = []
data = epochs.copy().add_proj(proj).apply_proj().get_data()
# save and reload data
fname_epo = op.join(tempdir, 'temp-epo.fif')
epochs.save(fname_epo) # Save without proj added
epochs_read = read_epochs(fname_epo)
epochs_read.add_proj(proj)
epochs_read.apply_proj() # This used to bomb
data_2 = epochs_read.get_data() # Let's check the result
assert_allclose(data, data_2, atol=1e-15, rtol=1e-3)
def test_evoked_arithmetic():
"""Test arithmetic of evoked data
"""
raw, events, picks = _get_data()
epochs1 = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, 0))
evoked1 = epochs1.average()
epochs2 = Epochs(raw, events[4:8], event_id, tmin, tmax, picks=picks,
baseline=(None, 0))
evoked2 = epochs2.average()
epochs = Epochs(raw, events[:8], event_id, tmin, tmax, picks=picks,
baseline=(None, 0))
evoked = epochs.average()
evoked_sum = evoked1 + evoked2
assert_array_equal(evoked.data, evoked_sum.data)
assert_array_equal(evoked.times, evoked_sum.times)
assert_true(evoked_sum.nave == (evoked1.nave + evoked2.nave))
evoked_diff = evoked1 - evoked1
assert_array_equal(np.zeros_like(evoked.data), evoked_diff.data)
def test_evoked_io_from_epochs():
"""Test IO of evoked data made from epochs
"""
tempdir = _TempDir()
raw, events, picks = _get_data()
# offset our tmin so we don't get exactly a zero value when decimating
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
epochs = Epochs(raw, events[:4], event_id, tmin + 0.011, tmax,
picks=picks, baseline=(None, 0), decim=5)
assert_true(len(w) == 1)
evoked = epochs.average()
evoked.save(op.join(tempdir, 'evoked-ave.fif'))
evoked2 = read_evokeds(op.join(tempdir, 'evoked-ave.fif'))[0]
assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20)
assert_allclose(evoked.times, evoked2.times, rtol=1e-4,
atol=1 / evoked.info['sfreq'])
# now let's do one with negative time
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
epochs = Epochs(raw, events[:4], event_id, 0.1, tmax,
picks=picks, baseline=(0.1, 0.2), decim=5)
evoked = epochs.average()
evoked.save(op.join(tempdir, 'evoked-ave.fif'))
evoked2 = read_evokeds(op.join(tempdir, 'evoked-ave.fif'))[0]
assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20)
assert_allclose(evoked.times, evoked2.times, rtol=1e-4, atol=1e-20)
# should be equivalent to a cropped original
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
epochs = Epochs(raw, events[:4], event_id, -0.2, tmax,
picks=picks, baseline=(0.1, 0.2), decim=5)
evoked = epochs.average()
evoked.crop(0.099, None)
assert_allclose(evoked.data, evoked2.data, rtol=1e-4, atol=1e-20)
assert_allclose(evoked.times, evoked2.times, rtol=1e-4, atol=1e-20)
def test_evoked_standard_error():
"""Test calculation and read/write of standard error
"""
raw, events, picks = _get_data()
tempdir = _TempDir()
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, 0))
evoked = [epochs.average(), epochs.standard_error()]
write_evokeds(op.join(tempdir, 'evoked-ave.fif'), evoked)
evoked2 = read_evokeds(op.join(tempdir, 'evoked-ave.fif'), [0, 1])
evoked3 = [read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 'Unknown'),
read_evokeds(op.join(tempdir, 'evoked-ave.fif'), 'Unknown',
kind='standard_error')]
for evoked_new in [evoked2, evoked3]:
assert_true(evoked_new[0]._aspect_kind ==
FIFF.FIFFV_ASPECT_AVERAGE)
assert_true(evoked_new[0].kind == 'average')
assert_true(evoked_new[1]._aspect_kind ==
FIFF.FIFFV_ASPECT_STD_ERR)
assert_true(evoked_new[1].kind == 'standard_error')
for ave, ave2 in zip(evoked, evoked_new):
assert_array_almost_equal(ave.data, ave2.data)
assert_array_almost_equal(ave.times, ave2.times)
assert_equal(ave.nave, ave2.nave)
assert_equal(ave._aspect_kind, ave2._aspect_kind)
assert_equal(ave.kind, ave2.kind)
assert_equal(ave.last, ave2.last)
assert_equal(ave.first, ave2.first)
def test_reject_epochs():
"""Test of epochs rejection
"""
raw, events, picks = _get_data()
events1 = events[events[:, 2] == event_id]
epochs = Epochs(raw, events1,
event_id, tmin, tmax, baseline=(None, 0),
reject=reject, flat=flat)
assert_raises(RuntimeError, len, epochs)
n_events = len(epochs.events)
data = epochs.get_data()
n_clean_epochs = len(data)
# Should match
# mne_process_raw --raw test_raw.fif --projoff \
# --saveavetag -ave --ave test.ave --filteroff
assert_true(n_events > n_clean_epochs)
assert_true(n_clean_epochs == 3)
assert_true(epochs.drop_log == [[], [], [], ['MEG 2443'], ['MEG 2443'],
['MEG 2443'], ['MEG 2443']])
# Ensure epochs are not dropped based on a bad channel
raw_2 = raw.copy()
raw_2.info['bads'] = ['MEG 2443']
reject_crazy = dict(grad=1000e-15, mag=4e-15, eeg=80e-9, eog=150e-9)
epochs = Epochs(raw_2, events1, event_id, tmin, tmax, baseline=(None, 0),
reject=reject_crazy, flat=flat)
epochs.drop_bad_epochs()
assert_true(all('MEG 2442' in e for e in epochs.drop_log))
assert_true(all('MEG 2443' not in e for e in epochs.drop_log))
# Invalid reject_tmin/reject_tmax/detrend
assert_raises(ValueError, Epochs, raw, events1, event_id, tmin, tmax,
reject_tmin=1., reject_tmax=0)
assert_raises(ValueError, Epochs, raw, events1, event_id, tmin, tmax,
reject_tmin=tmin - 1, reject_tmax=1.)
assert_raises(ValueError, Epochs, raw, events1, event_id, tmin, tmax,
reject_tmin=0., reject_tmax=tmax + 1)
epochs = Epochs(raw, events1, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), reject=reject, flat=flat,
reject_tmin=0., reject_tmax=.1)
data = epochs.get_data()
n_clean_epochs = len(data)
assert_true(n_clean_epochs == 7)
assert_true(len(epochs) == 7)
assert_true(epochs.times[epochs._reject_time][0] >= 0.)
assert_true(epochs.times[epochs._reject_time][-1] <= 0.1)
# Invalid data for _is_good_epoch function
epochs = Epochs(raw, events1, event_id, tmin, tmax, reject=None, flat=None)
assert_equal(epochs._is_good_epoch(None), (False, ['NO_DATA']))
assert_equal(epochs._is_good_epoch(np.zeros((1, 1))),
(False, ['TOO_SHORT']))
data = epochs[0].get_data()[0]
assert_equal(epochs._is_good_epoch(data), (True, None))
def test_preload_epochs():
"""Test preload of epochs
"""
raw, events, picks = _get_data()
epochs_preload = Epochs(raw, events[:16], event_id, tmin, tmax,
picks=picks, baseline=(None, 0), preload=True,
reject=reject, flat=flat)
data_preload = epochs_preload.get_data()
epochs = Epochs(raw, events[:16], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=False,
reject=reject, flat=flat)
data = epochs.get_data()
assert_array_equal(data_preload, data)
assert_array_almost_equal(epochs_preload.average().data,
epochs.average().data, 18)
def test_indexing_slicing():
"""Test of indexing and slicing operations
"""
raw, events, picks = _get_data()
epochs = Epochs(raw, events[:20], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=False,
reject=reject, flat=flat)
data_normal = epochs.get_data()
n_good_events = data_normal.shape[0]
# indices for slicing
start_index = 1
end_index = n_good_events - 1
assert((end_index - start_index) > 0)
for preload in [True, False]:
epochs2 = Epochs(raw, events[:20], event_id, tmin, tmax,
picks=picks, baseline=(None, 0), preload=preload,
reject=reject, flat=flat)
if not preload:
epochs2.drop_bad_epochs()
# using slicing
epochs2_sliced = epochs2[start_index:end_index]
data_epochs2_sliced = epochs2_sliced.get_data()
assert_array_equal(data_epochs2_sliced,
data_normal[start_index:end_index])
# using indexing
pos = 0
for idx in range(start_index, end_index):
data = epochs2_sliced[pos].get_data()
assert_array_equal(data[0], data_normal[idx])
pos += 1
# using indexing with an int
data = epochs2[data_epochs2_sliced.shape[0]].get_data()
assert_array_equal(data, data_normal[[idx]])
# using indexing with an array
idx = np.random.randint(0, data_epochs2_sliced.shape[0], 10)
data = epochs2[idx].get_data()
assert_array_equal(data, data_normal[idx])
# using indexing with a list of indices
idx = [0]
data = epochs2[idx].get_data()
assert_array_equal(data, data_normal[idx])
idx = [0, 1]
data = epochs2[idx].get_data()
assert_array_equal(data, data_normal[idx])
def test_comparision_with_c():
"""Test of average obtained vs C code
"""
raw, events = _get_data()[:2]
c_evoked = read_evokeds(evoked_nf_name, condition=0)
epochs = Epochs(raw, events, event_id, tmin, tmax,
baseline=None, preload=True,
reject=None, flat=None)
evoked = epochs.average()
sel = pick_channels(c_evoked.ch_names, evoked.ch_names)
evoked_data = evoked.data
c_evoked_data = c_evoked.data[sel]
assert_true(evoked.nave == c_evoked.nave)
assert_array_almost_equal(evoked_data, c_evoked_data, 10)
assert_array_almost_equal(evoked.times, c_evoked.times, 12)
def test_crop():
"""Test of crop of epochs
"""
raw, events, picks = _get_data()
epochs = Epochs(raw, events[:5], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=False,
reject=reject, flat=flat)
assert_raises(RuntimeError, epochs.crop, None, 0.2) # not preloaded
data_normal = epochs.get_data()
epochs2 = Epochs(raw, events[:5], event_id, tmin, tmax,
picks=picks, baseline=(None, 0), preload=True,
reject=reject, flat=flat)
with warnings.catch_warnings(record=True) as w:
epochs2.crop(-20, 200)
assert_true(len(w) == 2)
# indices for slicing
tmin_window = tmin + 0.1
tmax_window = tmax - 0.1
tmask = (epochs.times >= tmin_window) & (epochs.times <= tmax_window)
assert_true(tmin_window > tmin)
assert_true(tmax_window < tmax)
epochs3 = epochs2.crop(tmin_window, tmax_window, copy=True)
data3 = epochs3.get_data()
epochs2.crop(tmin_window, tmax_window)
data2 = epochs2.get_data()
assert_array_equal(data2, data_normal[:, :, tmask])
assert_array_equal(data3, data_normal[:, :, tmask])
# test time info is correct
epochs = EpochsArray(np.zeros((1, 1, 1000)), create_info(1, 1000., 'eeg'),
np.ones((1, 3), int), tmin=-0.2)
epochs.crop(-.200, .700)
last_time = epochs.times[-1]
with warnings.catch_warnings(record=True): # not LP filtered
epochs.decimate(10)
assert_allclose(last_time, epochs.times[-1])
def test_resample():
"""Test of resample of epochs
"""
raw, events, picks = _get_data()
epochs = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=False,
reject=reject, flat=flat)
assert_raises(RuntimeError, epochs.resample, 100)
epochs_o = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True,
reject=reject, flat=flat)
epochs = epochs_o.copy()
data_normal = cp.deepcopy(epochs.get_data())
times_normal = cp.deepcopy(epochs.times)
sfreq_normal = epochs.info['sfreq']
# upsample by 2
epochs = epochs_o.copy()
epochs.resample(sfreq_normal * 2, npad=0)
data_up = cp.deepcopy(epochs.get_data())
times_up = cp.deepcopy(epochs.times)
sfreq_up = epochs.info['sfreq']
# downsamply by 2, which should match
epochs.resample(sfreq_normal, npad=0)
data_new = cp.deepcopy(epochs.get_data())
times_new = cp.deepcopy(epochs.times)
sfreq_new = epochs.info['sfreq']
assert_true(data_up.shape[2] == 2 * data_normal.shape[2])
assert_true(sfreq_up == 2 * sfreq_normal)
assert_true(sfreq_new == sfreq_normal)
assert_true(len(times_up) == 2 * len(times_normal))
assert_array_almost_equal(times_new, times_normal, 10)
assert_true(data_up.shape[2] == 2 * data_normal.shape[2])
assert_array_almost_equal(data_new, data_normal, 5)
# use parallel
epochs = epochs_o.copy()
epochs.resample(sfreq_normal * 2, n_jobs=2, npad=0)
assert_true(np.allclose(data_up, epochs._data, rtol=1e-8, atol=1e-16))
# test copy flag
epochs = epochs_o.copy()
epochs_resampled = epochs.resample(sfreq_normal * 2, npad=0, copy=True)
assert_true(epochs_resampled is not epochs)
epochs_resampled = epochs.resample(sfreq_normal * 2, npad=0, copy=False)
assert_true(epochs_resampled is epochs)
def test_detrend():
"""Test detrending of epochs
"""
raw, events, picks = _get_data()
# test first-order
epochs_1 = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=None, detrend=1)
epochs_2 = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=None, detrend=None)
data_picks = pick_types(epochs_1.info, meg=True, eeg=True,
exclude='bads')
evoked_1 = epochs_1.average()
evoked_2 = epochs_2.average()
evoked_2.detrend(1)
# Due to roundoff these won't be exactly equal, but they should be close
assert_true(np.allclose(evoked_1.data, evoked_2.data,
rtol=1e-8, atol=1e-20))
# test zeroth-order case
for preload in [True, False]:
epochs_1 = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, None), preload=preload)
epochs_2 = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=None, preload=preload, detrend=0)
a = epochs_1.get_data()
b = epochs_2.get_data()
# All data channels should be almost equal
assert_true(np.allclose(a[:, data_picks, :], b[:, data_picks, :],
rtol=1e-16, atol=1e-20))
# There are non-M/EEG channels that should not be equal:
assert_true(not np.allclose(a, b))
assert_raises(ValueError, Epochs, raw, events[:4], event_id, tmin, tmax,
detrend=2)
def test_bootstrap():
"""Test of bootstrapping of epochs
"""
raw, events, picks = _get_data()
epochs = Epochs(raw, events[:5], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True,
reject=reject, flat=flat)
epochs2 = bootstrap(epochs, random_state=0)
assert_true(len(epochs2.events) == len(epochs.events))
assert_true(epochs._data.shape == epochs2._data.shape)
def test_epochs_copy():
"""Test copy epochs
"""
raw, events, picks = _get_data()
epochs = Epochs(raw, events[:5], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True,
reject=reject, flat=flat)
copied = epochs.copy()
assert_array_equal(epochs._data, copied._data)
epochs = Epochs(raw, events[:5], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=False,
reject=reject, flat=flat)
copied = epochs.copy()
data = epochs.get_data()
copied_data = copied.get_data()
assert_array_equal(data, copied_data)
def test_iter_evoked():
"""Test the iterator for epochs -> evoked
"""
raw, events, picks = _get_data()
epochs = Epochs(raw, events[:5], event_id, tmin, tmax, picks=picks,
baseline=(None, 0))
for ii, ev in enumerate(epochs.iter_evoked()):
x = ev.data
y = epochs.get_data()[ii, :, :]
assert_array_equal(x, y)
def test_subtract_evoked():
"""Test subtraction of Evoked from Epochs
"""
raw, events, picks = _get_data()
epochs = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks,
baseline=(None, 0))
# make sure subraction fails if data channels are missing
assert_raises(ValueError, epochs.subtract_evoked,
epochs.average(picks[:5]))
# do the subraction using the default argument
epochs.subtract_evoked()
# apply SSP now
epochs.apply_proj()
# use preloading and SSP from the start
epochs2 = Epochs(raw, events[:10], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True, proj=True)
evoked = epochs2.average()
epochs2.subtract_evoked(evoked)
# this gives the same result
assert_allclose(epochs.get_data(), epochs2.get_data())
# if we compute the evoked response after subtracting it we get zero
zero_evoked = epochs.average()
data = zero_evoked.data
assert_allclose(data, np.zeros_like(data), atol=1e-15)
def test_epoch_eq():
"""Test epoch count equalization and condition combining
"""
raw, events, picks = _get_data()
# equalizing epochs objects
epochs_1 = Epochs(raw, events, event_id, tmin, tmax, picks=picks)
epochs_2 = Epochs(raw, events, event_id_2, tmin, tmax, picks=picks)
epochs_1.drop_bad_epochs() # make sure drops are logged
assert_true(len([l for l in epochs_1.drop_log if not l]) ==
len(epochs_1.events))
drop_log1 = epochs_1.drop_log = [[] for _ in range(len(epochs_1.events))]
drop_log2 = [[] if l == ['EQUALIZED_COUNT'] else l for l in
epochs_1.drop_log]
assert_true(drop_log1 == drop_log2)
assert_true(len([l for l in epochs_1.drop_log if not l]) ==
len(epochs_1.events))
assert_true(epochs_1.events.shape[0] != epochs_2.events.shape[0])
equalize_epoch_counts([epochs_1, epochs_2], method='mintime')
assert_true(epochs_1.events.shape[0] == epochs_2.events.shape[0])
epochs_3 = Epochs(raw, events, event_id, tmin, tmax, picks=picks)
epochs_4 = Epochs(raw, events, event_id_2, tmin, tmax, picks=picks)
equalize_epoch_counts([epochs_3, epochs_4], method='truncate')
assert_true(epochs_1.events.shape[0] == epochs_3.events.shape[0])
assert_true(epochs_3.events.shape[0] == epochs_4.events.shape[0])
# equalizing conditions
epochs = Epochs(raw, events, {'a': 1, 'b': 2, 'c': 3, 'd': 4},
tmin, tmax, picks=picks, reject=reject)
epochs.drop_bad_epochs() # make sure drops are logged
assert_true(len([l for l in epochs.drop_log if not l]) ==
len(epochs.events))
drop_log1 = deepcopy(epochs.drop_log)
old_shapes = [epochs[key].events.shape[0] for key in ['a', 'b', 'c', 'd']]
epochs.equalize_event_counts(['a', 'b'], copy=False)
# undo the eq logging
drop_log2 = [[] if l == ['EQUALIZED_COUNT'] else l for l in
epochs.drop_log]
assert_true(drop_log1 == drop_log2)
assert_true(len([l for l in epochs.drop_log if not l]) ==
len(epochs.events))
new_shapes = [epochs[key].events.shape[0] for key in ['a', 'b', 'c', 'd']]
assert_true(new_shapes[0] == new_shapes[1])
assert_true(new_shapes[2] == new_shapes[2])
assert_true(new_shapes[3] == new_shapes[3])
# now with two conditions collapsed
old_shapes = new_shapes
epochs.equalize_event_counts([['a', 'b'], 'c'], copy=False)
new_shapes = [epochs[key].events.shape[0] for key in ['a', 'b', 'c', 'd']]
assert_true(new_shapes[0] + new_shapes[1] == new_shapes[2])
assert_true(new_shapes[3] == old_shapes[3])
assert_raises(KeyError, epochs.equalize_event_counts, [1, 'a'])
# now let's combine conditions
old_shapes = new_shapes
epochs = epochs.equalize_event_counts([['a', 'b'], ['c', 'd']])[0]
new_shapes = [epochs[key].events.shape[0] for key in ['a', 'b', 'c', 'd']]
assert_true(old_shapes[0] + old_shapes[1] == new_shapes[0] + new_shapes[1])
assert_true(new_shapes[0] + new_shapes[1] == new_shapes[2] + new_shapes[3])
assert_raises(ValueError, combine_event_ids, epochs, ['a', 'b'],
{'ab': 1})
combine_event_ids(epochs, ['a', 'b'], {'ab': 12}, copy=False)
caught = 0
for key in ['a', 'b']:
try:
epochs[key]
except KeyError:
caught += 1
assert_raises(Exception, caught == 2)
assert_true(not np.any(epochs.events[:, 2] == 1))
assert_true(not np.any(epochs.events[:, 2] == 2))
epochs = combine_event_ids(epochs, ['c', 'd'], {'cd': 34})
assert_true(np.all(np.logical_or(epochs.events[:, 2] == 12,
epochs.events[:, 2] == 34)))
assert_true(epochs['ab'].events.shape[0] == old_shapes[0] + old_shapes[1])
assert_true(epochs['ab'].events.shape[0] == epochs['cd'].events.shape[0])
def test_access_by_name():
"""Test accessing epochs by event name and on_missing for rare events
"""
tempdir = _TempDir()
raw, events, picks = _get_data()
# Test various invalid inputs
assert_raises(ValueError, Epochs, raw, events, {1: 42, 2: 42}, tmin,
tmax, picks=picks)
assert_raises(ValueError, Epochs, raw, events, {'a': 'spam', 2: 'eggs'},
tmin, tmax, picks=picks)
assert_raises(ValueError, Epochs, raw, events, {'a': 'spam', 2: 'eggs'},
tmin, tmax, picks=picks)
assert_raises(ValueError, Epochs, raw, events, 'foo', tmin, tmax,
picks=picks)
assert_raises(ValueError, Epochs, raw, events, ['foo'], tmin, tmax,
picks=picks)
# Test accessing non-existent events (assumes 12345678 does not exist)
event_id_illegal = dict(aud_l=1, does_not_exist=12345678)
assert_raises(ValueError, Epochs, raw, events, event_id_illegal,
tmin, tmax)
# Test on_missing
assert_raises(ValueError, Epochs, raw, events, 1, tmin, tmax,
on_missing='foo')
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
Epochs(raw, events, event_id_illegal, tmin, tmax, on_missing='warning')
nw = len(w)
assert_true(1 <= nw <= 2)
Epochs(raw, events, event_id_illegal, tmin, tmax, on_missing='ignore')
assert_equal(len(w), nw)
# Test constructing epochs with a list of ints as events
epochs = Epochs(raw, events, [1, 2], tmin, tmax, picks=picks)
for k, v in epochs.event_id.items():
assert_equal(int(k), v)
epochs = Epochs(raw, events, {'a': 1, 'b': 2}, tmin, tmax, picks=picks)
assert_raises(KeyError, epochs.__getitem__, 'bar')
data = epochs['a'].get_data()
event_a = events[events[:, 2] == 1]
assert_true(len(data) == len(event_a))
epochs = Epochs(raw, events, {'a': 1, 'b': 2}, tmin, tmax, picks=picks,
preload=True)
assert_raises(KeyError, epochs.__getitem__, 'bar')
temp_fname = op.join(tempdir, 'test-epo.fif')
epochs.save(temp_fname)
epochs2 = read_epochs(temp_fname)
for ep in [epochs, epochs2]:
data = ep['a'].get_data()
event_a = events[events[:, 2] == 1]
assert_true(len(data) == len(event_a))
assert_array_equal(epochs2['a'].events, epochs['a'].events)
epochs3 = Epochs(raw, events, {'a': 1, 'b': 2, 'c': 3, 'd': 4},
tmin, tmax, picks=picks, preload=True)
assert_equal(list(sorted(epochs3[('a', 'b')].event_id.values())),
[1, 2])
epochs4 = epochs['a']
epochs5 = epochs3['a']
assert_array_equal(epochs4.events, epochs5.events)
# 20 is our tolerance because epochs are written out as floats
assert_array_almost_equal(epochs4.get_data(), epochs5.get_data(), 20)
epochs6 = epochs3[['a', 'b']]
assert_true(all(np.logical_or(epochs6.events[:, 2] == 1,
epochs6.events[:, 2] == 2)))
assert_array_equal(epochs.events, epochs6.events)
assert_array_almost_equal(epochs.get_data(), epochs6.get_data(), 20)
# Make sure we preserve names
assert_equal(epochs['a'].name, 'a')
assert_equal(epochs[['a', 'b']]['a'].name, 'a')
@requires_pandas
def test_to_data_frame():
"""Test epochs Pandas exporter"""
raw, events, picks = _get_data()
epochs = Epochs(raw, events, {'a': 1, 'b': 2}, tmin, tmax, picks=picks)
assert_raises(ValueError, epochs.to_data_frame, index=['foo', 'bar'])
assert_raises(ValueError, epochs.to_data_frame, index='qux')
assert_raises(ValueError, epochs.to_data_frame, np.arange(400))
df = epochs.to_data_frame(index=['condition', 'epoch', 'time'],
picks=list(range(epochs.info['nchan'])))
# Default index and picks
df2 = epochs.to_data_frame()
assert_equal(df.index.names, df2.index.names)
assert_array_equal(df.columns.values, epochs.ch_names)
data = np.hstack(epochs.get_data())
assert_true((df.columns == epochs.ch_names).all())
assert_array_equal(df.values[:, 0], data[0] * 1e13)
assert_array_equal(df.values[:, 2], data[2] * 1e15)
for ind in ['time', ['condition', 'time'], ['condition', 'time', 'epoch']]:
df = epochs.to_data_frame(index=ind)
assert_true(df.index.names == ind if isinstance(ind, list) else [ind])
# test that non-indexed data were present as categorial variables
assert_array_equal(sorted(df.reset_index().columns[:3]),
sorted(['time', 'condition', 'epoch']))
def test_epochs_proj_mixin():
"""Test SSP proj methods from ProjMixin class
"""
raw, events, picks = _get_data()
for proj in [True, False]:
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), proj=proj)
assert_true(all(p['active'] == proj for p in epochs.info['projs']))
# test adding / deleting proj
if proj:
epochs.get_data()
assert_true(all(p['active'] == proj for p in epochs.info['projs']))
assert_raises(ValueError, epochs.add_proj, epochs.info['projs'][0],
{'remove_existing': True})
assert_raises(ValueError, epochs.add_proj, 'spam')
assert_raises(ValueError, epochs.del_proj, 0)
else:
projs = deepcopy(epochs.info['projs'])
n_proj = len(epochs.info['projs'])
epochs.del_proj(0)
assert_true(len(epochs.info['projs']) == n_proj - 1)
epochs.add_proj(projs, remove_existing=False)
assert_true(len(epochs.info['projs']) == 2 * n_proj - 1)
epochs.add_proj(projs, remove_existing=True)
assert_true(len(epochs.info['projs']) == n_proj)
# catch no-gos.
# wrong proj argument
assert_raises(ValueError, Epochs, raw, events[:4], event_id, tmin, tmax,
picks=picks, baseline=(None, 0), proj='crazy')
# delayed without reject params
assert_raises(RuntimeError, Epochs, raw, events[:4], event_id, tmin, tmax,
picks=picks, baseline=(None, 0), proj='delayed', reject=None)
for preload in [True, False]:
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), proj='delayed', preload=preload,
add_eeg_ref=True, reject=reject)
epochs2 = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=(None, 0), proj=True, preload=preload,
add_eeg_ref=True, reject=reject)
assert_allclose(epochs.copy().apply_proj().get_data()[0],
epochs2.get_data()[0], rtol=1e-10, atol=1e-25)
# make sure data output is constant across repeated calls
# e.g. drop bads
assert_array_equal(epochs.get_data(), epochs.get_data())
assert_array_equal(epochs2.get_data(), epochs2.get_data())
# test epochs.next calls
data = epochs.get_data().copy()
data2 = np.array([e for e in epochs])
assert_array_equal(data, data2)
# cross application from processing stream 1 to 2
epochs.apply_proj()
assert_array_equal(epochs._projector, epochs2._projector)
assert_allclose(epochs._data, epochs2.get_data())
# test mixin against manual application
epochs = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks,
baseline=None, proj=False, add_eeg_ref=True)
data = epochs.get_data().copy()
epochs.apply_proj()
assert_allclose(np.dot(epochs._projector, data[0]), epochs._data[0])
def test_delayed_epochs():
"""Test delayed projection
"""
raw, events, picks = _get_data()
events = events[:10]
picks = np.concatenate([pick_types(raw.info, meg=True, eeg=True)[::22],
pick_types(raw.info, meg=False, eeg=False,
ecg=True, eog=True)])
picks = np.sort(picks)
raw.info['lowpass'] = 40. # fake the LP info so no warnings
for preload in (True, False):
for proj in (True, False, 'delayed'):
for decim in (1, 3):
for ii in range(2):
epochs = Epochs(raw, events, event_id, tmin, tmax,
picks=picks, proj=proj, reject=reject,
preload=preload, decim=decim)
if ii == 1:
epochs.preload_data()
picks_data = pick_types(epochs.info, meg=True, eeg=True)
evoked = epochs.average(picks=picks_data)
if proj is True:
evoked.apply_proj()
epochs_data = epochs.get_data().mean(axis=0)[picks_data]
assert_array_equal(evoked.ch_names,
np.array(epochs.ch_names)[picks_data])
assert_allclose(evoked.times, epochs.times)
assert_allclose(evoked.data, epochs_data,
rtol=1e-5, atol=1e-15)
def test_drop_epochs():
"""Test dropping of epochs.
"""
raw, events, picks = _get_data()
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0))
events1 = events[events[:, 2] == event_id]
# Bound checks
assert_raises(IndexError, epochs.drop_epochs, [len(epochs.events)])
assert_raises(IndexError, epochs.drop_epochs, [-1])
assert_raises(ValueError, epochs.drop_epochs, [[1, 2], [3, 4]])
# Test selection attribute
assert_array_equal(epochs.selection,
np.where(events[:, 2] == event_id)[0])
assert_equal(len(epochs.drop_log), len(events))
assert_true(all(epochs.drop_log[k] == ['IGNORED']
for k in set(range(len(events))) - set(epochs.selection)))
selection = epochs.selection.copy()
n_events = len(epochs.events)
epochs.drop_epochs([2, 4], reason='d')
assert_equal(epochs.drop_log_stats(), 2. / n_events * 100)
assert_equal(len(epochs.drop_log), len(events))
assert_equal([epochs.drop_log[k]
for k in selection[[2, 4]]], [['d'], ['d']])
assert_array_equal(events[epochs.selection], events1[[0, 1, 3, 5, 6]])
assert_array_equal(events[epochs[3:].selection], events1[[5, 6]])
assert_array_equal(events[epochs['1'].selection], events1[[0, 1, 3, 5, 6]])
def test_drop_epochs_mult():
"""Test that subselecting epochs or making less epochs is equivalent"""
raw, events, picks = _get_data()
for preload in [True, False]:
epochs1 = Epochs(raw, events, {'a': 1, 'b': 2},
tmin, tmax, picks=picks, reject=reject,
preload=preload)['a']
epochs2 = Epochs(raw, events, {'a': 1},
tmin, tmax, picks=picks, reject=reject,
preload=preload)
if preload:
# In the preload case you cannot know the bads if already ignored
assert_equal(len(epochs1.drop_log), len(epochs2.drop_log))
for d1, d2 in zip(epochs1.drop_log, epochs2.drop_log):
if d1 == ['IGNORED']:
assert_true(d2 == ['IGNORED'])
if d1 != ['IGNORED'] and d1 != []:
assert_true((d2 == d1) or (d2 == ['IGNORED']))
if d1 == []:
assert_true(d2 == [])
assert_array_equal(epochs1.events, epochs2.events)
assert_array_equal(epochs1.selection, epochs2.selection)
else:
# In the non preload is should be exactly the same
assert_equal(epochs1.drop_log, epochs2.drop_log)
assert_array_equal(epochs1.events, epochs2.events)
assert_array_equal(epochs1.selection, epochs2.selection)
def test_contains():
"""Test membership API"""
raw, events = _get_data()[:2]
tests = [(('mag', False), ('grad', 'eeg')),
(('grad', False), ('mag', 'eeg')),
((False, True), ('grad', 'mag'))]
for (meg, eeg), others in tests:
picks_contains = pick_types(raw.info, meg=meg, eeg=eeg)
epochs = Epochs(raw, events, {'a': 1, 'b': 2}, tmin, tmax,
picks=picks_contains, reject=None,
preload=False)
test = 'eeg' if eeg is True else meg
assert_true(test in epochs)
assert_true(not any(o in epochs for o in others))
assert_raises(ValueError, epochs.__contains__, 'foo')
assert_raises(ValueError, epochs.__contains__, 1)
def test_drop_channels_mixin():
"""Test channels-dropping functionality
"""
raw, events = _get_data()[:2]
# here without picks to get additional coverage
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=None,
baseline=(None, 0), preload=True)
drop_ch = epochs.ch_names[:3]
ch_names = epochs.ch_names[3:]
ch_names_orig = epochs.ch_names
dummy = epochs.drop_channels(drop_ch, copy=True)
assert_equal(ch_names, dummy.ch_names)
assert_equal(ch_names_orig, epochs.ch_names)
assert_equal(len(ch_names_orig), epochs.get_data().shape[1])
epochs.drop_channels(drop_ch)
assert_equal(ch_names, epochs.ch_names)
assert_equal(len(ch_names), epochs.get_data().shape[1])
def test_pick_channels_mixin():
"""Test channel-picking functionality
"""
raw, events, picks = _get_data()
epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), preload=True)
ch_names = epochs.ch_names[:3]
epochs.preload = False
assert_raises(RuntimeError, epochs.drop_channels, ['foo'])
epochs.preload = True
ch_names_orig = epochs.ch_names
dummy = epochs.pick_channels(ch_names, copy=True)
assert_equal(ch_names, dummy.ch_names)
assert_equal(ch_names_orig, epochs.ch_names)
assert_equal(len(ch_names_orig), epochs.get_data().shape[1])
epochs.pick_channels(ch_names)
assert_equal(ch_names, epochs.ch_names)
assert_equal(len(ch_names), epochs.get_data().shape[1])
# Invalid picks
assert_raises(ValueError, Epochs, raw, events, event_id, tmin, tmax,
picks=[])
def test_equalize_channels():
"""Test equalization of channels
"""
raw, events, picks = _get_data()
epochs1 = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
baseline=(None, 0), proj=False, preload=True)
epochs2 = epochs1.copy()
ch_names = epochs1.ch_names[2:]
epochs1.drop_channels(epochs1.ch_names[:1])
epochs2.drop_channels(epochs2.ch_names[1:2])
my_comparison = [epochs1, epochs2]
equalize_channels(my_comparison)
for e in my_comparison:
assert_equal(ch_names, e.ch_names)
def test_illegal_event_id():
"""Test handling of invalid events ids"""
raw, events, picks = _get_data()
event_id_illegal = dict(aud_l=1, does_not_exist=12345678)
assert_raises(ValueError, Epochs, raw, events, event_id_illegal, tmin,
tmax, picks=picks, baseline=(None, 0), proj=False)
def test_add_channels_epochs():
"""Test adding channels"""
raw, events, picks = _get_data()
def make_epochs(picks, proj):
return Epochs(raw, events, event_id, tmin, tmax, baseline=(None, 0),
reject=None, preload=True, proj=proj, picks=picks)
picks = pick_types(raw.info, meg=True, eeg=True, exclude='bads')
picks_meg = pick_types(raw.info, meg=True, eeg=False, exclude='bads')
picks_eeg = pick_types(raw.info, meg=False, eeg=True, exclude='bads')
for proj in (False, True):
epochs = make_epochs(picks=picks, proj=proj)
epochs_meg = make_epochs(picks=picks_meg, proj=proj)
epochs_eeg = make_epochs(picks=picks_eeg, proj=proj)
epochs.info._check_consistency()
epochs_meg.info._check_consistency()
epochs_eeg.info._check_consistency()
epochs2 = add_channels_epochs([epochs_meg, epochs_eeg])
assert_equal(len(epochs.info['projs']), len(epochs2.info['projs']))
assert_equal(len(epochs.info.keys()), len(epochs2.info.keys()))
data1 = epochs.get_data()
data2 = epochs2.get_data()
data3 = np.concatenate([e.get_data() for e in
[epochs_meg, epochs_eeg]], axis=1)
assert_array_equal(data1.shape, data2.shape)
assert_allclose(data1, data3, atol=1e-25)
assert_allclose(data1, data2, atol=1e-25)
epochs_meg2 = epochs_meg.copy()
epochs_meg2.info['meas_date'] += 10
add_channels_epochs([epochs_meg2, epochs_eeg])
epochs_meg2 = epochs_meg.copy()
epochs2.info['filename'] = epochs2.info['filename'].upper()
epochs2 = add_channels_epochs([epochs_meg, epochs_eeg])
epochs_meg2 = epochs_meg.copy()
epochs_meg2.events[3, 2] -= 1
assert_raises(ValueError, add_channels_epochs,
[epochs_meg2, epochs_eeg])
assert_raises(ValueError, add_channels_epochs,
[epochs_meg, epochs_eeg[:2]])
epochs_meg.info['chs'].pop(0)
epochs_meg.info['ch_names'].pop(0)
epochs_meg.info['nchan'] -= 1
assert_raises(RuntimeError, add_channels_epochs,
[epochs_meg, epochs_eeg])
epochs_meg2 = epochs_meg.copy()
epochs_meg2.info['sfreq'] = None
assert_raises(RuntimeError, add_channels_epochs,
[epochs_meg2, epochs_eeg])
epochs_meg2 = epochs_meg.copy()
epochs_meg2.info['sfreq'] += 10
assert_raises(RuntimeError, add_channels_epochs,
[epochs_meg2, epochs_eeg])
epochs_meg2 = epochs_meg.copy()
epochs_meg2.info['ch_names'][1] = epochs_meg2.info['ch_names'][0]
epochs_meg2.info['chs'][1]['ch_name'] = epochs_meg2.info['ch_names'][1]
assert_raises(ValueError, add_channels_epochs,
[epochs_meg2, epochs_eeg])
epochs_meg2 = epochs_meg.copy()
epochs_meg2.info['dev_head_t']['to'] += 1
assert_raises(ValueError, add_channels_epochs,
[epochs_meg2, epochs_eeg])
epochs_meg2 = epochs_meg.copy()
epochs_meg2.info['dev_head_t']['to'] += 1
assert_raises(ValueError, add_channels_epochs,
[epochs_meg2, epochs_eeg])
epochs_meg2 = epochs_meg.copy()
epochs_meg2.info['expimenter'] = 'foo'
assert_raises(RuntimeError, add_channels_epochs,
[epochs_meg2, epochs_eeg])
epochs_meg2 = epochs_meg.copy()
epochs_meg2.preload = False
assert_raises(ValueError, add_channels_epochs,
[epochs_meg2, epochs_eeg])
epochs_meg2 = epochs_meg.copy()
epochs_meg2.tmin += 0.4
assert_raises(NotImplementedError, add_channels_epochs,
[epochs_meg2, epochs_eeg])
epochs_meg2 = epochs_meg.copy()
epochs_meg2.tmin += 0.5
assert_raises(NotImplementedError, add_channels_epochs,
[epochs_meg2, epochs_eeg])
epochs_meg2 = epochs_meg.copy()
epochs_meg2.baseline = None
assert_raises(NotImplementedError, add_channels_epochs,
[epochs_meg2, epochs_eeg])
epochs_meg2 = epochs_meg.copy()
epochs_meg2.event_id['b'] = 2
assert_raises(NotImplementedError, add_channels_epochs,
[epochs_meg2, epochs_eeg])
def test_array_epochs():
"""Test creating epochs from array
"""
import matplotlib.pyplot as plt
tempdir = _TempDir()
# creating
rng = np.random.RandomState(42)
data = rng.random_sample((10, 20, 300))
sfreq = 1e3
ch_names = ['EEG %03d' % (i + 1) for i in range(20)]
types = ['eeg'] * 20
info = create_info(ch_names, sfreq, types)
events = np.c_[np.arange(1, 600, 60),
np.zeros(10, int),
[1, 2] * 5]
event_id = {'a': 1, 'b': 2}
epochs = EpochsArray(data, info, events, tmin, event_id)
assert_true(str(epochs).startswith('<EpochsArray'))
# From GH#1963
assert_raises(ValueError, EpochsArray, data[:-1], info, events, tmin,
event_id)
assert_raises(ValueError, EpochsArray, data, info, events, tmin,
dict(a=1))
# saving
temp_fname = op.join(tempdir, 'test-epo.fif')
epochs.save(temp_fname)
epochs2 = read_epochs(temp_fname)
data2 = epochs2.get_data()
assert_allclose(data, data2)
assert_allclose(epochs.times, epochs2.times)
assert_equal(epochs.event_id, epochs2.event_id)
assert_array_equal(epochs.events, epochs2.events)
# plotting
epochs[0].plot()
plt.close('all')
# indexing
assert_array_equal(np.unique(epochs['a'].events[:, 2]), np.array([1]))
assert_equal(len(epochs[:2]), 2)
data[0, 5, 150] = 3000
data[1, :, :] = 0
data[2, 5, 210] = 3000
data[3, 5, 260] = 0
epochs = EpochsArray(data, info, events=events, event_id=event_id,
tmin=0, reject=dict(eeg=1000), flat=dict(eeg=1e-1),
reject_tmin=0.1, reject_tmax=0.2)
assert_equal(len(epochs), len(events) - 2)
assert_equal(epochs.drop_log[0], ['EEG 006'])
assert_equal(len(epochs.drop_log), 10)
assert_equal(len(epochs.events), len(epochs.selection))
# baseline
data = np.ones((10, 20, 300))
epochs = EpochsArray(data, info, events=events, event_id=event_id,
tmin=-.2, baseline=(None, 0))
ep_data = epochs.get_data()
assert_array_equal(np.zeros_like(ep_data), ep_data)
# one time point
epochs = EpochsArray(data[:, :, :1], info, events=events,
event_id=event_id, tmin=0., baseline=None)
assert_allclose(epochs.times, [0.])
assert_allclose(epochs.get_data(), data[:, :, :1])
epochs.save(temp_fname)
epochs_read = read_epochs(temp_fname)
assert_allclose(epochs_read.times, [0.])
assert_allclose(epochs_read.get_data(), data[:, :, :1])
# event as integer (#2435)
mask = (events[:, 2] == 1)
data_1 = data[mask]
events_1 = events[mask]
epochs = EpochsArray(data_1, info, events=events_1, event_id=1,
tmin=-0.2, baseline=(None, 0))
def test_concatenate_epochs():
"""Test concatenate epochs"""
raw, events, picks = _get_data()
epochs = Epochs(
raw=raw, events=events, event_id=event_id, tmin=tmin, tmax=tmax,
picks=picks)
epochs2 = epochs.copy()
epochs_list = [epochs, epochs2]
epochs_conc = concatenate_epochs(epochs_list)
assert_array_equal(
epochs_conc.events[:, 0], np.unique(epochs_conc.events[:, 0]))
expected_shape = list(epochs.get_data().shape)
expected_shape[0] *= 2
expected_shape = tuple(expected_shape)
assert_equal(epochs_conc.get_data().shape, expected_shape)
assert_equal(epochs_conc.drop_log, epochs.drop_log * 2)
epochs2 = epochs.copy()
epochs2._data = epochs2.get_data()
epochs2.preload = True
assert_raises(
ValueError, concatenate_epochs,
[epochs, epochs2.drop_channels(epochs2.ch_names[:1], copy=True)])
epochs2.times = np.delete(epochs2.times, 1)
assert_raises(
ValueError,
concatenate_epochs, [epochs, epochs2])
assert_equal(epochs_conc._raw, None)
# check if baseline is same for all epochs
epochs2.baseline = (-0.1, None)
assert_raises(ValueError, concatenate_epochs, [epochs, epochs2])
def test_add_channels():
"""Test epoch splitting / re-appending channel types
"""
raw, events, picks = _get_data()
epoch_nopre = Epochs(
raw=raw, events=events, event_id=event_id, tmin=tmin, tmax=tmax,
picks=picks)
epoch = Epochs(
raw=raw, events=events, event_id=event_id, tmin=tmin, tmax=tmax,
picks=picks, preload=True)
epoch_eeg = epoch.pick_types(meg=False, eeg=True, copy=True)
epoch_meg = epoch.pick_types(meg=True, copy=True)
epoch_stim = epoch.pick_types(meg=False, stim=True, copy=True)
epoch_eeg_meg = epoch.pick_types(meg=True, eeg=True, copy=True)
epoch_new = epoch_meg.add_channels([epoch_eeg, epoch_stim], copy=True)
assert_true(all(ch in epoch_new.ch_names
for ch in epoch_stim.ch_names + epoch_meg.ch_names))
epoch_new = epoch_meg.add_channels([epoch_eeg], copy=True)
assert_true(ch in epoch_new.ch_names for ch in epoch.ch_names)
assert_array_equal(epoch_new._data, epoch_eeg_meg._data)
assert_true(all(ch not in epoch_new.ch_names
for ch in epoch_stim.ch_names))
# Now test errors
epoch_badsf = epoch_eeg.copy()
epoch_badsf.info['sfreq'] = 3.1415927
epoch_eeg = epoch_eeg.crop(-.1, .1)
assert_raises(AssertionError, epoch_meg.add_channels, [epoch_nopre])
assert_raises(RuntimeError, epoch_meg.add_channels, [epoch_badsf])
assert_raises(AssertionError, epoch_meg.add_channels, [epoch_eeg])
assert_raises(ValueError, epoch_meg.add_channels, [epoch_meg])
assert_raises(AssertionError, epoch_meg.add_channels, epoch_badsf)
run_tests_if_main()
| bsd-3-clause |
dkrisman/Traipse | mercurial/portable_hgweb/server.py | 1 | 10801 | # hgweb/server.py - The standalone hg web server.
#
# Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
# Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2, incorporated herein by reference.
import os, sys, errno, urllib, BaseHTTPServer, socket, SocketServer, traceback
from upmana.mercurial import hg, util, error
from hgweb_mod import hgweb
from hgwebdir_mod import hgwebdir
from upmana.mercurial.i18n import _
def _splitURI(uri):
""" Return path and query splited from uri
Just like CGI environment, the path is unquoted, the query is
not.
"""
if '?' in uri:
path, query = uri.split('?', 1)
else:
path, query = uri, ''
return urllib.unquote(path), query
class _error_logger(object):
def __init__(self, handler):
self.handler = handler
def flush(self):
pass
def write(self, str):
self.writelines(str.split('\n'))
def writelines(self, seq):
for msg in seq:
self.handler.log_error("HG error: %s", msg)
class _hgwebhandler(object, BaseHTTPServer.BaseHTTPRequestHandler):
url_scheme = 'http'
def __init__(self, *args, **kargs):
self.protocol_version = 'HTTP/1.1'
BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, *args, **kargs)
def _log_any(self, fp, format, *args):
fp.write("%s - - [%s] %s\n" % (self.client_address[0],
self.log_date_time_string(),
format % args))
fp.flush()
def log_error(self, format, *args):
self._log_any(self.server.errorlog, format, *args)
def log_message(self, format, *args):
self._log_any(self.server.accesslog, format, *args)
def do_write(self):
try:
self.do_hgweb()
except socket.error, inst:
if inst[0] != errno.EPIPE:
raise
def do_POST(self):
try:
self.do_write()
except StandardError:
self._start_response("500 Internal Server Error", [])
self._write("Internal Server Error")
tb = "".join(traceback.format_exception(*sys.exc_info()))
self.log_error("Exception happened during processing "
"request '%s':\n%s", self.path, tb)
def do_GET(self):
self.do_POST()
def do_hgweb(self):
path, query = _splitURI(self.path)
env = {}
env['GATEWAY_INTERFACE'] = 'CGI/1.1'
env['REQUEST_METHOD'] = self.command
env['SERVER_NAME'] = self.server.server_name
env['SERVER_PORT'] = str(self.server.server_port)
env['REQUEST_URI'] = self.path
env['SCRIPT_NAME'] = self.server.prefix
env['PATH_INFO'] = path[len(self.server.prefix):]
env['REMOTE_HOST'] = self.client_address[0]
env['REMOTE_ADDR'] = self.client_address[0]
if query:
env['QUERY_STRING'] = query
if self.headers.typeheader is None:
env['CONTENT_TYPE'] = self.headers.type
else:
env['CONTENT_TYPE'] = self.headers.typeheader
length = self.headers.getheader('content-length')
if length:
env['CONTENT_LENGTH'] = length
for header in [h for h in self.headers.keys()
if h not in ('content-type', 'content-length')]:
hkey = 'HTTP_' + header.replace('-', '_').upper()
hval = self.headers.getheader(header)
hval = hval.replace('\n', '').strip()
if hval:
env[hkey] = hval
env['SERVER_PROTOCOL'] = self.request_version
env['wsgi.version'] = (1, 0)
env['wsgi.url_scheme'] = self.url_scheme
env['wsgi.input'] = self.rfile
env['wsgi.errors'] = _error_logger(self)
env['wsgi.multithread'] = isinstance(self.server,
SocketServer.ThreadingMixIn)
env['wsgi.multiprocess'] = isinstance(self.server,
SocketServer.ForkingMixIn)
env['wsgi.run_once'] = 0
self.close_connection = True
self.saved_status = None
self.saved_headers = []
self.sent_headers = False
self.length = None
for chunk in self.server.application(env, self._start_response):
self._write(chunk)
def send_headers(self):
if not self.saved_status:
raise AssertionError("Sending headers before "
"start_response() called")
saved_status = self.saved_status.split(None, 1)
saved_status[0] = int(saved_status[0])
self.send_response(*saved_status)
should_close = True
for h in self.saved_headers:
self.send_header(*h)
if h[0].lower() == 'content-length':
should_close = False
self.length = int(h[1])
# The value of the Connection header is a list of case-insensitive
# tokens separated by commas and optional whitespace.
if 'close' in [token.strip().lower() for token in
self.headers.get('connection', '').split(',')]:
should_close = True
if should_close:
self.send_header('Connection', 'close')
self.close_connection = should_close
self.end_headers()
self.sent_headers = True
def _start_response(self, http_status, headers, exc_info=None):
code, msg = http_status.split(None, 1)
code = int(code)
self.saved_status = http_status
bad_headers = ('connection', 'transfer-encoding')
self.saved_headers = [h for h in headers
if h[0].lower() not in bad_headers]
return self._write
def _write(self, data):
if not self.saved_status:
raise AssertionError("data written before start_response() called")
elif not self.sent_headers:
self.send_headers()
if self.length is not None:
if len(data) > self.length:
raise AssertionError("Content-length header sent, but more "
"bytes than specified are being written.")
self.length = self.length - len(data)
self.wfile.write(data)
self.wfile.flush()
class _shgwebhandler(_hgwebhandler):
url_scheme = 'https'
def setup(self):
self.connection = self.request
self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
def do_write(self):
from OpenSSL.SSL import SysCallError
try:
super(_shgwebhandler, self).do_write()
except SysCallError, inst:
if inst.args[0] != errno.EPIPE:
raise
def handle_one_request(self):
from OpenSSL.SSL import SysCallError, ZeroReturnError
try:
super(_shgwebhandler, self).handle_one_request()
except (SysCallError, ZeroReturnError):
self.close_connection = True
pass
def create_server(ui, repo):
use_threads = True
def openlog(opt, default):
if opt and opt != '-':
return open(opt, 'a')
return default
if repo is None:
myui = ui
else:
myui = repo.ui
address = myui.config("web", "address", "")
port = int(myui.config("web", "port", 8000))
prefix = myui.config("web", "prefix", "")
if prefix:
prefix = "/" + prefix.strip("/")
use_ipv6 = myui.configbool("web", "ipv6")
webdir_conf = myui.config("web", "webdir_conf")
ssl_cert = myui.config("web", "certificate")
accesslog = openlog(myui.config("web", "accesslog", "-"), sys.stdout)
errorlog = openlog(myui.config("web", "errorlog", "-"), sys.stderr)
if use_threads:
try:
from threading import activeCount
except ImportError:
use_threads = False
if use_threads:
_mixin = SocketServer.ThreadingMixIn
else:
if hasattr(os, "fork"):
_mixin = SocketServer.ForkingMixIn
else:
class _mixin:
pass
class MercurialHTTPServer(object, _mixin, BaseHTTPServer.HTTPServer):
# SO_REUSEADDR has broken semantics on windows
if os.name == 'nt':
allow_reuse_address = 0
def __init__(self, *args, **kargs):
BaseHTTPServer.HTTPServer.__init__(self, *args, **kargs)
self.accesslog = accesslog
self.errorlog = errorlog
self.daemon_threads = True
def make_handler():
if webdir_conf:
hgwebobj = hgwebdir(webdir_conf, ui)
elif repo is not None:
hgwebobj = hgweb(hg.repository(repo.ui, repo.root))
else:
raise error.RepoError(_("There is no Mercurial repository"
" here (.hg not found)"))
return hgwebobj
self.application = make_handler()
if ssl_cert:
try:
from OpenSSL import SSL
ctx = SSL.Context(SSL.SSLv23_METHOD)
except ImportError:
raise util.Abort(_("SSL support is unavailable"))
ctx.use_privatekey_file(ssl_cert)
ctx.use_certificate_file(ssl_cert)
sock = socket.socket(self.address_family, self.socket_type)
self.socket = SSL.Connection(ctx, sock)
self.server_bind()
self.server_activate()
self.addr, self.port = self.socket.getsockname()[0:2]
self.prefix = prefix
self.fqaddr = socket.getfqdn(address)
class IPv6HTTPServer(MercurialHTTPServer):
address_family = getattr(socket, 'AF_INET6', None)
def __init__(self, *args, **kwargs):
if self.address_family is None:
raise error.RepoError(_('IPv6 is not available on this system'))
super(IPv6HTTPServer, self).__init__(*args, **kwargs)
if ssl_cert:
handler = _shgwebhandler
else:
handler = _hgwebhandler
# ugly hack due to python issue5853 (for threaded use)
import mimetypes; mimetypes.init()
try:
if use_ipv6:
return IPv6HTTPServer((address, port), handler)
else:
return MercurialHTTPServer((address, port), handler)
except socket.error, inst:
raise util.Abort(_("cannot start server at '%s:%d': %s")
% (address, port, inst.args[1]))
| gpl-2.0 |
yl565/statsmodels | statsmodels/examples/ex_scatter_ellipse.py | 39 | 1367 | '''example for grid of scatter plots with probability ellipses
Author: Josef Perktold
License: BSD-3
'''
from statsmodels.compat.python import lrange
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.graphics.plot_grids import scatter_ellipse
nvars = 6
mmean = np.arange(1.,nvars+1)/nvars * 1.5
rho = 0.5
#dcorr = rho*np.ones((nvars, nvars)) + (1-rho)*np.eye(nvars)
r = np.random.uniform(-0.99, 0.99, size=(nvars, nvars))
##from scipy import stats
##r = stats.rdist.rvs(1, size=(nvars, nvars))
r = (r + r.T) / 2.
assert np.allclose(r, r.T)
mcorr = r
mcorr[lrange(nvars), lrange(nvars)] = 1
#dcorr = np.array([[1, 0.5, 0.1],[0.5, 1, -0.2], [0.1, -0.2, 1]])
mstd = np.arange(1.,nvars+1)/nvars
mcov = mcorr * np.outer(mstd, mstd)
evals = np.linalg.eigvalsh(mcov)
assert evals.min > 0 #assert positive definite
nobs = 100
data = np.random.multivariate_normal(mmean, mcov, size=nobs)
dmean = data.mean(0)
dcov = np.cov(data, rowvar=0)
print(dmean)
print(dcov)
dcorr = np.corrcoef(data, rowvar=0)
dcorr[np.triu_indices(nvars)] = 0
print(dcorr)
#default
#fig = scatter_ellipse(data, level=[0.5, 0.75, 0.95])
#used for checking
#fig = scatter_ellipse(data, level=[0.5, 0.75, 0.95], add_titles=True, keep_ticks=True)
#check varnames
varnames = ['var%d' % i for i in range(nvars)]
fig = scatter_ellipse(data, level=0.9, varnames=varnames)
plt.show()
| bsd-3-clause |
spbguru/repo1 | tests/integration/py2/nupic/opf/prediction_metrics_manager_test.py | 17 | 1272 | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# 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.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""This file invokes predictionmetricsmanager.py tests
TODO: Move these tests to unit test format.
"""
from nupic.frameworks.opf.predictionmetricsmanager import (
test as predictionMetricsManagerTest)
if __name__ == "__main__":
predictionMetricsManagerTest()
| gpl-3.0 |
jicruz/heroku-bot | lib/pycparser/_ast_gen.py | 22 | 8675 | #-----------------------------------------------------------------
# _ast_gen.py
#
# Generates the AST Node classes from a specification given in
# a configuration file
#
# The design of this module was inspired by astgen.py from the
# Python 2.5 code-base.
#
# Eli Bendersky [http://eli.thegreenplace.net]
# License: BSD
#-----------------------------------------------------------------
import pprint
from string import Template
class ASTCodeGenerator(object):
def __init__(self, cfg_filename='_c_ast.cfg'):
""" Initialize the code generator from a configuration
file.
"""
self.cfg_filename = cfg_filename
self.node_cfg = [NodeCfg(name, contents)
for (name, contents) in self.parse_cfgfile(cfg_filename)]
def generate(self, file=None):
""" Generates the code into file, an open file buffer.
"""
src = Template(_PROLOGUE_COMMENT).substitute(
cfg_filename=self.cfg_filename)
src += _PROLOGUE_CODE
for node_cfg in self.node_cfg:
src += node_cfg.generate_source() + '\n\n'
file.write(src)
def parse_cfgfile(self, filename):
""" Parse the configuration file and yield pairs of
(name, contents) for each node.
"""
with open(filename, "r") as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
colon_i = line.find(':')
lbracket_i = line.find('[')
rbracket_i = line.find(']')
if colon_i < 1 or lbracket_i <= colon_i or rbracket_i <= lbracket_i:
raise RuntimeError("Invalid line in %s:\n%s\n" % (filename, line))
name = line[:colon_i]
val = line[lbracket_i + 1:rbracket_i]
vallist = [v.strip() for v in val.split(',')] if val else []
yield name, vallist
class NodeCfg(object):
""" Node configuration.
name: node name
contents: a list of contents - attributes and child nodes
See comment at the top of the configuration file for details.
"""
def __init__(self, name, contents):
self.name = name
self.all_entries = []
self.attr = []
self.child = []
self.seq_child = []
for entry in contents:
clean_entry = entry.rstrip('*')
self.all_entries.append(clean_entry)
if entry.endswith('**'):
self.seq_child.append(clean_entry)
elif entry.endswith('*'):
self.child.append(clean_entry)
else:
self.attr.append(entry)
def generate_source(self):
src = self._gen_init()
src += '\n' + self._gen_children()
src += '\n' + self._gen_attr_names()
return src
def _gen_init(self):
src = "class %s(Node):\n" % self.name
if self.all_entries:
args = ', '.join(self.all_entries)
slots = ', '.join("'{0}'".format(e) for e in self.all_entries)
slots += ", 'coord', '__weakref__'"
arglist = '(self, %s, coord=None)' % args
else:
slots = "'coord', '__weakref__'"
arglist = '(self, coord=None)'
src += " __slots__ = (%s)\n" % slots
src += " def __init__%s:\n" % arglist
for name in self.all_entries + ['coord']:
src += " self.%s = %s\n" % (name, name)
return src
def _gen_children(self):
src = ' def children(self):\n'
if self.all_entries:
src += ' nodelist = []\n'
for child in self.child:
src += (
' if self.%(child)s is not None:' +
' nodelist.append(("%(child)s", self.%(child)s))\n') % (
dict(child=child))
for seq_child in self.seq_child:
src += (
' for i, child in enumerate(self.%(child)s or []):\n'
' nodelist.append(("%(child)s[%%d]" %% i, child))\n') % (
dict(child=seq_child))
src += ' return tuple(nodelist)\n'
else:
src += ' return ()\n'
return src
def _gen_attr_names(self):
src = " attr_names = (" + ''.join("%r, " % nm for nm in self.attr) + ')'
return src
_PROLOGUE_COMMENT = \
r'''#-----------------------------------------------------------------
# ** ATTENTION **
# This code was automatically generated from the file:
# $cfg_filename
#
# Do not modify it directly. Modify the configuration file and
# run the generator again.
# ** ** *** ** **
#
# pycparser: c_ast.py
#
# AST Node classes.
#
# Eli Bendersky [http://eli.thegreenplace.net]
# License: BSD
#-----------------------------------------------------------------
'''
_PROLOGUE_CODE = r'''
import sys
class Node(object):
__slots__ = ()
""" Abstract base class for AST nodes.
"""
def children(self):
""" A sequence of all children that are Nodes
"""
pass
def show(self, buf=sys.stdout, offset=0, attrnames=False, nodenames=False, showcoord=False, _my_node_name=None):
""" Pretty print the Node and all its attributes and
children (recursively) to a buffer.
buf:
Open IO buffer into which the Node is printed.
offset:
Initial offset (amount of leading spaces)
attrnames:
True if you want to see the attribute names in
name=value pairs. False to only see the values.
nodenames:
True if you want to see the actual node names
within their parents.
showcoord:
Do you want the coordinates of each Node to be
displayed.
"""
lead = ' ' * offset
if nodenames and _my_node_name is not None:
buf.write(lead + self.__class__.__name__+ ' <' + _my_node_name + '>: ')
else:
buf.write(lead + self.__class__.__name__+ ': ')
if self.attr_names:
if attrnames:
nvlist = [(n, getattr(self,n)) for n in self.attr_names]
attrstr = ', '.join('%s=%s' % nv for nv in nvlist)
else:
vlist = [getattr(self, n) for n in self.attr_names]
attrstr = ', '.join('%s' % v for v in vlist)
buf.write(attrstr)
if showcoord:
buf.write(' (at %s)' % self.coord)
buf.write('\n')
for (child_name, child) in self.children():
child.show(
buf,
offset=offset + 2,
attrnames=attrnames,
nodenames=nodenames,
showcoord=showcoord,
_my_node_name=child_name)
class NodeVisitor(object):
""" A base NodeVisitor class for visiting c_ast nodes.
Subclass it and define your own visit_XXX methods, where
XXX is the class name you want to visit with these
methods.
For example:
class ConstantVisitor(NodeVisitor):
def __init__(self):
self.values = []
def visit_Constant(self, node):
self.values.append(node.value)
Creates a list of values of all the constant nodes
encountered below the given node. To use it:
cv = ConstantVisitor()
cv.visit(node)
Notes:
* generic_visit() will be called for AST nodes for which
no visit_XXX method was defined.
* The children of nodes for which a visit_XXX was
defined will not be visited - if you need this, call
generic_visit() on the node.
You can use:
NodeVisitor.generic_visit(self, node)
* Modeled after Python's own AST visiting facilities
(the ast module of Python 3.0)
"""
def visit(self, node):
""" Visit a node.
"""
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
return visitor(node)
def generic_visit(self, node):
""" Called if no explicit visitor function exists for a
node. Implements preorder visiting of the node.
"""
for c_name, c in node.children():
self.visit(c)
'''
if __name__ == "__main__":
import sys
ast_gen = ASTCodeGenerator('_c_ast.cfg')
ast_gen.generate(open('c_ast.py', 'w'))
| gpl-3.0 |
ahmedaljazzar/edx-platform | common/lib/xmodule/xmodule/modulestore/tests/test_store_utilities.py | 4 | 2056 | """
Tests for store_utilities.py
"""
import unittest
from mock import Mock
import ddt
from xmodule.modulestore.store_utilities import (
get_draft_subtree_roots, draft_node_constructor
)
@ddt.ddt
class TestUtils(unittest.TestCase):
"""
Tests for store_utilities
ASCII trees for ONLY_ROOTS and SOME_TREES:
ONLY_ROOTS:
1)
vertical (not draft)
|
url1
2)
sequential (not draft)
|
url2
SOME_TREES:
1)
sequential_1 (not draft)
|
vertical_1
/ \
/ \
child_1 child_2
2)
great_grandparent_vertical (not draft)
|
grandparent_vertical
|
vertical_2
/ \
/ \
child_3 child_4
"""
shard = 2
ONLY_ROOTS = [
('url1', 'vertical'),
('url2', 'sequential'),
]
ONLY_ROOTS_URLS = ['url1', 'url2']
SOME_TREES = [
('child_1', 'vertical_1'),
('child_2', 'vertical_1'),
('vertical_1', 'sequential_1'),
('child_3', 'vertical_2'),
('child_4', 'vertical_2'),
('vertical_2', 'grandparent_vertical'),
('grandparent_vertical', 'great_grandparent_vertical'),
]
SOME_TREES_ROOTS_URLS = ['vertical_1', 'grandparent_vertical']
@ddt.data(
(ONLY_ROOTS, ONLY_ROOTS_URLS),
(SOME_TREES, SOME_TREES_ROOTS_URLS),
)
@ddt.unpack
def test_get_draft_subtree_roots(self, node_arguments_list, expected_roots_urls):
"""tests for get_draft_subtree_roots"""
module_nodes = []
for node_args in node_arguments_list:
module_nodes.append(draft_node_constructor(Mock(), node_args[0], node_args[1]))
subtree_roots_urls = [root.url for root in get_draft_subtree_roots(module_nodes)]
# check that we return the expected urls
self.assertEqual(set(subtree_roots_urls), set(expected_roots_urls))
| agpl-3.0 |
tinchoss/Python_Android | python/gdata/src/gdata/tlslite/X509CertChain.py | 45 | 6681 | """Class representing an X.509 certificate chain."""
from utils import cryptomath
class X509CertChain:
"""This class represents a chain of X.509 certificates.
@type x509List: list
@ivar x509List: A list of L{tlslite.X509.X509} instances,
starting with the end-entity certificate and with every
subsequent certificate certifying the previous.
"""
def __init__(self, x509List=None):
"""Create a new X509CertChain.
@type x509List: list
@param x509List: A list of L{tlslite.X509.X509} instances,
starting with the end-entity certificate and with every
subsequent certificate certifying the previous.
"""
if x509List:
self.x509List = x509List
else:
self.x509List = []
def getNumCerts(self):
"""Get the number of certificates in this chain.
@rtype: int
"""
return len(self.x509List)
def getEndEntityPublicKey(self):
"""Get the public key from the end-entity certificate.
@rtype: L{tlslite.utils.RSAKey.RSAKey}
"""
if self.getNumCerts() == 0:
raise AssertionError()
return self.x509List[0].publicKey
def getFingerprint(self):
"""Get the hex-encoded fingerprint of the end-entity certificate.
@rtype: str
@return: A hex-encoded fingerprint.
"""
if self.getNumCerts() == 0:
raise AssertionError()
return self.x509List[0].getFingerprint()
def getCommonName(self):
"""Get the Subject's Common Name from the end-entity certificate.
The cryptlib_py module must be installed in order to use this
function.
@rtype: str or None
@return: The CN component of the certificate's subject DN, if
present.
"""
if self.getNumCerts() == 0:
raise AssertionError()
return self.x509List[0].getCommonName()
def validate(self, x509TrustList):
"""Check the validity of the certificate chain.
This checks that every certificate in the chain validates with
the subsequent one, until some certificate validates with (or
is identical to) one of the passed-in root certificates.
The cryptlib_py module must be installed in order to use this
function.
@type x509TrustList: list of L{tlslite.X509.X509}
@param x509TrustList: A list of trusted root certificates. The
certificate chain must extend to one of these certificates to
be considered valid.
"""
import cryptlib_py
c1 = None
c2 = None
lastC = None
rootC = None
try:
rootFingerprints = [c.getFingerprint() for c in x509TrustList]
#Check that every certificate in the chain validates with the
#next one
for cert1, cert2 in zip(self.x509List, self.x509List[1:]):
#If we come upon a root certificate, we're done.
if cert1.getFingerprint() in rootFingerprints:
return True
c1 = cryptlib_py.cryptImportCert(cert1.writeBytes(),
cryptlib_py.CRYPT_UNUSED)
c2 = cryptlib_py.cryptImportCert(cert2.writeBytes(),
cryptlib_py.CRYPT_UNUSED)
try:
cryptlib_py.cryptCheckCert(c1, c2)
except:
return False
cryptlib_py.cryptDestroyCert(c1)
c1 = None
cryptlib_py.cryptDestroyCert(c2)
c2 = None
#If the last certificate is one of the root certificates, we're
#done.
if self.x509List[-1].getFingerprint() in rootFingerprints:
return True
#Otherwise, find a root certificate that the last certificate
#chains to, and validate them.
lastC = cryptlib_py.cryptImportCert(self.x509List[-1].writeBytes(),
cryptlib_py.CRYPT_UNUSED)
for rootCert in x509TrustList:
rootC = cryptlib_py.cryptImportCert(rootCert.writeBytes(),
cryptlib_py.CRYPT_UNUSED)
if self._checkChaining(lastC, rootC):
try:
cryptlib_py.cryptCheckCert(lastC, rootC)
return True
except:
return False
return False
finally:
if not (c1 is None):
cryptlib_py.cryptDestroyCert(c1)
if not (c2 is None):
cryptlib_py.cryptDestroyCert(c2)
if not (lastC is None):
cryptlib_py.cryptDestroyCert(lastC)
if not (rootC is None):
cryptlib_py.cryptDestroyCert(rootC)
def _checkChaining(self, lastC, rootC):
import cryptlib_py
import array
def compareNames(name):
try:
length = cryptlib_py.cryptGetAttributeString(lastC, name, None)
lastName = array.array('B', [0] * length)
cryptlib_py.cryptGetAttributeString(lastC, name, lastName)
lastName = lastName.tostring()
except cryptlib_py.CryptException, e:
if e[0] == cryptlib_py.CRYPT_ERROR_NOTFOUND:
lastName = None
try:
length = cryptlib_py.cryptGetAttributeString(rootC, name, None)
rootName = array.array('B', [0] * length)
cryptlib_py.cryptGetAttributeString(rootC, name, rootName)
rootName = rootName.tostring()
except cryptlib_py.CryptException, e:
if e[0] == cryptlib_py.CRYPT_ERROR_NOTFOUND:
rootName = None
return lastName == rootName
cryptlib_py.cryptSetAttribute(lastC,
cryptlib_py.CRYPT_CERTINFO_ISSUERNAME,
cryptlib_py.CRYPT_UNUSED)
if not compareNames(cryptlib_py.CRYPT_CERTINFO_COUNTRYNAME):
return False
if not compareNames(cryptlib_py.CRYPT_CERTINFO_LOCALITYNAME):
return False
if not compareNames(cryptlib_py.CRYPT_CERTINFO_ORGANIZATIONNAME):
return False
if not compareNames(cryptlib_py.CRYPT_CERTINFO_ORGANIZATIONALUNITNAME):
return False
if not compareNames(cryptlib_py.CRYPT_CERTINFO_COMMONNAME):
return False
return True | apache-2.0 |
rsvip/Django | tests/auth_tests/test_templates.py | 328 | 2785 | from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.contrib.auth.views import (
password_change, password_change_done, password_reset,
password_reset_complete, password_reset_confirm, password_reset_done,
)
from django.test import RequestFactory, TestCase, override_settings
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode
@override_settings(
PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='auth_tests.urls',
)
class AuthTemplateTests(TestCase):
def test_titles(self):
rf = RequestFactory()
user = User.objects.create_user('jsmith', 'jsmith@example.com', 'pass')
user = authenticate(username=user.username, password='pass')
request = rf.get('/somepath/')
request.user = user
response = password_reset(request, post_reset_redirect='dummy/')
self.assertContains(response, '<title>Password reset</title>')
self.assertContains(response, '<h1>Password reset</h1>')
response = password_reset_done(request)
self.assertContains(response, '<title>Password reset sent</title>')
self.assertContains(response, '<h1>Password reset sent</h1>')
# password_reset_confirm invalid token
response = password_reset_confirm(request, uidb64='Bad', token='Bad', post_reset_redirect='dummy/')
self.assertContains(response, '<title>Password reset unsuccessful</title>')
self.assertContains(response, '<h1>Password reset unsuccessful</h1>')
# password_reset_confirm valid token
default_token_generator = PasswordResetTokenGenerator()
token = default_token_generator.make_token(user)
uidb64 = force_text(urlsafe_base64_encode(force_bytes(user.pk)))
response = password_reset_confirm(request, uidb64, token, post_reset_redirect='dummy/')
self.assertContains(response, '<title>Enter new password</title>')
self.assertContains(response, '<h1>Enter new password</h1>')
response = password_reset_complete(request)
self.assertContains(response, '<title>Password reset complete</title>')
self.assertContains(response, '<h1>Password reset complete</h1>')
response = password_change(request, post_change_redirect='dummy/')
self.assertContains(response, '<title>Password change</title>')
self.assertContains(response, '<h1>Password change</h1>')
response = password_change_done(request)
self.assertContains(response, '<title>Password change successful</title>')
self.assertContains(response, '<h1>Password change successful</h1>')
| bsd-3-clause |
python-rope/rope | rope/refactor/introduce_factory.py | 3 | 6188 | import rope.base.exceptions
import rope.base.pyobjects
from rope.base import libutils
from rope.base import taskhandle, evaluate
from rope.base.change import (ChangeSet, ChangeContents)
from rope.refactor import rename, occurrences, sourceutils, importutils
class IntroduceFactory(object):
def __init__(self, project, resource, offset):
self.project = project
self.offset = offset
this_pymodule = self.project.get_pymodule(resource)
self.old_pyname = evaluate.eval_location(this_pymodule, offset)
if self.old_pyname is None or \
not isinstance(self.old_pyname.get_object(),
rope.base.pyobjects.PyClass):
raise rope.base.exceptions.RefactoringError(
'Introduce factory should be performed on a class.')
self.old_name = self.old_pyname.get_object().get_name()
self.pymodule = self.old_pyname.get_object().get_module()
self.resource = self.pymodule.get_resource()
def get_changes(self, factory_name, global_factory=False, resources=None,
task_handle=taskhandle.NullTaskHandle()):
"""Get the changes this refactoring makes
`factory_name` indicates the name of the factory function to
be added. If `global_factory` is `True` the factory will be
global otherwise a static method is added to the class.
`resources` can be a list of `rope.base.resource.File` that
this refactoring should be applied on; if `None` all python
files in the project are searched.
"""
if resources is None:
resources = self.project.get_python_files()
changes = ChangeSet('Introduce factory method <%s>' % factory_name)
job_set = task_handle.create_jobset('Collecting Changes',
len(resources))
self._change_module(resources, changes, factory_name,
global_factory, job_set)
return changes
def get_name(self):
"""Return the name of the class"""
return self.old_name
def _change_module(self, resources, changes,
factory_name, global_, job_set):
if global_:
replacement = '__rope_factory_%s_' % factory_name
else:
replacement = self._new_function_name(factory_name, global_)
for file_ in resources:
job_set.started_job(file_.path)
if file_ == self.resource:
self._change_resource(changes, factory_name, global_)
job_set.finished_job()
continue
changed_code = self._rename_occurrences(file_, replacement,
global_)
if changed_code is not None:
if global_:
new_pymodule = libutils.get_string_module(
self.project, changed_code, self.resource)
modname = libutils.modname(self.resource)
changed_code, imported = importutils.add_import(
self.project, new_pymodule, modname, factory_name)
changed_code = changed_code.replace(replacement, imported)
changes.add_change(ChangeContents(file_, changed_code))
job_set.finished_job()
def _change_resource(self, changes, factory_name, global_):
class_scope = self.old_pyname.get_object().get_scope()
source_code = self._rename_occurrences(
self.resource, self._new_function_name(factory_name,
global_), global_)
if source_code is None:
source_code = self.pymodule.source_code
else:
self.pymodule = libutils.get_string_module(
self.project, source_code, resource=self.resource)
lines = self.pymodule.lines
start = self._get_insertion_offset(class_scope, lines)
result = source_code[:start]
result += self._get_factory_method(lines, class_scope,
factory_name, global_)
result += source_code[start:]
changes.add_change(ChangeContents(self.resource, result))
def _get_insertion_offset(self, class_scope, lines):
start_line = class_scope.get_end()
if class_scope.get_scopes():
start_line = class_scope.get_scopes()[-1].get_end()
start = lines.get_line_end(start_line) + 1
return start
def _get_factory_method(self, lines, class_scope,
factory_name, global_):
unit_indents = ' ' * sourceutils.get_indent(self.project)
if global_:
if self._get_scope_indents(lines, class_scope) > 0:
raise rope.base.exceptions.RefactoringError(
'Cannot make global factory method for nested classes.')
return ('\ndef %s(*args, **kwds):\n%sreturn %s(*args, **kwds)\n' %
(factory_name, unit_indents, self.old_name))
unindented_factory = \
('@staticmethod\ndef %s(*args, **kwds):\n' % factory_name +
'%sreturn %s(*args, **kwds)\n' % (unit_indents, self.old_name))
indents = self._get_scope_indents(lines, class_scope) + \
sourceutils.get_indent(self.project)
return '\n' + sourceutils.indent_lines(unindented_factory, indents)
def _get_scope_indents(self, lines, scope):
return sourceutils.get_indents(lines, scope.get_start())
def _new_function_name(self, factory_name, global_):
if global_:
return factory_name
else:
return self.old_name + '.' + factory_name
def _rename_occurrences(self, file_, changed_name, global_factory):
finder = occurrences.create_finder(self.project, self.old_name,
self.old_pyname, only_calls=True)
result = rename.rename_in_module(finder, changed_name, resource=file_,
replace_primary=global_factory)
return result
IntroduceFactoryRefactoring = IntroduceFactory
| lgpl-3.0 |
benjixx/ansible | lib/ansible/utils/module_docs_fragments/backup.py | 427 | 1071 | # Copyright (c) 2015 Ansible, 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/>.
class ModuleDocFragment(object):
# Standard documentation fragment
DOCUMENTATION = '''
options:
backup:
description:
- Create a backup file including the timestamp information so you can get
the original file back if you somehow clobbered it incorrectly.
required: false
choices: [ "yes", "no" ]
default: "no"
'''
| gpl-3.0 |
UITools/saleor | saleor/shipping/migrations/0013_auto_20180822_0721.py | 1 | 4293 | # Generated by Django 2.0.3 on 2018-08-22 12:20
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django_countries.fields
import django_measurement.models
import django_prices.models
import saleor.core.weight
class Migration(migrations.Migration):
dependencies = [
('checkout', '0010_auto_20180822_0720'),
('order', '0052_auto_20180822_0720'),
('shipping', '0012_remove_legacy_shipping_methods'),
]
operations = [
migrations.CreateModel(
name='ShippingMethodTranslation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('language_code', models.CharField(max_length=10)),
('name', models.CharField(blank=True, max_length=255, null=True)),
],
),
migrations.CreateModel(
name='ShippingZone',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('countries', django_countries.fields.CountryField(max_length=749, multiple=True)),
],
options={
'permissions': (('manage_shipping', 'Manage shipping.'),),
},
),
migrations.AlterUniqueTogether(
name='shippingmethodcountry',
unique_together=set(),
),
migrations.RemoveField(
model_name='shippingmethodcountry',
name='shipping_method',
),
migrations.AlterModelOptions(
name='shippingmethod',
options={},
),
migrations.RemoveField(
model_name='shippingmethod',
name='description',
),
migrations.AddField(
model_name='shippingmethod',
name='maximum_order_price',
field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True),
),
migrations.AddField(
model_name='shippingmethod',
name='maximum_order_weight',
field=django_measurement.models.MeasurementField(blank=True, measurement_class='Mass', null=True),
),
migrations.AddField(
model_name='shippingmethod',
name='minimum_order_price',
field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, default=0, max_digits=12, null=True),
),
migrations.AddField(
model_name='shippingmethod',
name='minimum_order_weight',
field=django_measurement.models.MeasurementField(blank=True, default=saleor.core.weight.zero_weight, measurement_class='Mass', null=True),
),
migrations.AddField(
model_name='shippingmethod',
name='price',
field=django_prices.models.MoneyField(currency=settings.DEFAULT_CURRENCY, decimal_places=2, default=0, max_digits=12),
),
migrations.AddField(
model_name='shippingmethod',
name='type',
field=models.CharField(choices=[('price', 'Price based shipping'), ('weight', 'Weight based shipping')], default=None, max_length=30),
preserve_default=False,
),
migrations.DeleteModel(
name='ShippingMethodCountry',
),
migrations.AddField(
model_name='shippingmethodtranslation',
name='shipping_method',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='translations', to='shipping.ShippingMethod'),
),
migrations.AddField(
model_name='shippingmethod',
name='shipping_zone',
field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, related_name='shipping_methods', to='shipping.ShippingZone'),
preserve_default=False,
),
migrations.AlterUniqueTogether(
name='shippingmethodtranslation',
unique_together={('language_code', 'shipping_method')},
),
]
| bsd-3-clause |
arborh/tensorflow | tensorflow/python/kernel_tests/losses_test.py | 9 | 66662 | # 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.
# ==============================================================================
"""Tests for losses."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.ops.losses import losses
from tensorflow.python.ops.losses import util
from tensorflow.python.platform import test
from tensorflow.python.training import momentum as momentum_lib
@test_util.run_deprecated_v1
class AbsoluteDifferenceLossTest(test.TestCase):
def setUp(self):
super(AbsoluteDifferenceLossTest, self).setUp()
self._predictions = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
self._labels = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
def testValueErrorThrownWhenWeightIsNone(self):
with self.cached_session():
with self.assertRaises(ValueError):
losses.absolute_difference(
self._predictions, self._predictions, weights=None)
def testAllCorrectNoLossWeight(self):
loss = losses.absolute_difference(self._predictions, self._predictions)
with self.cached_session():
self.assertAlmostEqual(0.0, self.evaluate(loss), 3)
def testNonZeroLoss(self):
loss = losses.absolute_difference(self._labels, self._predictions)
with self.cached_session():
self.assertAlmostEqual(5.5, self.evaluate(loss), 3)
def testNonZeroLossWithPythonScalarWeight(self):
weights = 2.3
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(5.5 * weights, self.evaluate(loss), 3)
def testNonZeroLossWithScalarTensorWeight(self):
weights = 2.3
loss = losses.absolute_difference(self._labels, self._predictions,
constant_op.constant(weights))
with self.cached_session():
self.assertAlmostEqual(5.5 * weights, self.evaluate(loss), 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
weights = constant_op.constant((1.2, 0.0), shape=(2, 1))
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(5.6, self.evaluate(loss), 3)
def testNonZeroLossWithTwoDimBatchSpecificWeights(self):
weights = constant_op.constant([1.2, 0.0], shape=[2, 1])
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(5.6, self.evaluate(loss), 3)
def testNonZeroLossWithSampleSpecificWeights(self):
weights = constant_op.constant([3, 6, 5, 0, 4, 2], shape=[2, 3])
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(16.6, self.evaluate(loss), 3)
def testNonZeroLossWithSampleSpecificWeightsMostZero(self):
weights = constant_op.constant([0, 0, 0, 0, 0, 2], shape=[2, 3])
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(6.0, self.evaluate(loss), 3)
def testLossWithSampleSpecificWeightsAllZero(self):
weights = array_ops.zeros((2, 3))
loss = losses.absolute_difference(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(0.0, self.evaluate(loss), 3)
@test_util.assert_no_new_pyobjects_executing_eagerly
def testEagerNoMemoryLeaked(self):
# This is a somewhat convoluted way of testing that nothing gets added to
# a global collection.
predictions = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
labels = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
losses.absolute_difference(labels, predictions)
class SoftmaxCrossEntropyLossTest(test.TestCase):
def testNoneWeightRaisesValueError(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
with self.cached_session():
with self.assertRaises(ValueError):
losses.softmax_cross_entropy(labels, logits, weights=None)
@test_util.run_deprecated_v1
def testAllCorrect(self):
with self.cached_session():
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
loss = losses.softmax_cross_entropy(labels, logits)
self.assertEquals('softmax_cross_entropy_loss/value', loss.op.name)
self.assertAlmostEqual(loss.eval(), 0.0, 3)
@test_util.run_deprecated_v1
def testAllWrong(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
with self.cached_session():
loss = losses.softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 10.0, 3)
@test_util.run_deprecated_v1
def testNonZeroLossWithPythonScalarWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = 2.3
with self.cached_session():
loss = losses.softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(weights * 10.0, self.evaluate(loss), 3)
@test_util.run_deprecated_v1
def testNonZeroLossWithScalarTensorWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = 2.3
with self.cached_session():
loss = losses.softmax_cross_entropy(labels, logits,
constant_op.constant(weights))
self.assertAlmostEqual(weights * 10.0, self.evaluate(loss), 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = constant_op.constant((1.2, 3.4, 5.6))
with self.cached_session():
loss = losses.softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0,
self.evaluate(loss), 3)
def testAllWrongAllWeightsMissing(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = constant_op.constant([0, 0, 0], shape=[3])
with self.cached_session():
loss = losses.softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(0.0, self.evaluate(loss), 3)
def testSomeWeightsMissing(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = constant_op.constant([1.2, 0, 0], shape=[3])
with self.cached_session():
loss = losses.softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(12.0, self.evaluate(loss), 3)
def testSoftmaxWithMeasurementSpecificWeightsRaisesException(self):
with self.cached_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
weights = constant_op.constant([[3, 4, 5], [2, 6, 0], [8, 0, 1]])
with self.assertRaises(ValueError):
losses.softmax_cross_entropy(labels, logits, weights=weights).eval()
@test_util.run_deprecated_v1
def testSoftmaxLabelSmoothing(self):
with self.cached_session():
# Softmax Cross Entropy Loss is:
# -\sum_i p_i \log q_i
# where for a softmax activation
# \log q_i = x_i - \log \sum_j \exp x_j
# = x_i - x_max - \log \sum_j \exp (x_j - x_max)
# For our activations, [100, -100, -100] the log partition function
# becomes \log ( exp(0) + exp(-200) + exp(-200) ) = 0
# so our log softmaxes become: [0, -200, -200]
# so our cross entropy loss is:
# -(1 - L + L/n) * 0 + 400 * L/n = 400 L/n
logits = constant_op.constant([[100.0, -100.0, -100.0]])
labels = constant_op.constant([[1, 0, 0]])
label_smoothing = 0.1
loss = losses.softmax_cross_entropy(
labels, logits, label_smoothing=label_smoothing)
self.assertEquals(loss.op.name, 'softmax_cross_entropy_loss/value')
expected_value = 400.0 * label_smoothing / 3.0
self.assertAlmostEqual(loss.eval(), expected_value, 3)
class SparseSoftmaxCrossEntropyLossTest(test.TestCase):
def testNoneWeightRaisesValueError(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0], [1], [2]])
with self.cached_session():
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(labels, logits, weights=None)
@test_util.run_deprecated_v1
def testAllCorrectInt32Labels(self):
with self.cached_session():
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0], [1], [2]], dtype=dtypes.int32)
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 0.0, 3)
@test_util.assert_no_new_pyobjects_executing_eagerly
def testEagerNoMemoryLeaked(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0], [1], [2]], dtype=dtypes.int32)
losses.sparse_softmax_cross_entropy(labels, logits)
@test_util.run_deprecated_v1
def testAllCorrectInt64Labels(self):
with self.cached_session():
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[0], [1], [2]], dtype=dtypes.int64)
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 0.0, 3)
@test_util.run_deprecated_v1
def testAllCorrectNonColumnLabels(self):
with self.cached_session():
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([0, 1, 2])
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 0.0, 3)
@test_util.run_deprecated_v1
def testAllWrongInt32Labels(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]], dtype=dtypes.int32)
with self.cached_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 10.0, 3)
@test_util.run_deprecated_v1
def testAllWrongInt64Labels(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]], dtype=dtypes.int64)
with self.cached_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 10.0, 3)
@test_util.run_deprecated_v1
def testAllWrongNonColumnLabels(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([2, 0, 1])
with self.cached_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits)
self.assertEquals(loss.op.name, 'sparse_softmax_cross_entropy_loss/value')
self.assertAlmostEqual(loss.eval(), 10.0, 3)
@test_util.run_deprecated_v1
def testNonZeroLossWithPythonScalarWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = 2.3
with self.cached_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(weights * 10.0, self.evaluate(loss), 3)
@test_util.run_deprecated_v1
def testNonZeroLossWithScalarTensorWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = 2.3
with self.cached_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits,
constant_op.constant(weights))
self.assertAlmostEqual(weights * 10.0, self.evaluate(loss), 3)
def testNonZeroLossWith1DTensorWeight(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = 2.3
with self.cached_session():
loss = losses.sparse_softmax_cross_entropy(
labels, logits, constant_op.constant((weights,)))
self.assertAlmostEqual(weights * 10.0, self.evaluate(loss), 3)
@test_util.run_deprecated_v1
def testNonZeroLossWithPlaceholderForWeights(self):
logits = constant_op.constant([[10.0, 0.0, 0.0],
[0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = array_ops.placeholder(dtypes.float32)
with self.cached_session() as sess:
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
loss_val = sess.run(loss,
feed_dict={weights: ((1.2,), (3.4,), (5.6,))})
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, loss_val, 3)
@test_util.run_deprecated_v1
def testUnknownShapePlaceholderForLogitsLabelsButScalarWeights(self):
logits = array_ops.placeholder(dtypes.float32)
labels = array_ops.placeholder(dtypes.int32)
weights = 1.0
with self.cached_session() as sess:
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
loss_val = sess.run(loss,
feed_dict={
logits: [[10.0, 0.0, 0.0],
[0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]],
labels: [[2], [0], [1]],
})
self.assertAlmostEqual((1.0 + 1.0 + 1.0) * 10.0 / 3.0, loss_val, 3)
@test_util.run_deprecated_v1
def testNonZeroLossWithPlaceholderForLogitsLabelsAndWeights(self):
logits = array_ops.placeholder(dtypes.float32, shape=(None, 3))
labels = array_ops.placeholder(dtypes.int32, shape=(None, 1))
weights = array_ops.placeholder(dtypes.float32)
with self.cached_session() as sess:
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
loss_val = sess.run(loss,
feed_dict={
logits: [[10.0, 0.0, 0.0],
[0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]],
labels: [[2], [0], [1]],
weights: ((1.2,), (3.4,), (5.6,)),
})
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0, loss_val, 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = constant_op.constant([1.2, 3.4, 5.6], shape=(3, 1))
with self.cached_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0,
self.evaluate(loss), 3)
def testNonZeroLossWithColumnWeights(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = constant_op.constant([[1.2], [3.4], [5.6]])
with self.cached_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual((1.2 + 3.4 + 5.6) * 10.0 / 3.0,
self.evaluate(loss), 3)
def testAllWrongAllWeightsMissing(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = constant_op.constant([0, 0, 0], shape=(3, 1))
with self.cached_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(0.0, self.evaluate(loss), 3)
def testSomeWeightsMissing(self):
logits = constant_op.constant([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0],
[0.0, 0.0, 10.0]])
labels = constant_op.constant([[2], [0], [1]])
weights = constant_op.constant([1.2, 0, 0], shape=(3, 1))
with self.cached_session():
loss = losses.sparse_softmax_cross_entropy(labels, logits, weights)
self.assertAlmostEqual(12.0, self.evaluate(loss), 3)
@test_util.run_deprecated_v1
def testMeasurementSpecificWeightsRaisesException(self):
with self.cached_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0], [1], [2]])
weights = constant_op.constant([[3, 4, 5], [2, 6, 0], [8, 0, 1]])
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
def testInconsistentWeightSizeRaisesException(self):
"""The weight tensor has incorrect number of elements."""
with self.cached_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0], [1], [2]])
weights = constant_op.constant([1.2, 3.4, 5.6, 7.8])
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
def testInconsistentLabelSizeRaisesException(self):
"""The label tensor has incorrect number of elements."""
with self.cached_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0], [1], [2], [3]])
weights = constant_op.constant([1.2, 3.4, 5.6])
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
@test_util.run_deprecated_v1
def testInconsistentWeightShapeRaisesException(self):
"""The weight tensor has incorrect shape."""
with self.cached_session():
logits = constant_op.constant([[100.0, -100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0, -100.0],
[-100.0, -100.0, 100.0, -100.0],
[-100.0, -100.0, -100.0, 100.0]])
labels = constant_op.constant([[0], [1], [2], [3]])
weights = constant_op.constant([[1.2, 3.4], [5.6, 7.8]])
with self.assertRaises(ValueError):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
@test_util.run_deprecated_v1
def testInconsistentLabelShapeRaisesException(self):
"""The label tensor has incorrect shape."""
with self.cached_session():
logits = constant_op.constant([[100.0, -100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0, -100.0],
[-100.0, -100.0, 100.0, -100.0],
[-100.0, -100.0, -100.0, 100.0]])
labels = constant_op.constant([[0, 1], [2, 3]])
weights = constant_op.constant(1.2)
with self.assertRaisesRegexp(ValueError, 'mismatch'):
losses.sparse_softmax_cross_entropy(
labels, logits, weights=weights).eval()
class SigmoidCrossEntropyLossTest(test.TestCase):
@test_util.run_deprecated_v1
def testAllCorrectSigmoid(self):
with self.cached_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
loss = losses.sigmoid_cross_entropy(labels, logits)
self.assertEquals(logits.dtype, loss.dtype)
self.assertEquals('sigmoid_cross_entropy_loss/value', loss.op.name)
self.assertAlmostEqual(0.0, self.evaluate(loss), 3)
@test_util.run_deprecated_v1
def testLossWithSingleDimPlaceholderForLogitsAndWeights1(self):
logits = array_ops.placeholder(dtypes.float32, shape=(None, 1))
labels = array_ops.placeholder(dtypes.float32, shape=(None, 1))
weights = array_ops.ones_like(logits, dtype=dtypes.float32)
loss = losses.sigmoid_cross_entropy(labels, logits, weights)
self.assertEquals(logits.dtype, loss.dtype)
with self.cached_session() as sess:
loss = sess.run(loss,
feed_dict={
logits: np.ones((32, 1)),
labels: np.ones((32, 1)),
})
self.assertAlmostEqual(0.313, loss, 3)
@test_util.run_deprecated_v1
def testLossWithSingleDimPlaceholderForLogitsAndWeights2(self):
logits = array_ops.placeholder(dtypes.float32, shape=(None, 2))
labels = array_ops.placeholder(dtypes.float32, shape=(None, 2))
weights = array_ops.ones_like(logits, dtype=dtypes.float32)
loss = losses.sigmoid_cross_entropy(labels, logits, weights)
self.assertEquals(logits.dtype, loss.dtype)
with self.cached_session() as sess:
loss = sess.run(loss,
feed_dict={
logits: np.ones((32, 2)),
labels: np.ones((32, 2)),
})
self.assertAlmostEqual(0.313, loss, 3)
@test_util.run_deprecated_v1
def testAllWrongSigmoid(self):
with self.cached_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
loss = losses.sigmoid_cross_entropy(labels, logits)
self.assertEquals(logits.dtype, loss.dtype)
self.assertEquals('sigmoid_cross_entropy_loss/value', loss.op.name)
self.assertAlmostEqual(loss.eval(), 600.0 / 9.0, 3)
@test_util.run_deprecated_v1
def testAllWrongSigmoidWithMeasurementSpecificWeights(self):
with self.cached_session():
logits = constant_op.constant([[100.0, -100.0, -100.0],
[-100.0, 100.0, -100.0],
[-100.0, -100.0, 100.0]])
labels = constant_op.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
weights = constant_op.constant([[3, 4, 5], [2, 6, 0], [8, 0, 1]])
loss = losses.sigmoid_cross_entropy(labels, logits, weights)
self.assertEquals(logits.dtype, loss.dtype)
self.assertEquals('sigmoid_cross_entropy_loss/value', loss.op.name)
self.assertAlmostEqual(1700.0 / 7.0, self.evaluate(loss), 3)
@test_util.run_deprecated_v1
def testMultiCorrectSigmoid(self):
logits = constant_op.constant([[100.0, -100.0, 100.0],
[100.0, 100.0, -100.0],
[-100.0, 100.0, 100.0]])
labels = constant_op.constant([[1, 0, 1], [1, 1, 0], [0, 1, 1]])
loss = losses.sigmoid_cross_entropy(labels, logits)
self.assertEquals(logits.dtype, loss.dtype)
self.assertEquals('sigmoid_cross_entropy_loss/value', loss.op.name)
with self.cached_session():
self.assertAlmostEqual(0.0, self.evaluate(loss), 3)
def testSigmoidFloat64(self):
logits = constant_op.constant((
(100.0, -100.0, 100.0),
(100.0, -100.0, 100.0),
(100.0, 100.0, -100.0)
), dtype=dtypes.float64)
labels = constant_op.constant((
(1, 0, 1), (1, 1, 0), (0, 1, 1)
), dtype=dtypes.int64)
loss = losses.sigmoid_cross_entropy(labels, logits)
self.assertEquals(logits.dtype, loss.dtype)
with self.cached_session():
self.assertAlmostEqual(44.444, self.evaluate(loss), 3)
def testSigmoidNoReduction(self):
logits = constant_op.constant((
(100.0, -100.0, 100.0),
(100.0, -100.0, 100.0),
(100.0, 100.0, -100.0)))
labels = constant_op.constant(((1, 0, 1), (1, 1, 0), (0, 1, 1)))
loss = losses.sigmoid_cross_entropy(
labels, logits, reduction=losses.Reduction.NONE)
self.assertEquals(logits.dtype, loss.dtype)
with self.cached_session():
self.assertAllClose(((0., 0., 0.), (0., 100., 100.), (100., 0., 100.)),
self.evaluate(loss), 3)
@test_util.run_deprecated_v1
def testSigmoidLabelSmoothingCorrect(self):
with self.cached_session():
logits = constant_op.constant([[100.0, -100.0, -100.0]])
labels = constant_op.constant([[1, 0, 1]])
# Sigmoid cross entropy loss is:
# max(x,0) - x*z + log(1 + exp(-abs(x)))
# The new labels are:
# z' = z * (1 - L) + 0.5 L
# 1 -> 1 - 0.5 L
# 0 -> 0.5 L
# here we expect:
# 1/3 * (100 - 100 * (1 - 0.5 L) + 0
# + 0 + 100 * (0.5 L) + 0
# + 0 + 100 * (1 - 0.5 L) + 0)
# = 1/3 * (100 + 50 L)
label_smoothing = 0.1
loss = losses.sigmoid_cross_entropy(
labels, logits, label_smoothing=label_smoothing)
self.assertEquals(logits.dtype, loss.dtype)
self.assertEquals('sigmoid_cross_entropy_loss/value', loss.op.name)
expected_value = (100.0 + 50.0 * label_smoothing) / 3.0
self.assertAlmostEqual(loss.eval(), expected_value, 3)
@test_util.run_deprecated_v1
def testSigmoidLabelSmoothingEqualsSoftmaxTwoLabel(self):
with self.cached_session():
label_smoothing = 0.1
sigmoid_logits = constant_op.constant([[100.0, -100.0, -100.0]])
sigmoid_labels = constant_op.constant([[1, 0, 1]])
sigmoid_loss = losses.sigmoid_cross_entropy(
sigmoid_labels, sigmoid_logits, label_smoothing=label_smoothing)
self.assertEquals(sigmoid_logits.dtype, sigmoid_loss.dtype)
softmax_logits = constant_op.constant(
[[0.0, 100.0], [100.0, 0.0], [100.0, 0.0]])
softmax_labels = constant_op.constant([[0, 1], [1, 0], [0, 1]])
softmax_loss = losses.softmax_cross_entropy(
softmax_labels, softmax_logits, label_smoothing=label_smoothing)
self.assertAlmostEqual(sigmoid_loss.eval(), self.evaluate(softmax_loss),
3)
@test_util.run_deprecated_v1
class LogLossTest(test.TestCase):
def setUp(self):
super(LogLossTest, self).setUp()
predictions = np.asarray([.9, .2, .2, .8, .4, .6]).reshape((2, 3))
labels = np.asarray([1.0, 0.0, 1.0, 1.0, 0.0, 0.0]).reshape((2, 3))
self._np_predictions = predictions
self._np_labels = labels
epsilon = 1e-7
self._expected_losses = np.multiply(
labels, np.log(predictions + epsilon)) + np.multiply(
1 - labels, np.log(1 - predictions + epsilon))
self._predictions = constant_op.constant(predictions)
self._labels = constant_op.constant(labels)
def testValueErrorThrownWhenWeightIsNone(self):
with self.cached_session():
with self.assertRaises(ValueError):
losses.log_loss(self._labels, self._labels, weights=None)
def testAllCorrectNoLossWeight(self):
loss = losses.log_loss(self._labels, self._labels)
with self.cached_session():
self.assertAlmostEqual(0.0, self.evaluate(loss), 3)
def testAllCorrectNoLossWeightWithPlaceholder(self):
tf_predictions = array_ops.placeholder(
dtypes.float32, shape=self._np_labels.shape)
loss = losses.log_loss(self._labels, tf_predictions)
with self.cached_session():
self.assertAlmostEqual(
0.0, loss.eval(feed_dict={tf_predictions: self._np_labels}), 3)
def testNonZeroLoss(self):
loss = losses.log_loss(self._labels, self._predictions)
with self.cached_session():
self.assertAlmostEqual(-np.sum(self._expected_losses) / 6.0,
self.evaluate(loss), 3)
def testNonZeroLossWithPythonScalarWeight(self):
weights = 2.3
loss = losses.log_loss(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(weights * -np.sum(self._expected_losses) / 6.0,
self.evaluate(loss), 3)
def testNonZeroLossWithScalarTensorWeight(self):
weights = 2.3
loss = losses.log_loss(self._labels, self._predictions,
constant_op.constant(weights))
with self.cached_session():
self.assertAlmostEqual(weights * -np.sum(self._expected_losses) / 6.0,
self.evaluate(loss), 3)
def testNonZeroLossWithScalarTensorWeightAndPlaceholder(self):
tf_predictions = array_ops.placeholder(
dtypes.float32, shape=self._np_predictions.shape)
weights = 2.3
loss = losses.log_loss(self._labels, tf_predictions,
constant_op.constant(weights))
with self.cached_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._np_predictions})
self.assertAlmostEqual(weights * -np.sum(self._expected_losses) / 6.0,
loss, 3)
def testNonZeroLossWithScalarTensorWeightAndPlaceholderWithRankOnly(self):
tf_predictions = array_ops.placeholder(dtypes.float32, shape=[None, None])
weights = 2.3
loss = losses.log_loss(self._labels, tf_predictions,
constant_op.constant(weights))
with self.cached_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._np_predictions})
self.assertAlmostEqual(weights * -np.sum(self._expected_losses) / 6.0,
loss, 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
weights = constant_op.constant((1.2, 3.4), shape=(2, 1))
expected_losses = np.multiply(
self._expected_losses,
np.asarray([1.2, 1.2, 1.2, 3.4, 3.4, 3.4]).reshape((2, 3)))
loss = losses.log_loss(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(-np.sum(expected_losses) / 6.0,
self.evaluate(loss), 3)
def testNonZeroLossWithOneDimBatchSpecificWeightsSomeZero(self):
weights = constant_op.constant((1.2, 0), shape=(2, 1))
expected_losses = np.multiply(self._expected_losses,
np.asarray([1.2, 1.2, 1.2, 0, 0, 0]).reshape(
(2, 3)))
loss = losses.log_loss(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(-np.sum(expected_losses) / 3.0,
self.evaluate(loss), 3)
def testNonZeroLossWithTwoDimBatchSpecificWeightsSomeZero(self):
weights = constant_op.constant([1.2, 0], shape=[2, 1])
expected_losses = np.multiply(self._expected_losses,
np.asarray([1.2, 1.2, 1.2, 0, 0, 0]).reshape(
(2, 3)))
loss = losses.log_loss(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(-np.sum(expected_losses) / 3.0,
self.evaluate(loss), 3)
def testWeightsWithSameNumDimsButWrongShapeThrowsException(self):
weights = constant_op.constant(np.random.normal(size=(2, 4)), shape=[2, 4])
with self.cached_session():
with self.assertRaises(ValueError):
losses.log_loss(self._labels, self._predictions, weights)
def testNonZeroLossWithMeasurementSpecificWeights(self):
weights = np.array([3, 6, 5, 0, 4, 2]).reshape((2, 3))
expected_losses = np.multiply(self._expected_losses, weights)
loss = losses.log_loss(
self._labels,
self._predictions,
constant_op.constant(
weights, shape=(2, 3)))
with self.cached_session():
self.assertAlmostEqual(-np.sum(expected_losses) / 5.0,
self.evaluate(loss), 3)
def testNonZeroLossWithMeasurementSpecificWeightsWithPlaceholder(self):
weights = np.array([3, 6, 5, 0, 4, 2]).reshape((2, 3))
expected_losses = np.multiply(self._expected_losses, weights)
tf_predictions = array_ops.placeholder(dtypes.float32, shape=[2, 3])
loss = losses.log_loss(
self._labels,
tf_predictions,
constant_op.constant(
weights, shape=(2, 3)))
with self.cached_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._np_predictions})
self.assertAlmostEqual(-np.sum(expected_losses) / 5.0, loss, 3)
def testNonZeroLossWithSampleSpecificWeightsMostZero(self):
weights = np.array([0, 0, 0, 0, 0, 2]).reshape((2, 3))
expected_losses = np.multiply(self._expected_losses, weights)
loss = losses.log_loss(
self._labels,
self._predictions,
constant_op.constant(
weights, shape=(2, 3)))
with self.cached_session():
self.assertAlmostEqual(-np.sum(expected_losses), self.evaluate(loss), 3)
def testNonZeroLossWithSampleSpecificWeightsMostZeroWithPlaceholder(self):
weights = np.array([0, 0, 0, 0, 0, 2]).reshape((2, 3))
expected_losses = np.multiply(self._expected_losses, weights)
tf_predictions = array_ops.placeholder(dtypes.float32, shape=[2, 3])
tf_weights = constant_op.constant(weights, shape=(2, 3))
loss = losses.log_loss(self._labels, tf_predictions, tf_weights)
with self.cached_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._np_predictions})
self.assertAlmostEqual(-np.sum(expected_losses), loss, 3)
def testLossWithSampleSpecificWeightsAllZero(self):
tf_weights = array_ops.zeros(shape=(2, 3))
loss = losses.log_loss(self._labels, self._predictions, tf_weights)
with self.cached_session():
self.assertAlmostEqual(0.0, self.evaluate(loss), 3)
class HingeLossTest(test.TestCase):
def testIncompatibleShapes(self):
with self.cached_session():
logits = constant_op.constant([[-1.0], [2.1]])
labels = constant_op.constant([0.0, 1.0])
with self.assertRaises(ValueError):
_ = losses.hinge_loss(labels, logits).eval()
@test_util.run_deprecated_v1
def testAllOutsideMargin(self):
with self.cached_session():
logits = constant_op.constant([1.2, -1.4, -1.0, 2.1])
labels = constant_op.constant([1.0, 0.0, 0.0, 1.0])
loss = losses.hinge_loss(labels, logits)
self.assertAllClose(loss.eval(), 0.0, atol=1e-3)
@test_util.run_deprecated_v1
def testSomeInsideMargin(self):
with self.cached_session():
logits = constant_op.constant([[-0.7], [-1.4], [1.4], [0.6]])
labels = constant_op.constant([[0.0], [0.0], [1.0], [1.0]])
loss = losses.hinge_loss(labels, logits)
# Examples 1 and 4 are on the correct side of the hyperplane but within
# the margin so they incur some (small) loss.
self.assertAllClose(loss.eval(), 0.175, atol=1e-3)
@test_util.run_deprecated_v1
def testSomeMisclassified(self):
with self.cached_session():
logits = constant_op.constant([[[1.2], [0.4], [-1.0], [-1.1]]])
labels = constant_op.constant([[[1.0], [0.0], [0.0], [1.0]]])
loss = losses.hinge_loss(labels, logits)
# Examples 2 and 4 are on the wrong side of the hyperplane so they incur
# some (fairly large) loss.
self.assertAllClose(loss.eval(), 0.875, atol=1e-3)
class HuberLossTest(test.TestCase):
def testIncompatibleShapes(self):
with self.cached_session():
predictions = constant_op.constant([[-1.0], [2.1]])
labels = constant_op.constant([0.0, 1.0])
with self.assertRaises(ValueError):
_ = losses.huber_loss(labels, predictions).eval()
@test_util.run_deprecated_v1
def testAllQuadratic(self):
with self.cached_session():
predictions = constant_op.constant([1.5, -1.4, -1.0, 0.0])
labels = constant_op.constant([1.0, -1.0, 0.0, 0.5])
loss = losses.huber_loss(labels, predictions)
self.assertAllClose(loss.eval(),
0.5 * (0.25 + 0.16 + 1.0 + 0.25) / 4., atol=1e-5)
@test_util.run_deprecated_v1
def testAllLinear(self):
with self.cached_session():
predictions = constant_op.constant([1.5, -1.4, -1.0, 0.0])
labels = constant_op.constant([0.0, 1.0, 0.0, 1.5])
loss = losses.huber_loss(labels, predictions)
self.assertAllClose(loss.eval(),
(1.5 + 2.4 + 1.0 + 1.5) / 4. - 0.5, atol=1e-5)
@test_util.run_deprecated_v1
def testMixedQuadraticLinear(self):
with self.cached_session():
predictions = constant_op.constant([[1.5, -1.4, -1.0, 0.0],
[1.5, -1.4, -1.0, 0.0]])
labels = constant_op.constant([[1.0, -1.0, 0.0, 0.5],
[0.0, 1.0, 0.0, 1.5]])
loss = losses.huber_loss(labels, predictions)
quadratic = 0.5 * (0.25 + 0.16 + 1.0 + 0.25) / 4.
linear = (1.5 + 2.4 + 1.0 + 1.5) / 4. - 0.5
expected_loss = (quadratic + linear) / 2.
self.assertAllClose(loss.eval(), expected_loss, atol=1e-5)
def testAllQuadraticDelta(self):
with self.cached_session():
delta = 0.5
predictions = constant_op.constant([1.5, -1.4, -0.5, 0.0])
labels = constant_op.constant([1.0, -1.0, 0.0, 0.5])
expected = 0.5 * np.array([0.5**2, 0.4**2, 0.5**2, 0.5**2]).mean()
loss = losses.huber_loss(labels, predictions, delta=delta)
self.assertAllClose(expected, self.evaluate(loss), atol=1e-5)
def testAllLinearDelta(self):
delta = 0.5
predictions = constant_op.constant([1.5, -1.4, -1.0, 0.0])
labels = constant_op.constant([0.0, 1.0, 0.0, 1.5])
expected = delta * np.array([1.5, 2.4, 1.0, 1.5]).mean()
expected -= 0.5 * delta**2
loss = losses.huber_loss(labels, predictions, delta=delta)
with self.cached_session():
self.assertAllClose(expected, self.evaluate(loss), atol=1e-5)
@test_util.run_deprecated_v1
class MeanSquaredErrorTest(test.TestCase):
def setUp(self):
super(MeanSquaredErrorTest, self).setUp()
self._predictions = constant_op.constant([4, 8, 12, 8, 1, 3], shape=(2, 3))
self._labels = constant_op.constant([1, 9, 2, -5, -2, 6], shape=(2, 3))
def testValueErrorThrownWhenWeightIsNone(self):
with self.cached_session():
with self.assertRaises(ValueError):
losses.mean_squared_error(
self._predictions, self._predictions, weights=None)
@test_util.run_deprecated_v1
def testScalar(self):
with self.cached_session():
self.assertEqual(
0.0,
losses.mean_squared_error(predictions=constant_op.constant(0),
labels=constant_op.constant(0)).eval())
@test_util.run_deprecated_v1
def testAllCorrectNoLossWeight(self):
loss = losses.mean_squared_error(self._predictions, self._predictions)
with self.cached_session():
self.assertAlmostEqual(0.0, self.evaluate(loss), 3)
@test_util.run_deprecated_v1
def testNonZeroLoss(self):
loss = losses.mean_squared_error(self._labels, self._predictions)
with self.cached_session():
self.assertAlmostEqual(49.5, self.evaluate(loss), 3)
@test_util.run_deprecated_v1
def testNonZeroLossWithPythonScalarWeight(self):
weights = 2.3
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(49.5 * weights, self.evaluate(loss), 3)
@test_util.run_deprecated_v1
def testNonZeroLossWithScalarTensorWeight(self):
weights = 2.3
loss = losses.mean_squared_error(self._labels, self._predictions,
constant_op.constant(weights))
with self.cached_session():
self.assertAlmostEqual(49.5 * weights, self.evaluate(loss), 3)
def testNonZeroLossWithOneDimBatchSpecificWeights(self):
weights = constant_op.constant([1.2, 3.4], shape=(2, 1))
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(767.8 / 6.0, self.evaluate(loss), 3)
def testNonZeroLossWithTwoDimBatchSpecificWeights(self):
weights = constant_op.constant([1.2, 3.4], shape=[2, 1])
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(767.8 / 6.0, self.evaluate(loss), 3)
def testNonZeroLossWithSampleSpecificWeights(self):
weights = constant_op.constant([3, 6, 5, 0, 4, 2], shape=[2, 3])
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(587 / 5.0, self.evaluate(loss), 3)
def testNonZeroLossWithSampleSpecificWeightsMostZero(self):
weights = constant_op.constant([0, 0, 0, 0, 0, 2], shape=[2, 3])
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(18.0, self.evaluate(loss), 3)
def testLossWithSampleSpecificWeightsAllZero(self):
weights = array_ops.zeros((2, 3))
loss = losses.mean_squared_error(self._labels, self._predictions, weights)
with self.cached_session():
self.assertAlmostEqual(0.0, self.evaluate(loss), 3)
@test_util.run_deprecated_v1
class MeanPairwiseSquaredErrorTest(test.TestCase):
def setUp(self):
super(MeanPairwiseSquaredErrorTest, self).setUp()
self._predictions = np.array([[4, 8, 12], [8, 1, 3]])
self._labels = np.array([[1, 9, 2], [-5, -5, 7]])
batch_size, dims = self._labels.shape
# Compute the expected loss 'manually'.
total = np.zeros((batch_size,))
for b in range(batch_size):
for i in range(dims - 1):
for j in range(i + 1, dims):
x = self._predictions[b, i].item() - self._predictions[b, j].item()
y = self._labels[b, i].item() - self._labels[b, j].item()
diff = (x - y)
total[b] += (diff * diff)
self._expected_losses = np.divide(total, 3.0)
def testValueErrorThrownWhenWeightIsNone(self):
with self.cached_session():
with self.assertRaises(ValueError):
losses.mean_pairwise_squared_error(
predictions=constant_op.constant(self._labels),
labels=constant_op.constant(self._labels),
weights=None)
def _test_valid_weights(
self, labels, predictions, expected_loss, weights=1.0):
with self.cached_session():
static_inputs_op = losses.mean_pairwise_squared_error(
predictions=predictions, labels=labels, weights=weights)
self.assertAlmostEqual(
expected_loss, self.evaluate(static_inputs_op), places=3)
predictions_placeholder = array_ops.placeholder(
dtypes.float32, shape=np.asarray(predictions.shape))
labels_placeholder = array_ops.placeholder(
dtypes.int32, shape=np.asarray(labels.shape))
weights_placeholder = array_ops.placeholder(
dtypes.float32, shape=np.asarray(weights).shape)
dynamic_inputs_op = losses.mean_pairwise_squared_error(
predictions=predictions_placeholder,
labels=labels_placeholder,
weights=weights_placeholder)
feed_dict = {
predictions_placeholder: predictions,
labels_placeholder: labels,
weights_placeholder: weights,
}
self.assertAlmostEqual(
expected_loss, dynamic_inputs_op.eval(feed_dict=feed_dict), places=3)
def testAllCorrectNoLossWeight(self):
self._test_valid_weights(
self._labels, self._labels, expected_loss=0.0)
def testNonZeroLoss(self):
self._test_valid_weights(
self._labels, self._predictions,
expected_loss=np.sum(self._expected_losses))
def testGradientWithZeroWeight(self):
with ops.Graph().as_default():
random_seed.set_random_seed(0)
inputs = array_ops.ones((2, 3))
weights = variable_scope.get_variable(
'weights',
shape=[3, 4],
initializer=init_ops.truncated_normal_initializer())
predictions = math_ops.matmul(inputs, weights)
optimizer = momentum_lib.MomentumOptimizer(
learning_rate=0.001, momentum=0.9)
loss = losses.mean_pairwise_squared_error(predictions, predictions, 0)
gradients_to_variables = optimizer.compute_gradients(loss)
init_op = variables.global_variables_initializer()
with self.cached_session() as sess:
self.evaluate(init_op)
for grad, _ in gradients_to_variables:
np_grad = self.evaluate(grad)
self.assertFalse(np.isnan(np_grad).any())
def testNonZeroLossWithPythonScalarWeight(self):
weight = 2.3
self._test_valid_weights(
self._labels, self._predictions,
expected_loss=weight * np.sum(self._expected_losses),
weights=weight)
def testNonZeroLossWithScalarTensorWeight(self):
weights = 2.3
loss = losses.mean_pairwise_squared_error(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
weights=constant_op.constant(weights))
with self.cached_session():
self.assertAlmostEqual(weights * np.sum(self._expected_losses),
self.evaluate(loss), 3)
def testNonZeroLossWithScalarZeroWeight(self):
self._test_valid_weights(
self._labels, self._predictions, expected_loss=0.0, weights=0.0)
def test3d(self):
labels = np.array([
[[1, 9, 2], [12, 11, 10], [9, 8, 7]],
[[-5, -5, 7], [6, 5, 4], [3, 2, 1]],
])
predictions = np.array([
[[4, 8, 12], [1, 2, 3], [4, 5, 6]],
[[8, 1, 3], [7, 8, 9], [10, 11, 12]],
])
self._test_valid_weights(labels, predictions, expected_loss=137.5)
def test3dWeightedScalar(self):
labels = np.array([
[[1, 9, 2], [12, 11, 10], [9, 8, 7]],
[[-5, -5, 7], [6, 5, 4], [3, 2, 1]],
])
predictions = np.array([
[[4, 8, 12], [1, 2, 3], [4, 5, 6]],
[[8, 1, 3], [7, 8, 9], [10, 11, 12]],
])
weight = 3.0
self._test_valid_weights(
labels, predictions, expected_loss=weight * 137.5, weights=weight)
def _test_invalid_weights(
self, labels, predictions, weights=1.0):
expected_error_msg = 'weights can not be broadcast to values'
# Static check.
with self.assertRaisesRegexp(ValueError, expected_error_msg):
losses.mean_pairwise_squared_error(
predictions=predictions, labels=labels, weights=weights)
# Dynamic check.
predictions_placeholder = array_ops.placeholder(dtypes.float32)
labels_placeholder = array_ops.placeholder(dtypes.int32)
weights_placeholder = array_ops.placeholder(dtypes.float32)
dynamic_inputs_op = losses.mean_pairwise_squared_error(
predictions=predictions_placeholder,
labels=labels_placeholder,
weights=weights_placeholder)
with self.cached_session():
with self.assertRaisesRegexp(errors_impl.OpError, expected_error_msg):
dynamic_inputs_op.eval(feed_dict={
predictions_placeholder: predictions,
labels_placeholder: labels,
weights_placeholder: weights,
})
def testInvalid3dWeighted2x0(self):
labels = np.array([
[[1, 9, 2], [12, 11, 10], [9, 8, 7]],
[[-5, -5, 7], [6, 5, 4], [3, 2, 1]],
])
predictions = np.array([
[[4, 8, 12], [1, 2, 3], [4, 5, 6]],
[[8, 1, 3], [7, 8, 9], [10, 11, 12]],
])
self._test_invalid_weights(
labels, predictions, weights=np.asarray((1.2, 3.4)))
def test3dWeighted2x3x3(self):
labels = np.array([
[[1, 9, 2], [12, 11, 10], [9, 8, 7]],
[[-5, -5, 7], [6, 5, 4], [3, 2, 1]],
])
predictions = np.array([
[[4, 8, 12], [1, 2, 3], [4, 5, 6]],
[[8, 1, 3], [7, 8, 9], [10, 11, 12]],
])
self._test_valid_weights(
# TODO(ptucker): This doesn't look right.
labels,
predictions,
expected_loss=9 * 137.5,
weights=np.ones((2, 3, 3)))
def testLossWithAllZeroBatchSpecificWeights(self):
self._test_valid_weights(
self._labels, self._predictions, expected_loss=0.0,
weights=np.zeros((2, 1)))
def testLossIsAssociativeAcrossBatchElements(self):
with ops.Graph().as_default():
random_seed.set_random_seed(0)
height = 3
width = 4
shape = (1, height, width, 1)
labels0 = random_ops.random_uniform(
shape, minval=0, maxval=1, dtype=dtypes.float32)
predictions0 = random_ops.random_uniform(
shape, minval=0, maxval=1, dtype=dtypes.float32)
labels1 = random_ops.random_uniform(
shape, minval=0, maxval=1, dtype=dtypes.float32)
predictions1 = random_ops.random_uniform(
shape, minval=0, maxval=1, dtype=dtypes.float32)
loss0 = losses.mean_pairwise_squared_error(
labels=labels0,
predictions=predictions0)
loss1 = losses.mean_pairwise_squared_error(
labels=labels1,
predictions=predictions1)
loss0_1 = losses.mean_pairwise_squared_error(
labels=array_ops.concat([labels0, labels1], 0),
predictions=array_ops.concat([predictions0, predictions1], 0))
with self.cached_session() as session:
loss0, loss1, loss0_1 = session.run([loss0, loss1, loss0_1])
self.assertTrue(loss0 > 0)
self.assertTrue(loss1 > 0)
self.assertAlmostEqual(loss0 + loss1, loss0_1, 5)
@test_util.run_deprecated_v1
class CosineDistanceLossTest(test.TestCase):
def setUp(self):
super(CosineDistanceLossTest, self).setUp()
self._predictions = np.asarray([
[1, 0, 0], # Batch 1
[0, 0, -1],
[1, 0, 0], # Batch 2
[1, 0, 0],
[0, 0, -1], # Batch 3
[1, 0, 0]
]).reshape((3, 2, 3))
self._labels = np.asarray([[1, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0],
[0, 0, 1], [0, 1, 0]]).reshape((3, 2, 3))
def testValueErrorThrownWhenWeightIsNone(self):
with self.cached_session():
with self.assertRaises(ValueError):
losses.cosine_distance(
predictions=constant_op.constant(self._labels),
labels=constant_op.constant(self._labels),
dim=2,
weights=None)
def testAllCorrectNoWeights(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._labels),
labels=constant_op.constant(self._labels),
dim=2)
with self.cached_session():
self.assertAlmostEqual(0, self.evaluate(loss), 5)
def testPartiallyCorrectWithIntegerValues(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2)
with self.cached_session():
self.assertAlmostEqual(1, self.evaluate(loss), 5)
def testPartiallyCorrectFloatingPointValues(self):
predictions = np.matrix(
('0.819031913261206 0.567041924552012 0.087465312324590;'
'-0.665139432070255 -0.739487441769973 -0.103671883216994;'
'0.707106781186548 -0.707106781186548 0'))
labels = np.matrix(('0.819031913261206 0.567041924552012 0.087465312324590;'
'0.665139432070255 0.739487441769973 0.103671883216994;'
'0.707106781186548 0.707106781186548 0'))
tf_preds = constant_op.constant(
predictions, shape=(3, 1, 3), dtype=dtypes.float32)
tf_labels = constant_op.constant(
labels, shape=(3, 1, 3), dtype=dtypes.float32)
loss = losses.cosine_distance(tf_labels, tf_preds, dim=2)
with self.cached_session():
self.assertAlmostEqual(1.0, self.evaluate(loss), 5)
def testSampleSpecificWeights(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2,
weights=np.asarray((1, 0, 0)).reshape((3, 1, 1)))
with self.cached_session():
self.assertEqual(1.0, self.evaluate(loss))
def testMeasurementSpecificWeights(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2,
weights=constant_op.constant(
[1, 0, 0, 1, 1, 1], shape=(3, 2, 1)))
with self.cached_session():
self.assertEqual(3.0 / 4.0, self.evaluate(loss))
def testMeasurementSpecificWeightsWithPlaceholderWithShape(self):
tf_predictions = array_ops.placeholder(
dtypes.float32, shape=self._labels.shape)
loss = losses.cosine_distance(
predictions=tf_predictions,
labels=constant_op.constant(self._labels),
dim=2,
weights=constant_op.constant(
[1, 0, 0, 1, 1, 1], shape=(3, 2, 1)))
with self.cached_session() as sess:
loss = sess.run(loss, feed_dict={tf_predictions: self._predictions})
self.assertEqual(3.0 / 4.0, loss)
def testZeroLossWhenAllSampleSpecificWeightsAreZero(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2,
weights=array_ops.zeros((3, 1, 1)))
with self.cached_session():
self.assertEqual(0, self.evaluate(loss))
def testZeroLossWhenAllMeasurementSpecificWeightsAreZero(self):
loss = losses.cosine_distance(
predictions=constant_op.constant(self._predictions),
labels=constant_op.constant(self._labels),
dim=2,
weights=array_ops.zeros((3, 2, 1)))
with self.cached_session():
self.assertEqual(0, self.evaluate(loss))
class AddLossTest(test.TestCase):
def testNoCollectLossesBatch2(self):
logits = constant_op.constant([[1.2, 0.4, -1.0, -1.1]] * 2)
labels = constant_op.constant([[1.0, 0.0, 0.0, 1.0]] * 2)
self.assertFalse(util.get_losses())
losses.absolute_difference(logits, labels, loss_collection=None)
losses.log_loss(logits, labels, loss_collection=None)
losses.mean_squared_error(logits, labels, loss_collection=None)
losses.sigmoid_cross_entropy(logits, labels, loss_collection=None)
losses.softmax_cross_entropy(logits, labels, loss_collection=None)
self.assertFalse(util.get_losses())
class ComputeWeightedLossTest(test.TestCase):
def setUp(self):
super(ComputeWeightedLossTest, self).setUp()
self._shape = (3, 2, 4)
raw_losses = np.zeros(self._shape)
next_loss = 0.0
for i in range(self._shape[0]):
for j in range(self._shape[1]):
for k in range(self._shape[2]):
raw_losses[i][j][k] = next_loss
next_loss += 1.0
raw_losses.setflags(write=False)
self._raw_losses = raw_losses
def testUnweighted(self):
for reduction in losses.Reduction.all():
with ops.Graph().as_default() as g:
self.assertEqual(0, len(util.get_losses()))
raw_losses = self._raw_losses
unweighted_losses = (
losses.compute_weighted_loss(raw_losses, reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 1, 1)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 1, 4)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 2, 1)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 2, 4)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((3, 1, 1)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((3, 1, 4)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((3, 2, 1)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones(self._shape), reduction=reduction)
)
self.assertEqual(9, len(util.get_losses()))
with self.session(g):
for unweighted_loss in unweighted_losses:
if reduction == losses.Reduction.NONE:
self.assertAllClose(self._raw_losses,
self.evaluate(unweighted_loss))
elif reduction == losses.Reduction.SUM:
self.assertAllClose(
np.sum(self._raw_losses), self.evaluate(unweighted_loss))
else:
# reduction one of MEAN, SUM_OVER_NONZERO_WEIGHTS,
# SUM_BY_NONZERO_WEIGHTS or SUM_OVER_BATCH_SIZE.
self.assertAllClose(
np.mean(self._raw_losses), self.evaluate(unweighted_loss))
def testUnweightedFromPlaceholder(self):
for reduction in losses.Reduction.all():
with ops.Graph().as_default() as g:
self.assertEqual(0, len(util.get_losses()))
raw_losses = array_ops.placeholder(dtype=dtypes.float32)
feed_dict = {raw_losses: self._raw_losses}
unweighted_losses = (
losses.compute_weighted_loss(raw_losses, reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 1, 1)), reduction=reduction),
losses.compute_weighted_loss(
raw_losses, weights=np.ones((1, 1, 4)), reduction=reduction),
)
self.assertEqual(3, len(util.get_losses()))
with self.session(g):
for unweighted_loss in unweighted_losses:
if reduction == losses.Reduction.NONE:
self.assertAllClose(
self._raw_losses, unweighted_loss.eval(feed_dict))
elif reduction == losses.Reduction.SUM:
self.assertAllClose(
np.sum(self._raw_losses), unweighted_loss.eval(feed_dict))
else:
# reduction one of MEAN, SUM_OVER_NONZERO_WEIGHTS,
# SUM_BY_NONZERO_WEIGHTS or SUM_OVER_BATCH_SIZE.
self.assertAllClose(
np.mean(self._raw_losses), unweighted_loss.eval(feed_dict))
def testScalarWeight(self):
with ops.Graph().as_default():
self.assertEqual(0, len(util.get_losses()))
weight = 17.0
weighted_loss = losses.compute_weighted_loss(
self._raw_losses, weights=weight)
self.assertEqual(1, len(util.get_losses()))
with self.cached_session():
self.assertAllClose(
np.mean(weight * self._raw_losses), self.evaluate(weighted_loss))
def _test_invalid_weights(self, weights):
with ops.Graph().as_default():
self.assertEqual(0, len(util.get_losses()))
expected_error_msg = 'weights can not be broadcast to values'
# Static check.
with self.assertRaisesRegexp(ValueError, expected_error_msg):
losses.compute_weighted_loss(self._raw_losses, weights=weights)
# Dynamic check.
weights_placeholder = array_ops.placeholder(dtypes.float32)
weighted_loss = losses.compute_weighted_loss(
self._raw_losses, weights=weights_placeholder)
self.assertEqual(1, len(util.get_losses()))
with self.cached_session():
with self.assertRaisesRegexp(errors_impl.OpError, expected_error_msg):
weighted_loss.eval(feed_dict={weights_placeholder: weights})
def testInvalidWeightTooManyDims(self):
self._test_invalid_weights(np.zeros(shape=(2, 2, 2, 2)))
def testInvalidWeightMismatchedDim(self):
with ops.Graph().as_default():
raw_losses = array_ops.reshape(self._raw_losses, shape=(3, 2, 4, 1))
weights = np.ones(shape=(3, 2, 4, 2))
expected_error_msg = 'weights can not be broadcast to values'
self.assertEqual(0, len(util.get_losses()))
# Static check.
with self.assertRaisesRegexp(ValueError, expected_error_msg):
losses.compute_weighted_loss(raw_losses, weights=weights)
# Dynamic check.
weights_placeholder = array_ops.placeholder(dtypes.float32)
weighted_loss = losses.compute_weighted_loss(
raw_losses, weights=weights_placeholder)
self.assertEqual(1, len(util.get_losses()))
with self.cached_session():
with self.assertRaisesRegexp(errors_impl.OpError, expected_error_msg):
weighted_loss.eval(feed_dict={weights_placeholder: weights})
def testInvalid3Weight(self):
self._test_invalid_weights((17.0, 5.0, 2.0))
def testInvalid3x1Weight(self):
self._test_invalid_weights(((17.0,), (5.0,), (2.0,),))
def testInvalid3x2Weight(self):
self._test_invalid_weights((
(17.0, 3.0),
(5.0, 31.0),
(2.0, 7.0),))
def testInvalid1x2Weight(self):
self._test_invalid_weights((17.0, 3.0,),)
def testInvalidScalar1DWeight(self):
self._test_invalid_weights((17.0,),)
def _test_valid_weights(self, weights):
for reduction in losses.Reduction.all():
with ops.Graph().as_default() as g:
self.assertEqual(0, len(util.get_losses()))
weighted_loss = losses.compute_weighted_loss(
self._raw_losses, weights=weights, reduction=reduction)
self.assertEqual(1, len(util.get_losses()))
with self.session(g):
weighted_losses = weights * self._raw_losses
weighted_sum = np.sum(weighted_losses)
if reduction == losses.Reduction.NONE:
self.assertAllClose(weighted_losses, self.evaluate(weighted_loss))
elif reduction == losses.Reduction.SUM:
self.assertAllClose(weighted_sum, self.evaluate(weighted_loss))
else:
broadcast_weights = weights * np.ones_like(self._raw_losses)
if reduction == losses.Reduction.MEAN:
self.assertAllClose(weighted_sum / np.sum(broadcast_weights),
self.evaluate(weighted_loss))
elif (reduction == losses.Reduction.SUM_OVER_NONZERO_WEIGHTS or
reduction == losses.Reduction.SUM_BY_NONZERO_WEIGHTS):
self.assertAllClose(
weighted_sum / np.count_nonzero(broadcast_weights),
self.evaluate(weighted_loss))
elif reduction == losses.Reduction.SUM_OVER_BATCH_SIZE:
self.assertAllClose(weighted_sum / self._raw_losses.size,
self.evaluate(weighted_loss))
def test1x1x1Weight(self):
self._test_valid_weights((((17.0,),),))
def test1x2x1Weight(self):
self._test_valid_weights((((17.0,), (3.0,),),))
def test1x1x4Weight(self):
self._test_valid_weights((((17.0, 0.0, 2.0, 5.0),),))
def test3x1x1Weight(self):
self._test_valid_weights((((17.0,),), ((5.0,),), ((2.0,),),))
def test3x2x1Weight(self):
self._test_valid_weights((
((17.0,), (3.0,)),
((5.0,), (31.0,)),
((2.0,), (7.0,)),
))
def test3x1x4Weight(self):
self._test_valid_weights((
((17.0, 0.0, 2.0, 5.0),),
((5.0, 31.0, 17.0, 5.0),),
((7.0, 3.0, 11.0, 5.0),),
))
def test1x2x4Weight(self):
self._test_valid_weights(((
(17.0, 0.0, 2.0, 5.0),
(3.0, 13.0, 11.0, 2.0),
),))
def test3x2x4Weight(self):
self._test_valid_weights((
((17.0, 0.0, 2.0, 5.0), (3.0, 13.0, 11.0, 2.0),),
((5.0, 31.0, 17.0, 5.0), (13.0, 3.0, 0.0, 11.0),),
((0.0, 3.0, 11.0, 5.0), (13.0, 11.0, 1.0, 7.0),),
))
if __name__ == '__main__':
test.main()
| apache-2.0 |
RyanSkraba/beam | sdks/python/apache_beam/io/gcp/datastore_write_it_pipeline.py | 1 | 7435 | #
# 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.
#
"""A job that write Entries into Datastore.
The pipelines behave in the steps below.
1. Create and write Entities to Datastore
2. (Optional) If read limit was provided,
read it and confirm that the expected Entities were read.
3. Query the written Entities and verify result.
4. Delete Entries.
5. Query the written Entities, verify no results.
"""
from __future__ import absolute_import
import argparse
import hashlib
import logging
import uuid
import apache_beam as beam
from apache_beam.io.gcp.datastore.v1.datastoreio import DeleteFromDatastore
from apache_beam.io.gcp.datastore.v1.datastoreio import ReadFromDatastore
from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore
from apache_beam.options.pipeline_options import GoogleCloudOptions
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to
# Protect against environments where Datastore library is not available.
# pylint: disable=wrong-import-order, wrong-import-position
try:
from google.cloud.proto.datastore.v1 import entity_pb2
from google.cloud.proto.datastore.v1 import query_pb2
from googledatastore import helper as datastore_helper
from googledatastore import PropertyFilter
except ImportError:
pass
# pylint: enable=wrong-import-order, wrong-import-position
# pylint: enable=ungrouped-imports
_LOGGER = logging.getLogger(__name__)
def new_pipeline_with_job_name(pipeline_options, job_name, suffix):
"""Create a pipeline with the given job_name and a suffix."""
gcp_options = pipeline_options.view_as(GoogleCloudOptions)
# DirectRunner doesn't have a job name.
if job_name:
gcp_options.job_name = job_name + suffix
return TestPipeline(options=pipeline_options)
class EntityWrapper(object):
"""Create a Cloud Datastore entity from the given string."""
def __init__(self, kind, namespace, ancestor):
self._kind = kind
self._namespace = namespace
self._ancestor = ancestor
def make_entity(self, content):
"""Create entity from given string."""
entity = entity_pb2.Entity()
if self._namespace is not None:
entity.key.partition_id.namespace_id = self._namespace
# All entities created will have the same ancestor
datastore_helper.add_key_path(entity.key, self._kind, self._ancestor,
self._kind, hashlib.sha1(content).hexdigest())
datastore_helper.add_properties(entity, {'content': str(content)})
return entity
def make_ancestor_query(kind, namespace, ancestor):
"""Creates a Cloud Datastore ancestor query."""
ancestor_key = entity_pb2.Key()
datastore_helper.add_key_path(ancestor_key, kind, ancestor)
if namespace is not None:
ancestor_key.partition_id.namespace_id = namespace
query = query_pb2.Query()
query.kind.add().name = kind
datastore_helper.set_property_filter(
query.filter, '__key__', PropertyFilter.HAS_ANCESTOR, ancestor_key)
return query
def run(argv=None):
"""Main entry point."""
parser = argparse.ArgumentParser()
parser.add_argument('--kind',
dest='kind',
default='writereadtest',
help='Datastore Kind')
parser.add_argument('--num_entities',
dest='num_entities',
type=int,
required=True,
help='Number of entities to write')
parser.add_argument('--limit',
dest='limit',
type=int,
help='Limit of number of entities to write')
known_args, pipeline_args = parser.parse_known_args(argv)
pipeline_options = PipelineOptions(pipeline_args)
gcloud_options = pipeline_options.view_as(GoogleCloudOptions)
job_name = gcloud_options.job_name
kind = known_args.kind
num_entities = known_args.num_entities
project = gcloud_options.project
# a random ancesor key
ancestor = str(uuid.uuid4())
query = make_ancestor_query(kind, None, ancestor)
# Pipeline 1: Create and write the specified number of Entities to the
# Cloud Datastore.
_LOGGER.info('Writing %s entities to %s', num_entities, project)
p = new_pipeline_with_job_name(pipeline_options, job_name, '-write')
# pylint: disable=expression-not-assigned
(p
| 'Input' >> beam.Create(list(range(known_args.num_entities)))
| 'To String' >> beam.Map(str)
| 'To Entity' >> beam.Map(EntityWrapper(kind, None, ancestor).make_entity)
| 'Write to Datastore' >> WriteToDatastore(project))
p.run()
# Optional Pipeline 2: If a read limit was provided, read it and confirm
# that the expected entities were read.
if known_args.limit is not None:
_LOGGER.info('Querying a limited set of %s entities and verifying count.',
known_args.limit)
p = new_pipeline_with_job_name(pipeline_options, job_name, '-verify-limit')
query_with_limit = query_pb2.Query()
query_with_limit.CopyFrom(query)
query_with_limit.limit.value = known_args.limit
entities = p | 'read from datastore' >> ReadFromDatastore(project,
query_with_limit)
assert_that(
entities | beam.combiners.Count.Globally(),
equal_to([known_args.limit]))
p.run()
# Pipeline 3: Query the written Entities and verify result.
_LOGGER.info('Querying entities, asserting they match.')
p = new_pipeline_with_job_name(pipeline_options, job_name, '-verify')
entities = p | 'read from datastore' >> ReadFromDatastore(project, query)
assert_that(
entities | beam.combiners.Count.Globally(),
equal_to([num_entities]))
p.run()
# Pipeline 4: Delete Entities.
_LOGGER.info('Deleting entities.')
p = new_pipeline_with_job_name(pipeline_options, job_name, '-delete')
entities = p | 'read from datastore' >> ReadFromDatastore(project, query)
# pylint: disable=expression-not-assigned
(entities
| 'To Keys' >> beam.Map(lambda entity: entity.key)
| 'Delete keys' >> DeleteFromDatastore(project))
p.run()
# Pipeline 5: Query the written Entities, verify no results.
_LOGGER.info('Querying for the entities to make sure there are none present.')
p = new_pipeline_with_job_name(pipeline_options, job_name, '-verify-deleted')
entities = p | 'read from datastore' >> ReadFromDatastore(project, query)
assert_that(
entities | beam.combiners.Count.Globally(),
equal_to([0]))
p.run()
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
run()
| apache-2.0 |
ijmarshall/cochrane-nlp | quality4.py | 1 | 73371 | from tokenizer import sent_tokenizer, word_tokenizer
import biviewer
import pdb
import re
import progressbar
import collections
import string
from unidecode import unidecode
import codecs
import yaml
from pprint import pprint
import numpy as np
import math
import difflib
import sklearn
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.grid_search import GridSearchCV
from sklearn.feature_extraction import DictVectorizer
from sklearn import cross_validation
from sklearn import metrics
from sklearn import svm
from sklearn.linear_model import SGDClassifier
from sklearn.externals import six
from collections import defaultdict
from sklearn.metrics import precision_recall_fscore_support
import random
import operator
from sklearn.cross_validation import KFold
from journalreaders import PdfReader
import cPickle as pickle
from sklearn.metrics import f1_score, make_scorer, fbeta_score, accuracy_score
import nltk
from nltk.corpus import stopwords
REGEX_QUOTE_PRESENT = re.compile("Quote\:")
REGEX_QUOTE = re.compile("\"(.*?)\"") # retrive blocks of text in quotes
REGEX_ELLIPSIS = re.compile("\s*[\[\(]?\s?\.\.+\s?[\]\)]?\s*") # to catch various permetations of "..." and "[...]"
SIMPLE_WORD_TOKENIZER = re.compile("[a-zA-Z]{2,}") # regex of the rule used by sklearn CountVectorizer
CORE_DOMAINS = ["Random sequence generation", "Allocation concealment", "Blinding of participants and personnel",
"Blinding of outcome assessment", "Incomplete outcome data", "Selective reporting"]
# "OTHER" is generated in code, not in the mapping file
# see data/domain_names.txt for various other criteria
# all of these are available via QualityQuoteReader
ALL_DOMAINS = CORE_DOMAINS[:] # will be added to later
RoB_CLASSES = ["YES", "NO", "UNKNOWN"]
STOP_WORDS = set(stopwords.words('english'))
# @TODO move me
domain_str = lambda d: d.lower().replace(" ", "_")
def show_most_informative_features(vectorizer, clf, n=1000):
###
# note that in the multi-class case, clf.coef_ will
# have k weight vectors, which I believe are one per
# each class (i.e., each is a classifier discriminating
# one class versus the rest).
c_f = sorted(zip(clf.coef_[0], vectorizer.get_feature_names()))
if n == 0:
n = len(c_f)/2
top = zip(c_f[:n], c_f[:-(n+1):-1])
print
print "%d most informative features:" % (n, )
out_str = []
for (c1, f1), (c2, f2) in top:
out_str.append("\t%.4f\t%-15s\t\t%.4f\t%-15s" % (c1, f1, c2, f2))
feature_str = "\n".join(out_str)
return feature_str
def show_most_informative_features_ynu(vectorizer, clf, n=10):
###
# note that in the multi-class case, clf.coef_ will
# have k weight vectors, which I believe are one per
# each class (i.e., each is a classifier discriminating
# one class versus the rest).
combinations = ["NO vs (YES + UNKNOWN)", "UNKNOWN vs (YES + NO)", "YES vs (NO + UNKNOWN)"]
out_str = []
for i, combination in enumerate(combinations):
out_str.append(combination)
out_str.append("*" * 20)
c_f = sorted(zip(clf.coef_[i], vectorizer.get_feature_names()))
if n == 0:
n = len(c_f)/2
top = zip(c_f[:n], c_f[:-(n+1):-1])
for (c1, f1), (c2, f2) in top:
out_str.append("\t%.4f\t%-15s\t\t%.4f\t%-15s" % (c1, f1, c2, f2))
feature_str = "\n".join(out_str)
return feature_str
def load_domain_map(filename="data/domain_names.txt"):
with codecs.open(filename, 'rb', 'utf-8') as f:
raw_data = yaml.load(f)
mapping = {}
for key, value in raw_data.iteritems():
for synonym in value:
mapping[synonym] = key
return mapping
class QualityQuoteReader2():
"""
iterates through Cochrane Risk of Bias information
v2 maintains unique ids for all source studies + does not filter by whether a quote is present
returns list of quotes where they are available, else none
"""
def __init__(self, sent=False, test_mode=False):
self.BiviewerView = collections.namedtuple('BiViewer_View', ['uid', 'cochrane', 'studypdf'])
self.pdfviewer = biviewer.PDFBiViewer()
self.domain_map = load_domain_map()
if test_mode:
self.test_mode_break_point = 500
else:
self.test_mode_break_point = None
def __iter__(self):
"""
run through PDF/Cochrane data
preprocesses PDF text
and maps domain title to one of the core Risk of Bias domains if possible
"""
progress_bar_limit = len(self.pdfviewer) if self.test_mode_break_point is None else self.test_mode_break_point
p = progressbar.ProgressBar(progress_bar_limit, timer=True)
for uid, study in enumerate(self.pdfviewer):
if self.test_mode_break_point and (uid >= self.test_mode_break_point):
break
p.tap()
quality_data = study.cochrane["QUALITY"]
for domain in quality_data:
domain["QUOTES"] = self.preprocess_cochrane(domain["DESCRIPTION"])
try:
domain["DOMAIN"] = self.domain_map[domain["DOMAIN"]] # map domain titles to our core categories
except:
domain["DOMAIN"] = "OTHER"
yield self.BiviewerView(uid=uid, cochrane={"QUALITY": quality_data}, studypdf=self.preprocess_pdf(study.studypdf))
def __len__(self):
return len(self.pdfviewer) if self.test_mode_break_point is None else self.test_mode_break_point
def preprocess_pdf(self, pdftext):
pdftext = unidecode(pdftext)
pdftext = re.sub("\n", " ", pdftext) # preprocessing rule 1
return pdftext
def preprocess_cochrane(self, rawtext):
# regex clean up of cochrane strings
processedtext = unidecode(rawtext)
processedtext = re.sub(" +", " ", processedtext)
# extract all parts in quotes
quotes = REGEX_QUOTE.findall(processedtext)
# then split at any ellipses
quote_parts = []
for quote in quotes:
quote_parts.extend(REGEX_ELLIPSIS.split(quote))
return quote_parts
class PDFMatcher():
"""
matches and generates sent tokens from pdf text
"""
def __init__(self, quotes=None, pdftext=None):
# load a sequence matcher; turn autojunk off (since buggy for long strings)
self.sequencematcher = difflib.SequenceMatcher(None, autojunk=False)
if quotes:
self.quotes = self.load_quotes(quotes)
if pdftext:
self.pdftext = self.load_pdftext(pdftext)
def load_quotes(self, quotes):
self.quotes = quotes
def load_pdftext(self, pdftext):
self.pdftext = pdftext
self.lenpdf = len(pdftext)
self.sequencematcher.set_seq2(self.pdftext)
self.sent_indices = sent_tokenizer.span_tokenize(self.pdftext)
def _overlap(self, t1, t2):
"""
finds out whether two tuples overlap
"""
t1s, t1e = t1
t2s, t2e = t2
# true if either start of t1 is inside t2, or start of t2 is inside t1
return (t2s <= t1s <= t2e) or (t1s <= t2s <= t1e)
def generate_X(self):
X = []
# go through sentence indices
# make X (list of sentences)
for (start_i, end_i) in self.sent_indices:
X.append(self.pdftext[start_i: end_i])
return X
def generate_y(self, min_char_match=20):
"""
returns X: list of sentence strings
y: numpy vector of 1, -1 (for positive/negative examples)
"""
good_match = False # this will be set to True if sufficent matching characters in
# at least one of the parts of the quotes
match_indices = []
# go through quotes, match using difflib
# and keep any matches which are long enough so likely true matches
for quote in self.quotes:
self.sequencematcher.set_seq1(quote)
best_match = self.sequencematcher.find_longest_match(0, len(quote), 0, self.lenpdf)
# only interested in good quality matches
if best_match.size > min_char_match:
good_match = True
match_indices.append((best_match.b, best_match.b + best_match.size)) # add (start_i, end_i) tuples (of PDF indices)
y = []
if not good_match:
# if quality criteria not met, leave here
# (i.e. return empty lists [], [])
return y
# otherwise continue and generate feature and answer vectors
# get indices of sentences (rather than split)
sent_indices = sent_tokenizer.span_tokenize(self.pdftext)
# go through sentence indices
# make X (list of sentences)
# and calculate y, if there is *any* overlap with matched quoted text then
# y = True
for (start_i, end_i) in sent_indices:
# if any overlaps with quotes, then y = True, else False
if any((self._overlap((start_i, end_i), match_tuple) for match_tuple in match_indices)):
y.append(1)
else:
y.append(-1)
return y
class SentenceModel():
"""
predicts whether sentences contain risk of bias information
- uses data from Cochrane quotes only
"""
def __init__(self, test_mode=False):
self.quotereader = QualityQuoteReader2(test_mode=test_mode) # this now runs through all studies
def generate_data(self, uid_filter=None):
"""
tokenizes and processes the raw text from pdfs and cochrane
saves in self.X_list and self.y_list (both dicts)
"""
test_domains = CORE_DOMAINS # may change later to access various "other" domains
# one feature matrix X across all domains
self.X_list = [] # key will be unique id, value will be text
# but multiple y vectors; one for each test domain
self.y_list = {domain: [] for domain in test_domains}
self.y_judgements = {domain: [] for domain in test_domains} # used in subclasses to make hybrid models
self.X_uids = []
self.y_uids = {domain: [] for domain in test_domains}
for uid, cochrane_data, pdf_data in self.quotereader:
if uid_filter is not None and uid not in uid_filter:
continue
matcher = PDFMatcher()
matcher.load_pdftext(pdf_data)
X_study = matcher.generate_X()
self.X_list.extend(X_study)
self.X_uids.extend([uid] * len(X_study))
domains_done_already = [] # for this particular study
# (we're ignoring multiple quotes per domain at the moment and getting the first...)
for domain in cochrane_data["QUALITY"]:
if domain["DOMAIN"] not in test_domains or domain["DOMAIN"] in domains_done_already:
continue # skip if a domain is repeated in a study (though note that this is likely due to different RoB per *outcome* which is ignored here)
if domain["QUOTES"]:
matcher.load_quotes(domain["QUOTES"])
y_study = matcher.generate_y()
self.y_list[domain["DOMAIN"]].extend(y_study)
self.y_uids[domain["DOMAIN"]].extend([uid] * len(y_study))
self.y_judgements[domain["DOMAIN"]].extend([domain["RATING"]] * len(y_study))
domains_done_already.append(domain["DOMAIN"])
self.y = {domain: np.array(self.y_list[domain]) for domain in test_domains}
self.X_uids = np.array(self.X_uids)
self.y_uids = {domain: np.array(self.y_uids[domain]) for domain in test_domains}
self.y_judgements = {domain: np.array(self.y_judgements[domain]) for domain in test_domains}
# self.vectorize()
def vectorize(self):
self.vectorizer = ModularCountVectorizer()
# self.X = self.vectorizer.fit_transform(self.X_list, max_features=50000)
self.X = self.vectorizer.fit_transform(self.X_list)
def load_text(self, filename):
"""
loads the original text of all PDFs, to debugging and looking at predicted text from corpus
NB this is a large file
"""
with open(filename, 'rb') as f:
self.X_list = pickle.load(f)
def __len__(self):
"""
returns the total number of studies (not features)
"""
return len(self.quotereader)
def len_domain(self, domain):
return len(np.unique(self.y_uids[domain]))
def domain_X_filter(self, domain):
"""
returns X_filter for a domain
"""
y_study_uids = np.unique(self.y_uids[domain])
X_filter = np.nonzero([(X_uid in y_study_uids) for X_uid in self.X_uids])[0]
return X_filter
def domain_uids(self, domain):
unique_study_ids = np.unique(self.y_uids[domain])
return unique_study_ids
def X_y_uid_filtered(self, uids, domain):
X_all = self.X_domain_all(domain=domain)
y_all = self.y_domain_all(domain=domain)
filter_ids = np.nonzero([(y_study_id in uids) for y_study_id in self.y_uids[domain]])[0]
X_filtered = X_all[filter_ids]
y_filtered = y_all[filter_ids]
return X_filtered, y_filtered
def get_all_domains(self):
return self.y.keys()
def X_get_sentence(self, select_sent_id, domain):
y_study_ids = np.unique(self.y[domain].study_ids)
X_filter = np.nonzero([X_study_id in y_study_ids for X_study_id in self.X.study_ids])[0]
return self.X_list.data[X_filter[select_sent_id]]
def X_domain_all(self, domain):
"""
retrieve X data for a domain
"""
X_filter = self.domain_X_filter(domain)
return self.X[X_filter]
def y_domain_all(self, domain):
return self.y[domain]
# def X_y_filtered(self, filter_ids, domain):
# X_all = self.X_domain_all(domain=domain)
# y_all = self.y_domain_all(domain=domain)
# # np.unique always returns ordered ids
# unique_study_ids = np.unique(self.y_uids[domain])
# mapped_ids = [unique_study_ids[filter_id] for filter_id in filter_ids]
# filter_ids = np.nonzero([(y_study_id in mapped_ids) for y_study_id in self.y_uids[domain]])[0]
# X_filtered = X_all[filter_ids]
# y_filtered = y_all[filter_ids]
# return X_filtered, y_filtered
class DocumentLevelModel(SentenceModel):
"""
for predicting the risk of bias
as "HIGH", "LOW", or "UNKNOWN" for a document
using a binary bag-of-words as features for each document
"""
def generate_data(self, uid_filter=None, binarize=False):
"""
tokenizes and processes the raw text from pdfs and cochrane
saves in self.X_list and self.y_list (both dicts)
"""
test_domains = CORE_DOMAINS # may change later to access various "other" domains
# one feature matrix X across all domains
self.X_list = [] # key will be unique id, value will be text
# but multiple y vectors; one for each test domain
self.y_list = {domain: [] for domain in test_domains}
self.X_uids = []
self.y_uids = {domain: [] for domain in test_domains}
for uid, cochrane_data, pdf_data in self.quotereader:
if uid_filter is not None and uid not in uid_filter:
continue
X_study = [pdf_data] # this time the X is the whole pdf data
self.X_list.extend(X_study)
self.X_uids.extend([uid] * len(X_study))
domains_done_already = [] # for this particular study
# (we're ignoring multiple quotes per domain at the moment and getting the first...)
for domain in cochrane_data["QUALITY"]:
if domain["DOMAIN"] not in test_domains or domain["DOMAIN"] in domains_done_already:
continue # skip if a domain is repeated in a study (though note that this is likely due to different RoB per *outcome* which is ignored here)
if binarize:
y_study = 1 if domain["RATING"]=="YES" else -1 # binarize
else:
y_study = domain["RATING"]
self.y_list[domain["DOMAIN"]].append(y_study)
self.y_uids[domain["DOMAIN"]].append(uid)
domains_done_already.append(domain["DOMAIN"])
self.y = {domain: np.array(self.y_list[domain]) for domain in test_domains}
self.X_uids = np.array(self.X_uids)
self.y_uids = {domain: np.array(self.y_uids[domain]) for domain in test_domains}
class MultiTaskDocumentModel(DocumentLevelModel):
'''
The idea here is to train a single model across all domains. Basically:
y_ij = sign{(w0 + w_j) * x_i}
for document x_i, where a w_j is learned for each domain and w0 is a shared
weight vector (across domains).
'''
def vectorize(self):
self.vectorizer = ModularCountVectorizer()
self.vectorizer.builder_clear()
self.X_mt_labels = [] # which rows correspond to which doc/interactions?
self.y_mt = []
self.uids_to_row_indices = {}
self.row_indices_to_uids, self.row_indices_to_domains = [], []
# number of rows in the 'multi-task' matrix, which
# will vary depending on how many docs have labels
# for how many domains
n_rows = 0 # (equal to len(self.X_mt_labels)
'''
the vectorizer wants all the documents at once,
so here we are going to build them up. we're only
going to add interaction copies for a given document
for those domains that we have an associated label.
'''
docs = []
# which indices in docs correspond to copies for
# which domains?
domains_to_interaction_doc_indices = defaultdict(list)
for i, doc in enumerate(self.X_list):
# `intercept' document
uid = self.X_uids[i]
# add |CORE_DOMAINS| copies for each instance.
for domain in CORE_DOMAINS:
d_str = domain_str(domain)
if uid in self.domain_uids(domain):
# get the label (note that we match up the
# uid to do this)
uids_to_lbls = dict(zip(self.y_uids[domain],
self.y_domain_all(domain=domain)))
#y_index = self.y_uids(domain).index(uid)
#domain_ys = self.y_domain_all(domain=domain)
#self.y_mt.append(domain_ys[y_index])
self.y_mt.append(uids_to_lbls[uid])
# append interaction copy of doc
docs.append(doc)
self.row_indices_to_uids.append(uid)
self.row_indices_to_domains.append(domain)
self.X_mt_labels.append("%s-%s" % (i, d_str))
domains_to_interaction_doc_indices[d_str].append(n_rows)
n_rows += 1
'''
now actually ad documents and interaction copies to
the vectorizer.
'''
#for i, doc in enumerate(self.X_list):
# `intercept' document
self.vectorizer.builder_add_docs(docs)
for domain in CORE_DOMAINS:
d_str = domain_str(domain)
interaction_list = []
for i in xrange(len(docs)):
if i in domains_to_interaction_doc_indices[d_str]:
interaction_list.append(docs[i])
else:
interaction_list.append("")
self.vectorizer.builder_add_docs(interaction_list, prefix=d_str+"-")
# BCW -- attempting to upper bound features!
# note that this will keep the <max_features> most common
# features, regardless of whether or not they are 'interaction'
# features
# self.X = self.vectorizer.builder_fit_transform(max_features=50000)
self.X = self.vectorizer.builder_fit_transform(low=2)
def X_y_uid_filtered(self, uids, domain=None):
X_indices, y = [], []
for i in xrange(self.X.shape[0]):
if domain is None and self.row_indices_to_uids[i] in uids:
# if domain is None, return big multi-task design matrix
# -- you'll want to do this, e.g., for training
X_indices.append(i)
y.append(self.y_mt[i])
elif domain == self.row_indices_to_domains[i] and self.row_indices_to_uids[i] in uids:
# otherwise (when domain is not None), return
# instances for only the target domain
# (e.g., for testing)
X_indices.append(i)
y.append(self.y_mt[i])
return self.X[X_indices], y
class MultiTaskHybridDocumentModel(MultiTaskDocumentModel):
'''
same as the MultiTaskDocumentModel, except takes in sentence
level modelling too into the mix
'''
def vectorize(self):
self.vectorizer = ModularCountVectorizer()
self.vectorizer.builder_clear()
self.X_mt_labels = [] # which rows correspond to which doc/interactions?
self.y_mt = []
self.uids_to_row_indices = {}
self.row_indices_to_uids, self.row_indices_to_domains = [], []
# number of rows in the 'multi-task' matrix, which
# will vary depending on how many docs have labels
# for how many domains
n_rows = 0 # (equal to len(self.X_mt_labels)
'''
the vectorizer wants all the documents at once,
so here we are going to build them up. we're only
going to add interaction copies for a given document
for those domains that we have an associated label.
'''
docs = []
high_prob_sents = defaultdict(list)
# which indices in docs correspond to copies for
# which domains?
domains_to_interaction_doc_indices = defaultdict(list)
for i, doc in enumerate(self.X_list):
# `intercept' document
uid = self.X_uids[i]
# add |CORE_DOMAINS| copies for each instance.
for domain in CORE_DOMAINS:
d_str = domain_str(domain)
if uid in self.domain_uids(domain):
# get the label (note that we match up the
# uid to do this)
uids_to_lbls = dict(zip(self.y_uids[domain],
self.y_domain_all(domain=domain)))
#y_index = self.y_uids(domain).index(uid)
#domain_ys = self.y_domain_all(domain=domain)
#self.y_mt.append(domain_ys[y_index])
self.y_mt.append(uids_to_lbls[uid])
# append interaction copy of doc
docs.append(doc)
high_prob_sents[domain].append(self.get_sent_predictions_for_doc(doc, domain))
for high_prob_domain in CORE_DOMAINS:
if high_prob_domain != domain:
high_prob_sents[high_prob_domain].append("")
self.row_indices_to_uids.append(uid)
self.row_indices_to_domains.append(domain)
self.X_mt_labels.append("%s-%s" % (i, d_str))
domains_to_interaction_doc_indices[d_str].append(n_rows)
n_rows += 1
'''
now actually add documents and interaction copies to
the vectorizer.
'''
#for i, doc in enumerate(self.X_list):
# `intercept' document
self.vectorizer.builder_add_docs(docs)
for domain in CORE_DOMAINS:
d_str = domain_str(domain)
interaction_list, sent_interaction_list = [], []
for i in xrange(len(docs)):
if i in domains_to_interaction_doc_indices[d_str]:
interaction_list.append(docs[i])
sent_interaction_list.append(high_prob_sents[domain][i])
else:
interaction_list.append("")
sent_interaction_list.append("")
self.vectorizer.builder_add_docs(interaction_list, prefix=d_str+"-doc-")
self.vectorizer.builder_add_docs(sent_interaction_list, prefix=d_str+"-sent-")
self.X = self.vectorizer.builder_fit_transform(max_features=200000, low=3)
# self.X = self.vectorizer.builder_fit_transform(max_features=50000)
####
# maybe record the feature indices here that are to receive
# different 'amounts' of regularization
####
def get_sent_predictions_for_doc(self, doc, domain):
# tokenize into sentences
sents = sent_tokenizer.tokenize(doc)
# vectorize the sentences
X_sents = self.sent_vectorizer.transform(sents)
# get predicted 1 / -1 for the sentences
pred_class = self.sent_clfs[domain].predict(X_sents)
# get the sentences which are predicted 1
positive_sents = [sent for sent, pred in zip(sents, pred_class) if pred==1]
# make a single string per doc
rob_sents = " ".join(positive_sents)
return rob_sents
def set_sent_model(self, sent_clfs, sent_vectorizer):
"""
set a model which takes in a list of sentences;
and returns -1 or 1
"""
self.sent_clfs = sent_clfs
self.sent_vectorizer = sent_vectorizer
class HybridDocModel(DocumentLevelModel):
"""
for predicting the risk of bias
as "HIGH", "LOW", or "UNKNOWN" for a document
using a binary bag-of-words as features for each document
"""
def vectorize(self, domain=None):
if domain is None:
raise TypeError("this class requires domain specific vectorization")
self.vectorizer = ModularCountVectorizer()
self.vectorizer.builder_clear()
X_filter = self.domain_X_filter(domain)
predictions = self.get_sent_predictions_for_domain(domain)
self.vectorizer.builder_add_docs([self.X_list[i] for i in X_filter])
self.vectorizer.builder_add_docs(predictions, prefix="high-prob-sent-", weighting=10)
self.X = self.vectorizer.builder_fit_transform()
def get_sent_predictions_for_domain(self, domain):
uids = self.domain_uids(domain)
predictions = []
for uid in uids:
# get the index of the study with specified uid
study_index = np.nonzero(self.X_uids==uid)[0][0]
# tokenize into sentences
sents = sent_tokenizer.tokenize(self.X_list[study_index])
# vectorize the sentences
X_sents = self.sent_vectorizer.transform(sents)
# get predicted 1 / -1 for the sentences
pred_class = self.sent_clf.predict(X_sents)
# get the sentences which are predicted 1
positive_sents = [sent for sent, pred in zip(sents, pred_class) if pred==1]
# make a single string per doc
doc = " ".join(positive_sents)
predictions.append(doc)
return predictions
def set_sent_model(self, doc_clf, doc_vectorizer):
"""
set a model which takes in a list of sentences;
and returns -1 or 1
"""
self.sent_clf = doc_clf
self.sent_vectorizer = doc_vectorizer
def X_y_uid_filtered(self, uids, domain):
X_all = self.X
y_all = self.y_domain_all(domain=domain)
filter_ids = np.nonzero([(y_study_id in uids) for y_study_id in self.y_uids[domain]])[0]
X_filtered = X_all[filter_ids]
y_filtered = y_all[filter_ids]
return X_filtered, y_filtered
# class HybridDocModel2(HybridDocModel):
# """
# for predicting the risk of bias
# as "HIGH", "LOW", or "UNKNOWN" for a document
# using a binary bag-of-words as features for each document
# """
# def vectorize(self, domain=None):
# if domain is None:
# raise TypeError("this class requires domain specific vectorization")
# self.vectorizer = ModularCountVectorizer()
# self.vectorizer.builder_clear()
# X_filter = self.domain_X_filter(domain)
# predictions = self.get_sent_predictions_for_domain(domain)
# # self.vectorizer.builder_add_docs([self.X_list[i] for i in X_filter])
# self.vectorizer.builder_add_docs(predictions, prefix="high-prob-sent-")
# self.X = self.vectorizer.builder_fit_transform()
class HybridModel(SentenceModel):
"""
predicts whether sentences contain risk of bias information
- uses real RoB judgements
"""
def vectorize(self, domain=None, interaction_classes=["YES", "NO"]):
if domain is None:
raise TypeError("this class requires domain specific vectorization")
self.vectorizer = ModularCountVectorizer()
self.vectorizer.builder_clear()
X_filter = self.domain_X_filter(domain)
sents = [self.X_list[i] for i in X_filter]
self.vectorizer.builder_add_docs(sents)
for interaction_class in interaction_classes:
self.vectorizer.builder_add_interaction_features(
sents, self.y_judgements[domain]==interaction_class, prefix="rob-" + interaction_class + "-")
self.X = self.vectorizer.builder_fit_transform()
def X_y_uid_filtered(self, uids, domain):
X_all = self.X
y_all = self.y_domain_all(domain=domain)
filter_ids = np.nonzero([(y_study_id in uids) for y_study_id in self.y_uids[domain]])[0]
X_filtered = X_all[filter_ids]
y_filtered = y_all[filter_ids]
return X_filtered, y_filtered
class HybridModelProbablistic(HybridModel):
"""
predicts whether sentences contain risk of bias information
- requires a model to be passed in which can predice RoB judgements from
full text document
"""
def vectorize(self, domain=None, interaction_classes=["YES", "NO"], use_vectorizer=None):
if domain is None:
raise TypeError("this class requires domain specific vectorization")
if use_vectorizer is None:
self.vectorizer = ModularCountVectorizer()
else:
self.vectorizer = use_vectorizer
self.vectorizer.builder_clear()
X_filter = self.domain_X_filter(domain)
predictions = self.get_doc_predictions_for_domain(domain)
sents = [self.X_list[i] for i in X_filter]
self.vectorizer.builder_add_docs(sents)
for interaction_class in interaction_classes:
self.vectorizer.builder_add_interaction_features(sents, predictions==interaction_class, prefix="rob-" + interaction_class + "-")
if use_vectorizer is None:
self.X = self.vectorizer.builder_fit_transform()
else:
self.X = self.vectorizer.builder_transform()
def get_doc_predictions_for_domain(self, domain):
uids = self.domain_uids(domain)
predictions = []
for uid in uids:
# get the indices of all sentences in the study with specified uid
X_filter = np.nonzero(self.X_uids==uid)[0]
# make a single string per doc
doc = " ".join([self.X_list[i] for i in X_filter])
# vectorize the docs, then predict using the model
X_doc = self.doc_vectorizer.transform(doc)
prediction = self.doc_clf.predict(X_doc)
# add the same prediction for each sentence
predictions.extend([prediction[0]] * len(X_filter))
return np.array(predictions)
def set_doc_model(self, doc_clf, doc_vectorizer):
"""
set a model which takes in a full text doc;
outputs a doc class "YES", "NO", or "UNKNOWN"
"""
self.doc_clf = doc_clf
self.doc_vectorizer = doc_vectorizer
def _document_frequency(X):
"""Count the number of non-zero values for each feature in csc_matrix X."""
return np.diff(X.indptr)
class ModularCountVectorizer():
"""
Similar to CountVectorizer from sklearn, but allows building up
of feature matrix gradually, and adding prefixes to feature names
(to identify interaction terms)
"""
def __init__(self, *args, **kwargs):
self.data = []
self.vectorizer = DictVectorizer(*args, **kwargs)
def _transform_X_to_dict(self, X, prefix=None, weighting=1):
"""
makes a list of dicts from a document
1. word tokenizes
2. creates {word1:1, word2:1...} dicts
(note all set to '1' since the DictVectorizer we use assumes all missing are 0)
"""
return [self._dict_from_word_list(
self._word_tokenize(document, prefix=prefix), weighting=1) for document in X]
def _word_tokenize(self, text, prefix=None, stopword=True):
"""
simple word tokenizer using the same rule as sklearn
punctuation is ignored, all 2 or more letter characters are a word
"""
stop_word_list = STOP_WORDS if stopword else set()
if prefix:
return [prefix + word.lower() for word in SIMPLE_WORD_TOKENIZER.findall(text)
if not word.lower() in stop_word_list]
else:
return [word.lower() for word in SIMPLE_WORD_TOKENIZER.findall(text)
if not word.lower() in stop_word_list]
def _dict_from_word_list(self, word_list, weighting=1):
return {word: weighting for word in word_list}
def _dictzip(self, dictlist1, dictlist2):
"""
zips together two lists of dicts of the same length
"""
# checks lists must be the same length
if len(dictlist1) != len(dictlist2):
raise IndexError("Unable to combine featuresets with different number of examples")
output = []
for dict1, dict2 in zip(dictlist1, dictlist2):
output.append(dict(dict1.items() + dict2.items()))
# note that this *overwrites* any duplicate keys with the key/value from dictlist2!!
return output
def transform(self, X, prefix=None):
# X is a list of document strings
# word tokenizes each one, then passes to a dict vectorizer
dict_list = self._transform_X_to_dict(X, prefix=prefix)
return self.vectorizer.transform(dict_list)
def fit_transform(self, X, prefix=None, max_features=None, low=None):
# X is a list of document strings
# word tokenizes each one, then passes to a dict vectorizer
dict_list = self._transform_X_to_dict(X, prefix=prefix)
X = self.vectorizer.fit_transform(dict_list)
if max_features is not None or low is not None:
X, removed = self._limit_features(X.tocsc(),
self.vectorizer.vocabulary_, low=low, limit=max_features)
print "pruned %s features!" % len(removed)
X = X.tocsc()
return self.vectorizer.fit_transform(dict_list)
def get_feature_names(self):
return self.vectorizer.get_feature_names()
def builder_clear(self):
self.builder = []
self.builder_len = 0
def builder_add_docs(self, X, prefix = None, weighting=1):
#pdb.set_trace()
if not self.builder:
self.builder_len = len(X)
self.builder = self._transform_X_to_dict(X, prefix=prefix, weighting=weighting)
else:
X_dicts = self._transform_X_to_dict(X, prefix=prefix, weighting=weighting)
self.builder = self._dictzip(self.builder, X_dicts)
def builder_add_interaction_features(self, X, interactions, prefix=None):
if prefix is None:
raise TypeError('Prefix is required when adding interaction features')
doc_list = [(sent if interacting else "") for sent, interacting in zip(X, interactions)]
self.builder_add_docs(doc_list, prefix)
def builder_fit_transform(self, max_features=None, low=2):
X = self.vectorizer.fit_transform(self.builder)
if max_features is not None or low is not None:
X, removed = self._limit_features(X.tocsc(),
self.vectorizer.vocabulary_, low=low, limit=max_features)
print "pruned %s features!" % len(removed)
X = X.tocsc()
return X #self.vectorizer.fit_transform(self.builder)
def builder_transform(self):
return self.vectorizer.transform(self.builder)
def _limit_features(self, cscmatrix, vocabulary, high=None, low=None,
limit=None):
"""Remove too rare or too common features.
Prune features that are non zero in more samples than high or less
documents than low, modifying the vocabulary, and restricting it to
at most the limit most frequent.
This does not prune samples with zero features.
"""
if high is None and low is None and limit is None:
return cscmatrix, set()
# Calculate a mask based on document frequencies
dfs = _document_frequency(cscmatrix)
mask = np.ones(len(dfs), dtype=bool)
if high is not None:
mask &= dfs <= high
if low is not None:
mask &= dfs >= low
if limit is not None and mask.sum() > limit:
# backward compatibility requires us to keep lower indices in ties!
# (and hence to reverse the sort by negating dfs)
mask_inds = (-dfs[mask]).argsort()[:limit]
new_mask = np.zeros(len(dfs), dtype=bool)
new_mask[np.where(mask)[0][mask_inds]] = True
mask = new_mask
new_indices = np.cumsum(mask) - 1 # maps old indices to new
removed_terms = set()
for term, old_index in list(six.iteritems(vocabulary)):
if mask[old_index]:
vocabulary[term] = new_indices[old_index]
else:
del vocabulary[term]
removed_terms.add(term)
kept_indices = np.where(mask)[0]
return cscmatrix[:, kept_indices], removed_terms
def sentence_prediction_test(class_weight={1: 5, -1:1}, model=SentenceModel(test_mode=True)):
print
print
print
print "Sentence level prediction"
print "=" * 40
print
s = model
print "Model name:\t" + s.__class__.__name__
print s.__doc__
print "class_weight=%s" % (str(class_weight),)
s.generate_data()
s.vectorize()
for test_domain in CORE_DOMAINS:
print ("*"*40) + "\n\n" + test_domain + "\n\n" + ("*" * 40)
domain_uids = s.domain_uids(test_domain)
no_studies = len(domain_uids)
kf = KFold(no_studies, n_folds=5, shuffle=False, indices=True)
# # tuned_parameters = {"alpha": np.logspace(-4, -1, 10)}
# tuned_parameters = [{"alpha": np.logspace(-4, -1, 5)}, {"class_weight": [{1: i, -1: 1} for i in np.logspace(0, 1, 5)]}]
# clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring='recall')
print "making scorer"
ftwo_scorer = make_scorer(fbeta_score, beta=2)
tuned_parameters = [{"alpha": np.logspace(-4, -1, 10)}, {"class_weight": [{1: i, -1: 1} for i in np.logspace(0, 1, 10)]}]
clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring=ftwo_scorer)
metrics = []
for fold_i, (train, test) in enumerate(kf):
X_train, y_train = s.X_y_uid_filtered(domain_uids[train], test_domain)
X_test, y_test = s.X_y_uid_filtered(domain_uids[test], test_domain)
clf.fit(X_train, y_train)
y_preds = clf.predict(X_test)
fold_metric = np.array(sklearn.metrics.precision_recall_fscore_support(y_test, y_preds))[:,1]
metrics.append(fold_metric) # get the scores for positive instances
print "fold %d:\tprecision %.2f, recall %.2f, f-score %.2f" % (fold_i, fold_metric[0], fold_metric[1], fold_metric[2])
# if not sample and list_features:
# # not an obvious way to get best features for ensemble
# print show_most_informative_features(s.vectorizer, clf)
# summary score
summary_metrics = np.mean(metrics, axis=0)
print "=" * 40
print "mean score:\tprecision %.2f, recall %.2f, f-score %.2f" % (summary_metrics[0], summary_metrics[1], summary_metrics[2])
# then train all for most informative features
clf = SGDClassifier(loss="hinge", penalty="L2", alpha=0.01, class_weight={1: 5, -1: 1})
X_all = s.X_domain_all(test_domain)
y_all = s.y_domain_all(test_domain)
clf.fit(X_all, y_all)
print show_most_informative_features(s.vectorizer, clf)
def stupid_sentence_prediction_test(model=SentenceModel(test_mode=False)):
print
print
print
print "Sentence level prediction"
print "=" * 40
print
s = model
print "Model name:\t" + s.__class__.__name__
print s.__doc__
# print "class_weight=%s" % (str(class_weight),)
s.generate_data()
s.vectorize()
for test_domain in CORE_DOMAINS:
print ("*"*40) + "\n\n" + test_domain + "\n\n" + ("*" * 40)
domain_uids = s.domain_uids(test_domain)
no_studies = len(domain_uids)
kf = KFold(no_studies, n_folds=5, shuffle=False, indices=True)
print "making scorer"
metrics = []
for fold_i, (train, test) in enumerate(kf):
X_test, y_test = s.X_y_uid_filtered(domain_uids[test], test_domain)
y_preds = np.array([1] * len(y_test))
fold_metric = np.array(sklearn.metrics.precision_recall_fscore_support(y_test, y_preds))[:,1]
fold_metric = np.append(fold_metric, accuracy_score(y_test, y_preds))
metrics.append(fold_metric) # get the scores for positive instances
print "fold %d:\tprecision %.2f, recall %.2f, f-score %.2f, precision %.2f" % (fold_i, fold_metric[0], fold_metric[1], fold_metric[2], fold_metric[3])
# if not sample and list_features:
# # not an obvious way to get best features for ensemble
# print show_most_informative_features(s.vectorizer, clf)
# summary score
summary_metrics = np.mean(metrics, axis=0)
print "=" * 40
print "mean score:\tprecision %.2f, recall %.2f, f-score %.2f, precision %.2f" % (summary_metrics[0], summary_metrics[1], summary_metrics[2], summary_metrics[3])
def binary_doc_prediction_test(model=DocumentLevelModel(test_mode=False)):
print
print
print
print "Binary doc prediction"
print "=" * 40
print
s = model
s.generate_data(binarize=True)
s.vectorize()
for test_domain in CORE_DOMAINS:
print ("*"*40) + "\n\n" + test_domain + "\n\n" + ("*" * 40)
domain_uids = s.domain_uids(test_domain)
no_studies = len(domain_uids)
kf = KFold(no_studies, n_folds=5, shuffle=False, indices=True)
# # tuned_parameters = {"alpha": np.logspace(-4, -1, 10)}
# tuned_parameters = [{"alpha": np.logspace(-4, -1, 5)}, {"class_weight": [{1: i, -1: 1} for i in np.logspace(0, 1, 5)]}]
# clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring='recall')
# print "making scorer"
# ftwo_scorer = make_scorer(fbeta_score, beta=2)
tuned_parameters = {"alpha": np.logspace(-4, -1, 10), "class_weight": [{1: i, -1: 1} for i in np.logspace(-1, 1, 10)]}
clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring="f1")
metrics = []
for fold_i, (train, test) in enumerate(kf):
X_train, y_train = s.X_y_uid_filtered(domain_uids[train], test_domain)
X_test, y_test = s.X_y_uid_filtered(domain_uids[test], test_domain)
clf.fit(X_train, y_train)
y_preds = clf.predict(X_test)
fold_metric = np.array(sklearn.metrics.precision_recall_fscore_support(y_test, y_preds))[:,1]
metrics.append(fold_metric) # get the scores for positive instances
print "fold %d:\tprecision %.2f, recall %.2f, f-score %.2f" % (fold_i, fold_metric[0], fold_metric[1], fold_metric[2])
# if not sample and list_features:
# # not an obvious way to get best features for ensemble
# print show_most_informative_features(s.vectorizer, clf)
# summary score
summary_metrics = np.mean(metrics, axis=0)
print "=" * 40
print "mean score:\tprecision %.2f, recall %.2f, f-score %.2f" % (summary_metrics[0], summary_metrics[1], summary_metrics[2])
# then train all for most informative features
clf = SGDClassifier(loss="hinge", penalty="L2", alpha=0.01, class_weight={1: 5, -1: 1})
X_all = s.X_domain_all(test_domain)
y_all = s.y_domain_all(test_domain)
clf.fit(X_all, y_all)
print show_most_informative_features(s.vectorizer, clf)
def multitask_document_prediction_test(model=MultiTaskDocumentModel(test_mode=False),
test_domain=CORE_DOMAINS[0]):
print "multitask!"
d = model
d.generate_data(binarize=True) # some variations use the quote data internally
# for sentence prediction (for additional features)
# d.X_uids contains all the UIds.
# d.y_uids contains a dictionary mapping domains to the UIds for
# which we have labels (in said domain)
#pdb.set_trace()
all_uids = d.X_uids
d.vectorize()
####
# the major change here is we don't loop through the domains!
tuned_parameters = {"alpha": np.logspace(-4, -1, 10)}
clf = GridSearchCV(SGDClassifier(loss="log", penalty="L2"),
tuned_parameters, scoring='f1')
kf = KFold(len(all_uids), n_folds=5, shuffle=False) ### TODO 250 is totally random
metrics = defaultdict(list)
for fold_i, (train, test) in enumerate(kf):
print "Training on fold", fold_i,
# note that we do *not* pass in a domain here, because
# we use *all* domain training data
X_train, y_train = d.X_y_uid_filtered(all_uids[train])
print "done!"
clf.fit(X_train, y_train)
print "Testing on fold", fold_i,
for domain in CORE_DOMAINS:
# multitask uses same trained model for all domains, but test on separate test data
X_test, y_test = d.X_y_uid_filtered(all_uids[test], domain)
y_preds = clf.predict(X_test)
fold_metric = np.array(sklearn.metrics.precision_recall_fscore_support(y_test, y_preds))[:,1]
metrics[domain].append(fold_metric) # get the scores for positive instances (save them up since all in the wrong order here!)
print "done!"
# then recreate in the right order for printout
for domain in CORE_DOMAINS:
print
print domain
print "*" * 60
print
for fold_i, fold_metric in enumerate(metrics[domain]):
print "fold %d:\tprecision %.2f, recall %.2f, f-score %.2f" % (fold_i, fold_metric[0], fold_metric[1], fold_metric[2])
# summary score
summary_metrics = np.mean(metrics[domain], axis=0)
print "=" * 40
print "mean score:\tprecision %.2f, recall %.2f, f-score %.2f" % (summary_metrics[0], summary_metrics[1], summary_metrics[2])
def dummy_document_prediction():
print "dummy!"
d = DocumentLevelModel(test_mode=False)
d.generate_data(binarize=True) # some variations use the quote data internally
# for sentence prediction (for additional features)
d.vectorize()
all_uids = d.X_uids
kf = KFold(len(all_uids), n_folds=5, shuffle=False) ### TODO 250 is totally random
metrics = defaultdict(list)
for fold_i, (train, test) in enumerate(kf):
print "Testing on fold", fold_i,
for domain in CORE_DOMAINS:
# multitask uses same trained model for all domains, but test on separate test data
X_test, y_test = d.X_y_uid_filtered(all_uids[test], domain)
y_preds = np.array(([1] * len(y_test))) # everything gets marked low risk of bias
fold_metric = np.array(sklearn.metrics.precision_recall_fscore_support(y_test, y_preds))[:,1]
metrics[domain].append(fold_metric) # get the scores for positive instances (save them up since all in the wrong order here!)
print "done!"
# then recreate in the right order for printout
for domain in CORE_DOMAINS:
print
print domain
print "*" * 60
print
for fold_i, fold_metric in enumerate(metrics[domain]):
print "fold %d:\tprecision %.2f, recall %.2f, f-score %.2f" % (fold_i, fold_metric[0], fold_metric[1], fold_metric[2])
# summary score
summary_metrics = np.mean(metrics[domain], axis=0)
print "=" * 40
print "mean score:\tprecision %.2f, recall %.2f, f-score %.2f" % (summary_metrics[0], summary_metrics[1], summary_metrics[2])
def multitask_hybrid_document_prediction_test(model=MultiTaskHybridDocumentModel(test_mode=True)):
print "multitask! and hybrid! :)"
d = model
d.generate_data(binarize=True) # some variations use the quote data internally
# for sentence prediction (for additional features)
# d.X_uids contains all the UIds.
# d.y_uids contains a dictionary mapping domains to the UIds for
# which we have labels (in said domain)
#pdb.set_trace()
all_uids = d.X_uids
# d.vectorize()
####
# the major change here is we don't loop through the domains!
tuned_parameters = {"alpha": np.logspace(-4, -1, 10)}
clf = GridSearchCV(SGDClassifier(loss="log", penalty="L2"),
tuned_parameters, scoring='f1')
kf = KFold(len(all_uids), n_folds=5, shuffle=False)
metrics = defaultdict(list)
print "...generating sentence data...",
s = SentenceModel(test_mode=False)
s.generate_data()
s.vectorize()
print "done!"
sent_tuned_parameters = [{"alpha": np.logspace(-4, -1, 5)}, {"class_weight": [{1: i, -1: 1} for i in np.logspace(0, 2, 10)]}]
for fold_i, (train, test) in enumerate(kf):
sent_clfs = defaultdict(list)
for domain in CORE_DOMAINS:
sents_X, sents_y = s.X_domain_all(domain=domain), s.y_domain_all(domain=domain)
sent_clfs[domain] = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"),
tuned_parameters, scoring='recall')
print "Training on fold", fold_i,
d.set_sent_model(sent_clfs, s.vectorizer)
d.vectorize()
# note that we do *not* pass in a domain here, because
# we use *all* domain training data
X_train, y_train = d.X_y_uid_filtered(all_uids[train])
sent_clfs[domain].fit(sents_X, sents_y)
clf.fit(X_train, y_train)
print "done!"
print "Testing on fold", fold_i,
for domain in CORE_DOMAINS:
# multitask uses same trained model for all domains, but test on separate test data
X_test, y_test = d.X_y_uid_filtered(all_uids[test], domain)
y_preds = clf.predict(X_test)
fold_metric = np.array(sklearn.metrics.precision_recall_fscore_support(y_test, y_preds))[:,1]
metrics[domain].append(fold_metric) # get the scores for positive instances (save them up since all in the wrong order here!)
print "done!"
# then recreate in the right order for printout
for domain in CORE_DOMAINS:
print
print domain
print "*" * 60
print
for fold_i, fold_metric in enumerate(metrics[domain]):
print "fold %d:\tprecision %.2f, recall %.2f, f-score %.2f" % (fold_i, fold_metric[0], fold_metric[1], fold_metric[2])
# summary score
summary_metrics = np.mean(metrics[domain], axis=0)
print "=" * 40
print "mean score:\tprecision %.2f, recall %.2f, f-score %.2f" % (summary_metrics[0], summary_metrics[1], summary_metrics[2])
def document_prediction_test(model=DocumentLevelModel(test_mode=False)):
print "Document level prediction"
print "=" * 40
print
d = model
d.generate_data() # some variations use the quote data internally
# for sentence prediction (for additional features)
d.vectorize()
for test_domain in CORE_DOMAINS:
print ("*"*40) + "\n\n" + test_domain + "\n\n" + ("*" * 40)
# f1_prefer_nos = make_scorer(f1_score, pos_label="NO")
tuned_parameters = {"alpha": np.logspace(-4, -1, 10)}
clf = GridSearchCV(SGDClassifier(loss="log", penalty="L2"), tuned_parameters, scoring='f1')
# clf = SGDClassifier(loss="hinge", penalty="L2")
domain_uids = d.domain_uids(test_domain)
no_studies = len(domain_uids)
kf = KFold(no_studies, n_folds=5, shuffle=False)
metrics = []
for fold_i, (train, test) in enumerate(kf):
X_train, y_train = d.X_y_uid_filtered(domain_uids[train], test_domain)
X_test, y_test = d.X_y_uid_filtered(domain_uids[test], test_domain)
clf.fit(X_train, y_train)
y_preds = clf.predict(X_test)
fold_metric = np.array(sklearn.metrics.precision_recall_fscore_support(y_test, y_preds, labels=RoB_CLASSES))[:3]
print ('fold %d\t' % (fold_i)) + '\t'.join(RoB_CLASSES)
# for metric_type, scores in zip(["prec.", "recall", "f1"], fold_metric):
# print "%s\t%.2f\t%.2f\t%.2f" % (metric_type, scores[0], scores[1], scores[2])
# print
# print clf.best_params_
#### START CONFUSION
real_no_indices = (y_test=="NO")
print "The actual NOs were predicted as..."
print collections.Counter(y_preds[real_no_indices])
#### END CONFUSION
metrics.append(fold_metric) # get the scores for positive instances
# print "fold %d:\tprecision %.2f, recall %.2f, f-score %.2f" % (fold_i, fold_metric[0], fold_metric[1], fold_metric[2])
mean_scores = np.mean(metrics, axis=0)
print "=" * 40
print 'means \t' + '\t'.join(RoB_CLASSES)
for metric_type, scores in zip(["prec.", "recall", "f1"], mean_scores):
print "%s\t%.2f\t%.2f\t%.2f" % (metric_type, scores[0], scores[1], scores[2])
print
# then train all for most informative features
clf = SGDClassifier(loss="hinge", penalty="L2", alpha=0.01)
X_all = d.X_domain_all(test_domain)
y_all = d.y_domain_all(test_domain)
clf.fit(X_all, y_all)
print show_most_informative_features_ynu(d.vectorizer, clf)
def simple_hybrid_prediction_test(model=HybridModel(test_mode=True)):
print "Hybrid prediction"
print "=" * 40
print
s = model
s.generate_data() # some variations use the quote data internally
# for sentence prediction (for additional features)
for test_domain in CORE_DOMAINS:
s.vectorize(test_domain)
print ("*"*40) + "\n\n" + test_domain + "\n\n" + ("*" * 40)
domain_uids = s.domain_uids(test_domain)
no_studies = len(domain_uids)
kf = KFold(no_studies, n_folds=5, shuffle=False)
# tuned_parameters = [{"alpha": np.logspace(-4, -1, 5)}, {"class_weight": [{1: i, -1: 1} for i in np.logspace(0, 1, 5)]}]
# clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring='f1')
print "making scorer"
ftwo_scorer = make_scorer(fbeta_score, beta=2)
tuned_parameters = [{"alpha": np.logspace(-4, -1, 10)}, {"class_weight": [{1: i, -1: 1} for i in np.logspace(0, 1, 10)]}]
clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring=ftwo_scorer)
metrics = []
for fold_i, (train, test) in enumerate(kf):
X_train, y_train = s.X_y_uid_filtered(domain_uids[train], test_domain)
X_test, y_test = s.X_y_uid_filtered(domain_uids[test], test_domain)
clf.fit(X_train, y_train)
y_preds = clf.predict(X_test)
fold_metric = np.array(sklearn.metrics.precision_recall_fscore_support(y_test, y_preds))[:,1]
metrics.append(fold_metric) # get the scores for positive instances
print "fold %d:\tprecision %.2f, recall %.2f, f-score %.2f" % (fold_i, fold_metric[0], fold_metric[1], fold_metric[2])
metrics.append(fold_metric) # get the scores for positive instances
# summary score
summary_metrics = np.mean(metrics, axis=0)
print "=" * 40
print "mean score:\tprecision %.2f, recall %.2f, f-score %.2f" % (summary_metrics[0], summary_metrics[1], summary_metrics[2])
# def simple_hybrid_prediction_test(model=HybridModel(test_mode=True)):
# print "Hybrid prediction"
# print "=" * 40
# print
# s = model
# s.generate_data() # some variations use the quote data internally
# # for sentence prediction (for additional features)
# for test_domain in CORE_DOMAINS:
# s.vectorize(test_domain)
# print ("*"*40) + "\n\n" + test_domain + "\n\n" + ("*" * 40)
# domain_uids = s.domain_uids(test_domain)
# no_studies = len(domain_uids)
# kf = KFold(no_studies, n_folds=5, shuffle=False)
# tuned_parameters = [{"alpha": np.logspace(-4, -1, 5)}, {"class_weight": [{1: i, -1: 1} for i in np.logspace(0, 1, 5)]}]
# clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring='f1')
# metrics = []
# for fold_i, (train, test) in enumerate(kf):
# X_train, y_train = s.X_y_uid_filtered(domain_uids[train], test_domain)
# X_test, y_test = s.X_y_uid_filtered(domain_uids[test], test_domain)
# clf.fit(X_train, y_train)
# y_preds = clf.predict(X_test)
# fold_metric = np.array(sklearn.metrics.precision_recall_fscore_support(y_test, y_preds))[:,1]
# metrics.append(fold_metric) # get the scores for positive instances
# print "fold %d:\tprecision %.2f, recall %.2f, f-score %.2f" % (fold_i, fold_metric[0], fold_metric[1], fold_metric[2])
# metrics.append(fold_metric) # get the scores for positive instances
# # summary score
# summary_metrics = np.mean(metrics, axis=0)
# print "=" * 40
# print "mean score:\tprecision %.2f, recall %.2f, f-score %.2f" % (summary_metrics[0], summary_metrics[1], summary_metrics[2])
def true_hybrid_prediction_test(model, test_mode=False):
print "True Hybrid prediction"
print "=" * 40
print
s = model
s.generate_data() # some variations use the quote data internally
# for sentence prediction (for additional features)
s_cheat = HybridModel(test_mode=False)
s_cheat.generate_data()
for test_domain in CORE_DOMAINS:
print ("*"*40) + "\n\n" + test_domain + "\n\n" + ("*" * 40)
domain_uids = s.domain_uids(test_domain)
no_studies = len(domain_uids)
kf = KFold(no_studies, n_folds=5, shuffle=False)
print "making scorer"
ftwo_scorer = make_scorer(fbeta_score, beta=2)
tuned_parameters = [{"alpha": np.logspace(-4, -1, 10)}, {"class_weight": [{1: i, -1: 1} for i in np.logspace(0, 1, 10)]}]
clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring=ftwo_scorer)
metrics = []
for fold_i, (train, test) in enumerate(kf):
print "training doc level model with test data, please wait..."
d = DocumentLevelModel(test_mode=False)
d.generate_data(uid_filter=domain_uids[train])
d.vectorize()
doc_X, doc_y = d.X_domain_all(domain=test_domain), d.y_domain_all(domain=test_domain)
doc_tuned_parameters = {"alpha": np.logspace(-4, -1, 10)}
doc_clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), doc_tuned_parameters, scoring='f1')
doc_clf.fit(doc_X, doc_y)
s.set_doc_model(doc_clf, d.vectorizer)
s_cheat.vectorize(test_domain)
s.vectorize(test_domain, use_vectorizer=s_cheat.vectorizer)
X_train, y_train = s_cheat.X_y_uid_filtered(domain_uids[train], test_domain)
# train on the *true* labels
X_test, y_test = s.X_y_uid_filtered(domain_uids[test], test_domain)
clf.fit(X_train, y_train)
y_preds = clf.predict(X_test)
fold_metric = np.array(sklearn.metrics.precision_recall_fscore_support(y_test, y_preds))[:,1]
metrics.append(fold_metric) # get the scores for positive instances
print "fold %d:\tprecision %.2f, recall %.2f, f-score %.2f" % (fold_i, fold_metric[0], fold_metric[1], fold_metric[2])
metrics.append(fold_metric) # get the scores for positive instances
# summary score
summary_metrics = np.mean(metrics, axis=0)
print "=" * 40
print "mean score:\tprecision %.2f, recall %.2f, f-score %.2f" % (summary_metrics[0], summary_metrics[1], summary_metrics[2])
def hybrid_doc_prediction_test(model=HybridDocModel(test_mode=True)):
print "Hybrid doc level prediction"
print "=" * 40
print
d = model
d.generate_data() # some variations use the quote data internally
# for sentence prediction (for additional features)
for test_domain in CORE_DOMAINS:
print ("*"*40) + "\n\n" + test_domain + "\n\n" + ("*" * 40)
domain_uids = d.domain_uids(test_domain)
no_studies = len(domain_uids)
kf = KFold(no_studies, n_folds=5, shuffle=False)
tuned_parameters = {"alpha": np.logspace(-4, -1, 5)}
clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring='f1')
metrics = []
for fold_i, (train, test) in enumerate(kf):
s = SentenceModel(test_mode=False)
s.generate_data(uid_filter=domain_uids[train])
s.vectorize()
sents_X, sents_y = s.X_domain_all(domain=test_domain), s.y_domain_all(domain=test_domain)
sent_tuned_parameters = [{"alpha": np.logspace(-4, -1, 5)}, {"class_weight": [{1: i, -1: 1} for i in np.logspace(0, 2, 10)]}]
sent_clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring='recall')
sent_clf.fit(sents_X, sents_y)
d.set_sent_model(sent_clf, s.vectorizer)
d.vectorize(test_domain)
X_train, y_train = d.X_y_uid_filtered(domain_uids[train], test_domain)
X_test, y_test = d.X_y_uid_filtered(domain_uids[test], test_domain)
clf.fit(X_train, y_train)
y_preds = clf.predict(X_test)
fold_metric = np.array(sklearn.metrics.precision_recall_fscore_support(y_test, y_preds, labels=RoB_CLASSES))[:3]
print ('fold %d\t' % (fold_i)) + '\t'.join(RoB_CLASSES)
for metric_type, scores in zip(["prec.", "recall", "f1"], fold_metric):
print "%s\t%.2f\t%.2f\t%.2f" % (metric_type, scores[0], scores[1], scores[2])
print
metrics.append(fold_metric) # get the scores for positive instances
# print "fold %d:\tprecision %.2f, recall %.2f, f-score %.2f" % (fold_i, fold_metric[0], fold_metric[1], fold_metric[2])
mean_scores = np.mean(metrics, axis=0)
print "=" * 40
print 'means \t' + '\t'.join(RoB_CLASSES)
for metric_type, scores in zip(["prec.", "recall", "f1"], mean_scores):
print "%s\t%.2f\t%.2f\t%.2f" % (metric_type, scores[0], scores[1], scores[2])
print
def binary_hybrid_doc_prediction_test(model=HybridDocModel(test_mode=True)):
print "Binary hybrid doc level prediction"
print "=" * 40
print
d = model
d.generate_data(binarize=True) # some variations use the quote data internally
# for sentence prediction (for additional features)
for test_domain in CORE_DOMAINS:
print ("*"*40) + "\n\n" + test_domain + "\n\n" + ("*" * 40)
domain_uids = d.domain_uids(test_domain)
no_studies = len(domain_uids)
kf = KFold(no_studies, n_folds=5, shuffle=False)
tuned_parameters = {"alpha": np.logspace(-4, -1, 10), "class_weight": [{1: i, -1: 1} for i in np.logspace(-1, 1, 10)]}
clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring='f1')
metrics = []
for fold_i, (train, test) in enumerate(kf):
s = SentenceModel(test_mode=True)
s.generate_data(uid_filter=domain_uids[train])
s.vectorize()
sents_X, sents_y = s.X_domain_all(domain=test_domain), s.y_domain_all(domain=test_domain)
sent_tuned_parameters = [{"alpha": np.logspace(-4, -1, 5)}, {"class_weight": [{1: i, -1: 1} for i in np.logspace(0, 2, 10)]}]
sent_clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring='recall')
sent_clf.fit(sents_X, sents_y)
d.set_sent_model(sent_clf, s.vectorizer)
d.vectorize(test_domain)
X_train, y_train = d.X_y_uid_filtered(domain_uids[train], test_domain)
X_test, y_test = d.X_y_uid_filtered(domain_uids[test], test_domain)
clf.fit(X_train, y_train)
y_preds = clf.predict(X_test)
fold_metric = np.array(sklearn.metrics.precision_recall_fscore_support(y_test, y_preds))[:,1]
metrics.append(fold_metric) # get the scores for positive instances
print "fold %d:\tprecision %.2f, recall %.2f, f-score %.2f" % (fold_i, fold_metric[0], fold_metric[1], fold_metric[2])
metrics.append(fold_metric) # get the scores for positive instances
# print "fold %d:\tprecision %.2f, recall %.2f, f-score %.2f" % (fold_i, fold_metric[0], fold_metric[1], fold_metric[2])
summary_metrics = np.mean(metrics, axis=0)
print "=" * 40
print "mean score:\tprecision %.2f, recall %.2f, f-score %.2f" % (summary_metrics[0], summary_metrics[1], summary_metrics[2])
# then train all for most informative features
s = SentenceModel(test_mode=True)
s.generate_data(uid_filter=domain_uids)
s.vectorize()
sents_X, sents_y = s.X_domain_all(domain=test_domain), s.y_domain_all(domain=test_domain)
sent_tuned_parameters = [{"alpha": np.logspace(-4, -1, 5)}, {"class_weight": [{1: i, -1: 1} for i in np.logspace(0, 2, 10)]}]
sent_clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring='recall')
sent_clf.fit(sents_X, sents_y)
d.set_sent_model(sent_clf, s.vectorizer)
d.vectorize(test_domain)
clf = SGDClassifier(loss="hinge", penalty="L2", alpha=0.1, class_weight={1: 1, -1: 1})
X_all, y_all = d.X_y_uid_filtered(domain_uids, test_domain)
clf.fit(X_all, y_all)
print show_most_informative_features(s.vectorizer, clf)
def binary_hybrid_doc_prediction_test2(model=HybridDocModel(test_mode=True)):
print "Binary hybrid doc level prediction version 2 (maybe quicker!!)"
print "=" * 40
print
d = model
d.generate_data(binarize=True) # some variations use the quote data internally
# for sentence prediction (for additional features)
for test_domain in CORE_DOMAINS:
print ("*"*40) + "\n\n" + test_domain + "\n\n" + ("*" * 40)
domain_uids = d.domain_uids(test_domain)
no_studies = len(domain_uids)
kf = KFold(no_studies, n_folds=5, shuffle=False)
tuned_parameters = {"alpha": np.logspace(-4, -1, 10), "class_weight": [{1: i, -1: 1} for i in np.logspace(-1, 1, 10)]}
clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring='f1')
metrics = []
s = SentenceModel(test_mode=True)
s.generate_data(uid_filter=domain_uids)
s.vectorize()
for fold_i, (train, test) in enumerate(kf):
sents_X, sents_y = s.X_y_uid_filtered(domain_uids[test], test_domain)
# sent_tuned_parameters = [{"alpha": np.logspace(-4, -1, 5)}, {"class_weight": [{1: i, -1: 1} for i in np.logspace(0, 2, 10)]}]
# sent_clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring='recall')
sent_tuned_parameters = [{"alpha": np.logspace(-4, -1, 5)}]
sent_clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2", class_weight={1:5, -1:1}), sent_tuned_parameters, scoring='recall')
sent_clf.fit(sents_X, sents_y)
d.set_sent_model(sent_clf, s.vectorizer)
d.vectorize(test_domain)
X_train, y_train = d.X_y_uid_filtered(domain_uids[train], test_domain)
X_test, y_test = d.X_y_uid_filtered(domain_uids[test], test_domain)
clf.fit(X_train, y_train)
# print show_most_informative_features(s.vectorizer, clf.best_estimator_)
print show_most_informative_features(s.vectorizer, clf)
# y_preds = clf.predict(X_test)
# fold_metric = np.array(sklearn.metrics.precision_recall_fscore_support(y_test, y_preds))[:,1]
# metrics.append(fold_metric) # get the scores for positive instances
# print "fold %d:\tprecision %.2f, recall %.2f, f-score %.2f" % (fold_i, fold_metric[0], fold_metric[1], fold_metric[2])
# metrics.append(fold_metric) # get the scores for positive instances
# summary_metrics = np.mean(metrics, axis=0)
# print "=" * 40
# print "mean score:\tprecision %.2f, recall %.2f, f-score %.2f" % (summary_metrics[0], summary_metrics[1], summary_metrics[2])
# # then train all for most informative features
# sents_X, sents_y = s.X_domain_all(domain=test_domain), s.y_domain_all(domain=test_domain)
# sent_tuned_parameters = [{"alpha": np.logspace(-4, -1, 5)}, {"class_weight": [{1: i, -1: 1} for i in np.logspace(0, 2, 10)]}]
# sent_clf = GridSearchCV(SGDClassifier(loss="hinge", penalty="L2"), tuned_parameters, scoring='recall')
# sent_clf.fit(sents_X, sents_y)
# d.set_sent_model(sent_clf, s.vectorizer)
# d.vectorize(test_domain)
# clf = SGDClassifier(loss="hinge", penalty="L2", alpha=0.5, class_weight={1: 1, -1: 1})
# X_all, y_all = d.X_y_uid_filtered(domain_uids, test_domain)
# clf.fit(X_all, y_all)
def main():
# dummy_document_prediction()
stupid_sentence_prediction_test()
# true_hybrid_prediction_test(model=HybridModelProbablistic(test_mode=False))
# sentence_prediction_test(model=SentenceModel(test_mode=False))
# simple_hybrid_prediction_test(model=HybridModel(test_mode=False))
# binary_doc_prediction_test()
#print "Try weighting sentences better"
#binary_hybrid_doc_prediction_test2()
# binary_hybrid_doc_prediction_test()
# hybrid_doc_prediction_test(model=HybridDocModel2(test_mode=False))
# document_prediction_test(model=DocumentLevelModel(test_mode=False))
# multitask_document_prediction_test(model=MultiTaskDocumentModel(test_mode=False))
# multitask_hybrid_document_prediction_test(model=MultiTaskHybridDocumentModel(test_mode=False))
if __name__ == '__main__':
main()
| gpl-3.0 |
foodszhang/kbengine | kbe/src/lib/python/Lib/test/test_unpack.py | 174 | 2619 | doctests = """
Unpack tuple
>>> t = (1, 2, 3)
>>> a, b, c = t
>>> a == 1 and b == 2 and c == 3
True
Unpack list
>>> l = [4, 5, 6]
>>> a, b, c = l
>>> a == 4 and b == 5 and c == 6
True
Unpack implied tuple
>>> a, b, c = 7, 8, 9
>>> a == 7 and b == 8 and c == 9
True
Unpack string... fun!
>>> a, b, c = 'one'
>>> a == 'o' and b == 'n' and c == 'e'
True
Unpack generic sequence
>>> class Seq:
... def __getitem__(self, i):
... if i >= 0 and i < 3: return i
... raise IndexError
...
>>> a, b, c = Seq()
>>> a == 0 and b == 1 and c == 2
True
Single element unpacking, with extra syntax
>>> st = (99,)
>>> sl = [100]
>>> a, = st
>>> a
99
>>> b, = sl
>>> b
100
Now for some failures
Unpacking non-sequence
>>> a, b, c = 7
Traceback (most recent call last):
...
TypeError: 'int' object is not iterable
Unpacking tuple of wrong size
>>> a, b = t
Traceback (most recent call last):
...
ValueError: too many values to unpack (expected 2)
Unpacking tuple of wrong size
>>> a, b = l
Traceback (most recent call last):
...
ValueError: too many values to unpack (expected 2)
Unpacking sequence too short
>>> a, b, c, d = Seq()
Traceback (most recent call last):
...
ValueError: need more than 3 values to unpack
Unpacking sequence too long
>>> a, b = Seq()
Traceback (most recent call last):
...
ValueError: too many values to unpack (expected 2)
Unpacking a sequence where the test for too long raises a different kind of
error
>>> class BozoError(Exception):
... pass
...
>>> class BadSeq:
... def __getitem__(self, i):
... if i >= 0 and i < 3:
... return i
... elif i == 3:
... raise BozoError
... else:
... raise IndexError
...
Trigger code while not expecting an IndexError (unpack sequence too long, wrong
error)
>>> a, b, c, d, e = BadSeq()
Traceback (most recent call last):
...
test.test_unpack.BozoError
Trigger code while expecting an IndexError (unpack sequence too short, wrong
error)
>>> a, b, c = BadSeq()
Traceback (most recent call last):
...
test.test_unpack.BozoError
"""
__test__ = {'doctests' : doctests}
def test_main(verbose=False):
from test import support
from test import test_unpack
support.run_doctest(test_unpack, verbose)
if __name__ == "__main__":
test_main(verbose=True)
| lgpl-3.0 |
MLAB-project/weewx | examples/pmon/bin/user/pmon.py | 4 | 5857 | # Copyright 2013 Matthew Wall
"""weewx module that records process information.
Installation
Put this file in the bin/user directory.
Configuration
Add the following to weewx.conf:
[ProcessMonitor]
data_binding = pmon_binding
[DataBindings]
[[pmon_binding]]
database = pmon_sqlite
manager = weewx.manager.DaySummaryManager
table_name = archive
schema = user.pmon.schema
[Databases]
[[pmon_sqlite]]
database_name = archive/pmon.sdb
database_type = SQLite
[Engine]
[[Services]]
archive_services = ..., user.pmon.ProcessMonitor
"""
import os
import platform
import re
import syslog
import time
from subprocess import Popen, PIPE
import weewx
import weedb
import weeutil.weeutil
from weewx.engine import StdService
VERSION = "0.4"
def logmsg(level, msg):
syslog.syslog(level, 'pmon: %s' % msg)
def logdbg(msg):
logmsg(syslog.LOG_DEBUG, msg)
def loginf(msg):
logmsg(syslog.LOG_INFO, msg)
def logerr(msg):
logmsg(syslog.LOG_ERR, msg)
schema = [
('dateTime', 'INTEGER NOT NULL PRIMARY KEY'),
('usUnits', 'INTEGER NOT NULL'),
('interval', 'INTEGER NOT NULL'),
('mem_vsz', 'INTEGER'),
('mem_rss', 'INTEGER'),
]
class ProcessMonitor(StdService):
def __init__(self, engine, config_dict):
super(ProcessMonitor, self).__init__(engine, config_dict)
d = config_dict.get('ProcessMonitor', {})
self.process = d.get('process', 'weewxd')
self.max_age = weeutil.weeutil.to_int(d.get('max_age', 2592000))
# get the database parameters we need to function
binding = d.get('data_binding', 'pmon_binding')
self.dbm = self.engine.db_binder.get_manager(data_binding=binding,
initialize=True)
# be sure database matches the schema we have
dbcol = self.dbm.connection.columnsOf(self.dbm.table_name)
dbm_dict = weewx.manager.get_manager_dict_from_config(config_dict, binding)
memcol = [x[0] for x in dbm_dict['schema']]
if dbcol != memcol:
raise Exception('pmon schema mismatch: %s != %s' % (dbcol, memcol))
self.last_ts = None
self.bind(weewx.NEW_ARCHIVE_RECORD, self.new_archive_record)
def shutDown(self):
try:
self.dbm.close()
except weedb.DatabaseError:
pass
def new_archive_record(self, event):
"""save data to database then prune old records as needed"""
now = int(time.time() + 0.5)
delta = now - event.record['dateTime']
if delta > event.record['interval'] * 60:
logdbg("Skipping record: time difference %s too big" % delta)
return
if self.last_ts is not None:
self.save_data(self.get_data(now, self.last_ts))
self.last_ts = now
if self.max_age is not None:
self.prune_data(now - self.max_age)
def save_data(self, record):
"""save data to database"""
self.dbm.addRecord(record)
def prune_data(self, ts):
"""delete records with dateTime older than ts"""
sql = "delete from %s where dateTime < %d" % (self.dbm.table_name, ts)
self.dbm.getSql(sql)
try:
# sqlite databases need some help to stay small
self.dbm.getSql('vacuum')
except weedb.DatabaseError:
pass
COLUMNS = re.compile('[\S]+\s+[\d]+\s+[\d.]+\s+[\d.]+\s+([\d]+)\s+([\d]+)')
def get_data(self, now_ts, last_ts):
record = dict()
record['dateTime'] = now_ts
record['usUnits'] = weewx.METRIC
record['interval'] = int((now_ts - last_ts) / 60)
try:
cmd = 'ps aux'
p = Popen(cmd, shell=True, stdout=PIPE)
o = p.communicate()[0]
for line in o.split('\n'):
if line.find(self.process) >= 0:
m = self.COLUMNS.search(line)
if m:
record['mem_vsz'] = int(m.group(1))
record['mem_rss'] = int(m.group(2))
except (ValueError, IOError, KeyError), e:
logerr('apcups_info failed: %s' % e)
return record
# what follows is a basic unit test of this module. to run the test:
#
# cd /home/weewx
# PYTHONPATH=bin python bin/user/pmon.py
#
if __name__ == "__main__":
from weewx.engine import StdEngine
config = {
'Station': {
'station_type': 'Simulator',
'altitude': [0, 'foot'],
'latitude': 0,
'longitude': 0},
'Simulator': {
'driver': 'weewx.drivers.simulator',
'mode': 'simulator'},
'ProcessMonitor': {
'data_binding': 'pmon_binding',
'process': 'weewxd'},
'DataBindings': {
'pmon_binding': {
'database': 'pmon_sqlite',
'manager': 'weewx.manager.DaySummaryManager',
'table_name': 'archive',
'schema': 'user.pmon.schema'}},
'Databases': {
'pmon_sqlite': {
'database_name': 'pmon.sdb',
'database_type': 'SQLite'}},
'DatabaseTypes': {
'SQLite': {
'driver': 'weedb.sqlite',
'SQLITE_ROOT': '/var/tmp'}},
'Engine': {
'Services': {
'process_services': 'user.pmon.ProcessMonitor'}}}
eng = StdEngine(config)
svc = ProcessMonitor(eng, config)
nowts = lastts = int(time.time())
rec = svc.get_data(nowts, lastts)
print rec
time.sleep(5)
nowts = int(time.time())
rec = svc.get_data(nowts, lastts)
print rec
time.sleep(5)
lastts = nowts
nowts = int(time.time())
rec = svc.get_data(nowts, lastts)
print rec
os.remove('/var/tmp/pmon.sdb')
| gpl-3.0 |
darkleons/BE | openerp/report/common.py | 457 | 3337 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 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/>.
#
##############################################################################
pageSize = {
'A4': (210,297),
'A5': (148.5,105)
}
odt_namespace = {
"office":"{urn:oasis:names:tc:opendocument:xmlns:office:1.0}",
"style":"{urn:oasis:names:tc:opendocument:xmlns:style:1.0}",
"text":"{urn:oasis:names:tc:opendocument:xmlns:text:1.0}",
"table":"{urn:oasis:names:tc:opendocument:xmlns:table:1.0}",
"draw":"{urn:oasis:names:tc:opendocument:xmlns:drawing:1.0}",
"fo":"{urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0}",
"xlink":"{http://www.w3.org/1999/xlink}",
"dc":"{http://purl.org/dc/elements/1.1/}",
"meta":"{urn:oasis:names:tc:opendocument:xmlns:meta:1.0}",
"number":"{urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0}",
"svg":"{urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0}",
"chart":"{urn:oasis:names:tc:opendocument:xmlns:chart:1.0}",
"dr3d":"{urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0}",
"math":"{http://www.w3.org/1998/Math/MathML}",
"form":"{urn:oasis:names:tc:opendocument:xmlns:form:1.0}",
"script":"{urn:oasis:names:tc:opendocument:xmlns:script:1.0}",
"ooo":"{http://openoffice.org/2004/office}",
"ooow":"{http://openoffice.org/2004/writer}",
"oooc":"{http://openoffice.org/2004/calc}",
"dom":"{http://www.w3.org/2001/xml-events}" }
sxw_namespace = {
"office":"{http://openoffice.org/2000/office}",
"style":"{http://openoffice.org/2000/style}",
"text":"{http://openoffice.org/2000/text}",
"table":"{http://openoffice.org/2000/table}",
"draw":"{http://openoffice.org/2000/drawing}",
"fo":"{http://www.w3.org/1999/XSL/Format}",
"xlink":"{http://www.w3.org/1999/xlink}",
"dc":"{http://purl.org/dc/elements/1.1/}",
"meta":"{http://openoffice.org/2000/meta}",
"number":"{http://openoffice.org/2000/datastyle}",
"svg":"{http://www.w3.org/2000/svg}",
"chart":"{http://openoffice.org/2000/chart}",
"dr3d":"{http://openoffice.org/2000/dr3d}",
"math":"{http://www.w3.org/1998/Math/MathML}",
"form":"{http://openoffice.org/2000/form}",
"script":"{http://openoffice.org/2000/script}",
"ooo":"{http://openoffice.org/2004/office}",
"ooow":"{http://openoffice.org/2004/writer}",
"oooc":"{http://openoffice.org/2004/calc}",
"dom":"{http://www.w3.org/2001/xml-events}"}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
jakerockland/find-s | find-s.py | 1 | 3211 | # This program is an machine learning experiment with the FindS concept learning algorithm
# Based on an excercise from Machine Learning by Thomas Mitchell (1997)
# By: Jacob Rockland
#
# The attribute EnjoySport indicates whether or not Aldo enjoys his favorite
# water sport on this day
#
# For all possible days with the following attributes:
# Sky: Sunny/Rainy
# AirTemp: Warm/Cold
# Humidity: Normal/High
# Wind: Strong/Weak
# Water: Warm/Cool
# Forecast: Same/Change
#
# Let us represent the hypothesis with the vector:
# [Sky, AirTemp, Humidity, Wind, Water, Forecast]
#
# Where each constraint may be '?' to represent that any value is acceptable,
# '0' to represent that no value is acceptable, or a specific value (from above)
#
# A training example for the hypothesis is True if it correctly predicts that
# Aldo will enjoy his water sport on this day, and False otherwise
import random
attributes = [['Sunny','Rainy'],
['Warm','Cold'],
['Normal','High'],
['Strong','Weak'],
['Warm','Cool'],
['Same','Change']]
num_attributes = len(attributes)
def getRandomTrainingExample(target_concept = ['?'] * num_attributes):
training_example = []
classification = True
for i in range(num_attributes):
training_example.append(attributes[i][random.randint(0,1)])
if target_concept[i] != '?' and target_concept[i] != training_example[i]:
classification = False
return training_example, classification
def findS(training_examples = []):
hypothesis = ['0'] * num_attributes
for example in training_examples:
if example[1]:
for i in range(num_attributes):
example_attribute = example[0][i]
hypothesis_attribute = hypothesis[i]
if example_attribute == attributes[i][0]:
if hypothesis_attribute == '0':
hypothesis_attribute = attributes[i][0]
elif hypothesis_attribute == attributes[i][1]:
hypothesis_attribute = '?'
elif example_attribute == attributes[i][1]:
if hypothesis_attribute == '0':
hypothesis_attribute = attributes[i][1]
elif hypothesis_attribute == attributes[i][0]:
hypothesis_attribute = '?'
hypothesis[i] = hypothesis_attribute
return hypothesis
def experiment(target_concept = ['?'] * num_attributes):
training_examples = []
while findS(training_examples) != target_concept:
training_examples.append(getRandomTrainingExample(target_concept))
return len(training_examples)
def main():
target_concept = ['Sunny','Warm','?','?','?','?']
num_experiments = 1000
experiment_results = []
for i in range(num_experiments):
experiment_results.append(experiment(target_concept))
average_result = sum(experiment_results) / num_experiments
print(str(len(experiment_results)) + ' Experiments Ran')
print('Average # Examples Required: ' + str(average_result))
print('Target Concept:' + str(target_concept))
if __name__ == "__main__":
main()
| mit |
shssoichiro/servo | tests/wpt/css-tests/css-text-decor-3_dev/xhtml1/support/generate-text-emphasis-ruby-tests.py | 829 | 3042 | #!/usr/bin/env python
# - * - coding: UTF-8 - * -
"""
This script generates tests text-emphasis-ruby-001 ~ 004 which tests
emphasis marks with ruby in four directions. It outputs a list of all
tests it generated in the format of Mozilla reftest.list to the stdout.
"""
from __future__ import unicode_literals
TEST_FILE = 'text-emphasis-ruby-{:03}{}.html'
TEST_TEMPLATE = '''<!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Test: text-emphasis and ruby, {wm}, {pos}</title>
<link rel="author" title="Xidorn Quan" href="https://www.upsuper.org">
<link rel="author" title="Mozilla" href="https://www.mozilla.org">
<link rel="help" href="https://drafts.csswg.org/css-text-decor-3/#text-emphasis-position-property">
<meta name="assert" content="emphasis marks are drawn outside the ruby">
<link rel="match" href="text-emphasis-ruby-{index:03}-ref.html">
<p>Pass if the emphasis marks are outside the ruby:</p>
<div style="line-height: 5; writing-mode: {wm}; ruby-position: {ruby_pos}; text-emphasis-position: {posval}">ルビ<span style="text-emphasis: circle">と<ruby>圏<rt>けん</rt>点<rt>てん</rt></ruby>を</span>同時</div>
'''
REF_FILE = 'text-emphasis-ruby-{:03}-ref.html'
REF_TEMPLATE = '''<!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Reference: text-emphasis and ruby, {wm}, {pos}</title>
<link rel="author" title="Xidorn Quan" href="https://www.upsuper.org">
<link rel="author" title="Mozilla" href="https://www.mozilla.org">
<style> rtc {{ font-variant-east-asian: inherit; }} </style>
<p>Pass if the emphasis marks are outside the ruby:</p>
<div style="line-height: 5; writing-mode: {wm}; ruby-position: {posval}">ルビ<ruby>と<rtc>●</rtc>圏<rt>けん</rt><rtc>●</rtc>点<rt>てん</rt><rtc>●</rtc>を<rtc>●</rtc></ruby>同時</div>
'''
TEST_CASES = [
('top', 'horizontal-tb', 'over', [
('horizontal-tb', 'over right')]),
('bottom', 'horizontal-tb', 'under', [
('horizontal-tb', 'under right')]),
('right', 'vertical-rl', 'over', [
('vertical-rl', 'over right'),
('vertical-lr', 'over right')]),
('left', 'vertical-rl', 'under', [
('vertical-rl', 'over left'),
('vertical-lr', 'over left')]),
]
SUFFIXES = ['', 'a']
def write_file(filename, content):
with open(filename, 'wb') as f:
f.write(content.encode('UTF-8'))
print("# START tests from {}".format(__file__))
idx = 0
for pos, ref_wm, ruby_pos, subtests in TEST_CASES:
idx += 1
ref_file = REF_FILE.format(idx)
ref_content = REF_TEMPLATE.format(pos=pos, wm=ref_wm, posval=ruby_pos)
write_file(ref_file, ref_content)
suffix = iter(SUFFIXES)
for wm, posval in subtests:
test_file = TEST_FILE.format(idx, next(suffix))
test_content = TEST_TEMPLATE.format(
wm=wm, pos=pos, index=idx, ruby_pos=ruby_pos, posval=posval)
write_file(test_file, test_content)
print("== {} {}".format(test_file, ref_file))
print("# END tests from {}".format(__file__))
| mpl-2.0 |
souzabrizolara/py-home-shell | src/dao/appliancedao.py | 1 | 1109 | __author__ = 'alisonbento'
import basedao
from src.entities.hsappliance import HomeShellAppliance
import datetime
import configs
class ApplianceDAO(basedao.BaseDAO):
def __init__(self, connection):
basedao.BaseDAO.__init__(self, connection, 'hs_appliances', 'appliance_id')
def convert_row_to_object(self, entity_row):
appliance = HomeShellAppliance()
appliance.id = entity_row['appliance_id']
appliance.package = entity_row['package']
appliance.type = entity_row['type']
appliance.name = entity_row['type']
appliance.key = None
appliance.address = entity_row['address']
appliance.hash = entity_row['appliance_hash']
appliance.modified = entity_row['modified']
appliance.modified_datetime = datetime.datetime.strptime(appliance.modified, configs.DATABASE_DATE_FORMAT)
return appliance
def update(self, entity):
cursor = self.connection.cursor()
sql = "UPDATE " + self.table + " SET modified = ? WHERE appliance_id = ?"
cursor.execute(sql, (entity.modified, entity.id))
| apache-2.0 |
harshaneelhg/scikit-learn | examples/linear_model/plot_lasso_lars.py | 363 | 1080 | #!/usr/bin/env python
"""
=====================
Lasso path using LARS
=====================
Computes Lasso Path along the regularization parameter using the LARS
algorithm on the diabetes dataset. Each color represents a different
feature of the coefficient vector, and this is displayed as a function
of the regularization parameter.
"""
print(__doc__)
# Author: Fabian Pedregosa <fabian.pedregosa@inria.fr>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn import datasets
diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target
print("Computing regularization path using the LARS ...")
alphas, _, coefs = linear_model.lars_path(X, y, method='lasso', verbose=True)
xx = np.sum(np.abs(coefs.T), axis=1)
xx /= xx[-1]
plt.plot(xx, coefs.T)
ymin, ymax = plt.ylim()
plt.vlines(xx, ymin, ymax, linestyle='dashed')
plt.xlabel('|coef| / max|coef|')
plt.ylabel('Coefficients')
plt.title('LASSO Path')
plt.axis('tight')
plt.show()
| bsd-3-clause |
Flutras/techstitution | app/mod_main/views.py | 1 | 15521 | from flask import Blueprint, render_template, request, redirect, url_for, Response, jsonify, flash
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, DateTimeField, TextField, SubmitField, TextAreaField, RadioField
from wtforms import validators, ValidationError
from wtforms.validators import InputRequired
from bson import ObjectId
from app import mongo
from bson import json_util
import json
mod_main = Blueprint('main', __name__)
@mod_main.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] == 'admin' and request.form['password'] == 'admin':
return redirect(url_for('main.index'))
else:
error = 'Invalid Credentials. Please try again.'
return render_template('mod_main/login.html', error=error)
else:
return render_template('mod_main/login.html', error=error)
class AddPeopleForm(FlaskForm):
firstname = StringField('Firstname', validators=[InputRequired("Please fill out firstname")])
lastname = StringField('Lastname', validators=[InputRequired()])
# submit = SubmitField("Submit")
@mod_main.route('/index', methods=['GET', 'POST'])
def indexpage():
form=AddPeopleForm();
if request.method == 'GET':
reports = mongo.db.reports.find()
return render_template('mod_main/index.html', reports=reports, form=form)
@mod_main.route('/', methods=['GET', 'POST'])
def index():
form = AddPeopleForm()
if request.method == 'GET':
reports = mongo.db.reports.find()
audits = mongo.db.audits.find()
return render_template('mod_main/dashboard.html', reports=reports, audits=audits, form=form)
elif request.method == 'POST' and form.validate_on_submit():
mongo.db.reports.insert({
"firstname": request.form['firstname'],
"lastname": request.form['lastname']
})
return redirect(url_for('main.index'))
@mod_main.route('/audit_list', methods=['GET', 'POST'])
def audit_list():
audits = mongo.db.audits.find()
return render_template('mod_main/audit_list.html', audits=audits)
# New Audit Form
class AddAuditForm(FlaskForm):
audit_ref_num = IntegerField('Reference number', validators=[InputRequired("Please enter audit reference number!")])
audit_title = StringField('Title', validators=[InputRequired("Please enter audit title!")])
audit_type = StringField('Audit type', validators=[InputRequired("Please enter audit type!")])
audit_organization = StringField('Organization', validators=[InputRequired("Please enter organization!")])
audit_start_date = DateTimeField('Audit Start Date', validators=[InputRequired("Please enter start date!")])
audit_end_date = DateTimeField('Audit End Date', validators=[InputRequired("Please enter end date!")])
audit_auditee = StringField('Auditee', validators=[InputRequired("Please enter auditee!")])
audit_place = StringField('Place', validators=[InputRequired("Please enter place!")])
audit_frefnum = IntegerField('Follow-up reference number', validators=[InputRequired("Please enter follow-up reference number!")])
audit_chrefnum = IntegerField('Change reference number', validators=[InputRequired("Please enter changed reference number!")])
audit_tl = StringField('Audit Team Leader', validators=[InputRequired("Please enter team leader name!")])
audit_tm = StringField('Audit Team Members', validators=[InputRequired("Please enter team members!")])
audit_ap = StringField('Auditee Participants', validators=[InputRequired("Please enter auditee participants!")])
submit = SubmitField("Submit")
@mod_main.route('/add_audit_form', methods=['GET', 'POST'])
def add_audit_form():
form = AddAuditForm()
if request.method == 'GET':
audits = mongo.db.audits.find()
return render_template('mod_main/add_audit_form.html', audits=audits, form=form)
elif request.method == 'POST':
data = request.form
new_inputs = ({})
counter = 1
while counter < 5:
if 'input'+str(counter) in data:
new_inputs.update({
'input_'+str(counter): data['input'+str(counter)]
})
counter += 1
print new_inputs
mongo.db.audits.insert({
"new_inputs": new_inputs,
"audit_ref_num": request.form['audit_ref_num'],
"audit_title": request.form['audit_title'],
"audit_type": request.form['audit_type'],
"audit_organization": request.form['audit_organization'],
"audit_start_date": request.form['audit_start_date'],
"audit_end_date": request.form['audit_end_date'],
"audit_auditee": request.form['audit_auditee'],
"audit_place": request.form['audit_place'],
"audit_frefnum": request.form['audit_frefnum'],
"audit_chrefnum": request.form['audit_chrefnum'],
"audit_tl": request.form['audit_tl'],
"audit_tm": request.form['audit_tm'],
"audit_ap": request.form['audit_ap']
})
return redirect(url_for('main.index'))
# New NC Form
class AddNCForm(FlaskForm):
nc_title = StringField('Title', validators=[InputRequired("Please enter NC title!")])
nc_operator_auditee = StringField('Operator Auditee', validators=[InputRequired("Please enter operator auditee!")])
nc_number = IntegerField('Number', validators=[InputRequired("Please enter number!")])
nc_date = DateTimeField('Date', validators=[InputRequired("Please enter date!")])
nc_status = StringField('Status', validators=[InputRequired("Please enter status!")])
nc_agreed_date_for_CAP = DateTimeField('Agreed date for CAP', validators=[InputRequired("Please enter agreed date for CAP!")])
nc_level = StringField('Level', validators=[InputRequired("Please enter level!")])
nc_due_date = DateTimeField('Due Date', validators=[InputRequired("Please enter due date!")])
nc_closure_date = DateTimeField('Closure Date', validators=[InputRequired("Please enter closure date!")])
nc_requirement_references = StringField('Requirement References', validators=[InputRequired("Please enter requirement refeences!")])
nc_further_references = StringField('Further References', validators=[InputRequired("Please enter further references!")])
nc_auditor_ofcaa = StringField('Auditor of CAA', validators=[InputRequired("Please enter auditor of CAA!")])
nc_auditee_rfCAP = StringField('Auditee responsible for CAP', validators=[InputRequired("Please enter auditee!")])
requirement_references = TextAreaField('', validators=[InputRequired("Please enter requirement references!")])
nc_details = TextAreaField('Non Conformity Details', validators=[InputRequired("Please enter details!")])
submit = SubmitField("Submit")
@mod_main.route('/<string:audit_id>/add_nc_form', methods=['GET', 'POST'])
def add_nc_form(audit_id):
form = AddNCForm()
if request.method == 'GET':
audit = mongo.db.audits.find({"_id": ObjectId(audit_id)})
return render_template('mod_main/add_nc_form.html', audit=audit, form=form)
elif request.method == 'POST':
# print "post request"
mongo.db.audits.update({"_id": ObjectId(audit_id)}, {"$set": {nonconformities: {
"nc_title": request.form['nc_title'],
"nc_operator_auditee": request.form['nc_operator_auditee'],
"nc_number": request.form['nc_number'],
"nc_date": request.form['nc_date'],
"nc_status": request.form['nc_status'],
"nc_agreed_date_for_CAP": request.form['nc_agreed_date_for_CAP'],
"nc_level": request.form['nc_level'],
"nc_due_date": request.form['nc_due_date'],
"nc_closure_date": request.form['nc_closure_date'],
"nc_requirement_references": request.form['nc_requirement_references'],
"nc_further_references": request.form['nc_further_references'],
"nc_auditor_ofcaa": request.form['nc_auditor_ofcaa'],
"nc_auditee_rfCAP": request.form['nc_auditee_rfCAP'],
"requirement_references": request.form['requirement_references'],
"nc_details": request.form['nc_details']
}}})
return redirect(url_for('main.show_audit', audit_id=audit_id))
# New NC Form
class AddCAForm(FlaskForm):
ca_description = StringField('Corrective Action Description', validators=[InputRequired("Please enter description!")])
ca_date_of_capapproval = DateTimeField('Date of CAP approval', validators=[InputRequired("Please enter date!")])
ca_due_date = DateTimeField('Due Date', validators=[InputRequired("Please enter due date!")])
ca_contact_person = StringField('Contact Person', validators=[InputRequired("Please enter contact!")])
ca_closure_date = DateTimeField('Closure Date', validators=[InputRequired("Please enter due date!")])
ca_due_date_history = TextAreaField('Due Date History', validators=[InputRequired("Please enter due date!")])
submit = SubmitField("Submit")
@mod_main.route('/<string:audit_id>/add_ca_form', methods=['GET', 'POST'])
def add_ca_form(audit_id):
form = AddCAForm()
if request.method == 'GET':
audit = mongo.db.audits.find({"_id": ObjectId(audit_id)})
return render_template('mod_main/add_ca_form.html', audit=audit, form=form)
elif request.method == 'POST':
# print "post request"
mongo.db.correctiveactions.update({"_id": ObjectId(audit_id)}, {"$set": {
"ca_description": request.form['ca_description'],
"ca_date_of_capapproval": request.form['ca_date_of_capapproval'],
"ca_due_date": request.form['ca_due_date'],
"ca_contact_person": request.form['ca_contact_person'],
"ca_closure_date": request.form['ca_closure_date'],
"ca_due_date_history": request.form['ca_due_date_history']
}})
return redirect(url_for('main.show_nc', audit_id=audit_id))
@mod_main.route('/add_people_form', methods=['GET', 'POST'])
def add_people_form():
form = AddPeopleForm()
if request.method == 'GET':
reports = mongo.db.reports.find()
return render_template('mod_main/add_people_form.html', reports=reports, form=form)
elif request.method == 'POST' and form.validate_on_submit():
# print "post request"
mongo.db.reports.insert({
"firstname": request.form['firstname'],
"lastname": request.form['lastname']
})
# return "Form successfully submitted!"
return redirect(url_for('main.indexpage'))
# behet post request ne kete url
@mod_main.route('/remove/audit', methods=['POST'])
def remove_audit():
if request.method == 'POST':
audit_id = request.form['id']
mongo.db.audits.remove({"_id": ObjectId(audit_id)})
return Response(json.dumps({"removed": True}), mimetype='application/json')
@mod_main.route('/remove/report', methods=['POST'])
def remove_report():
if request.method == 'POST':
report_id = request.form['id']
mongo.db.reports.remove({"_id": ObjectId(report_id)})
return Response(json.dumps({"removed": True}), mimetype='application/json')
@mod_main.route('/show_audit/<string:audit_id>', methods=['GET', 'POST'])
def show_audit(audit_id):
form = AddAuditForm()
if request.method == 'GET':
audit = mongo.db.audits.find_one({"_id": ObjectId(audit_id)})
return render_template('mod_main/audit_details.html', audit=audit, form=form)
@mod_main.route('/edit/<string:audit_id>', methods=['GET', 'POST'])
def edit_audit(audit_id):
form = AddAuditForm()
if request.method == 'GET':
audit = mongo.db.audits.find_one({"_id": ObjectId(audit_id)})
return render_template('mod_main/audit_edit.html', audit=audit, form=form)
elif request.method == 'POST':
audit = mongo.db.audits.find_one({"_id": ObjectId(audit_id)})
mongo.db.audits.update({"_id": ObjectId(audit_id)}, {"$set": {
"audit_ref_num": request.form['audit_ref_num'],
"audit_title": request.form['audit_title'],
"audit_type": request.form['audit_type'],
"audit_organization": request.form['audit_organization'],
"audit_start_date": request.form['audit_start_date'],
"audit_end_date": request.form['audit_end_date'],
"audit_auditee": request.form['audit_auditee'],
"audit_place": request.form['audit_place'],
"audit_frefnum": request.form['audit_frefnum'],
"audit_chrefnum": request.form['audit_chrefnum'],
"audit_tl": request.form['audit_tl'],
"audit_tm": request.form['audit_tm'],
"audit_ap": request.form['audit_ap']
}})
return redirect(url_for('main.show_audit', audit_id= audit_id))
# return 'Showing result ' + str(result)
@mod_main.route('/show_report/<string:report_id>', methods=['GET'])
def show_report(report_id):
result = mongo.db.reports.find_one({"_id": ObjectId(report_id)})
return 'Showing result ' + str(result)
@mod_main.route('/add-people', methods=['GET', 'POST'])
def add_people():
# TODO: Implement POST REQUEST
# if success:
form = AddPeopleForm()
reports = mongo.db.reports.find();
if request.method == 'GET':
return render_template('mod_main/index.html', form=form, reports=reports)
elif request.method == 'POST':
# Get form
form = AddPeopleForm()
# Get form data
data = form.data
# Add document to the database
added_report_id = mongo.db.reports.insert(data)
# Get the added document
report_doc = mongo.db.reports.find_one({"_id": ObjectId(added_report_id)})
# Return a json response
return Response(json_util.dumps(report_doc),mimetype="application/json")
else:
return Response(json_util.dumps({"error":"Something went wrong!"}),mimetype="application/json")
@mod_main.route('/add-audit', methods=['GET', 'POST'])
def add_audit():
# TODO: Implement POST REQUEST
# if success:
form = AddAuditForm()
if request.method == 'POST':
if form.validate() == False:
# flash('All fields are required!')
audits = mongo.db.audits.find()
return render_template('mod_main/add_audit.html', audits=audits, form=form)
else:
mongo.db.audits.insert({
"audit_title": request.form['audit_title'],
"audit_ref_num": request.form['audit_ref_num'],
"audit_start_date": request.form['audit_start_date']
})
return redirect(url_for('main.audit_list'))
elif request.method == 'GET':
return render_template('mod_main/add_audit.html', form=form)
# views for new bootstrap admin dashboard theme template
@mod_main.route('/corrective_actions', methods=['GET', 'POST'])
def corrective_actions():
# audits = mongo.db.audits.find()
return render_template('mod_main/corrective_actions.html')
@mod_main.route('/forms', methods=['GET', 'POST'])
def forms():
# audits = mongo.db.audits.find()
return render_template('mod_main/forms.html')
@mod_main.route('/blank-page', methods=['GET', 'POST'])
def blank_page():
# audits = mongo.db.audits.find()
return render_template('mod_main/blank-page.html')
| cc0-1.0 |
catapult-project/catapult-csm | third_party/gsutil/third_party/boto/boto/contrib/__init__.py | 147 | 1105 | # Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# 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, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing 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 MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR 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.
#
| bsd-3-clause |
vsvankhede/foursquared | mock_server/playfoursquare.py | 134 | 2253 | #!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| apache-2.0 |
Mozhuowen/brython | www/src/Lib/test/test_winsound.py | 25 | 9156 | # Ridiculously simple test of the winsound module for Windows.
import unittest
from test import support
support.requires('audio')
import time
import os
import subprocess
winsound = support.import_module('winsound')
ctypes = support.import_module('ctypes')
import winreg
def has_sound(sound):
"""Find out if a particular event is configured with a default sound"""
try:
# Ask the mixer API for the number of devices it knows about.
# When there are no devices, PlaySound will fail.
if ctypes.windll.winmm.mixerGetNumDevs() == 0:
return False
key = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER,
"AppEvents\Schemes\Apps\.Default\{0}\.Default".format(sound))
return winreg.EnumValue(key, 0)[1] != ""
except WindowsError:
return False
class BeepTest(unittest.TestCase):
# As with PlaySoundTest, incorporate the _have_soundcard() check
# into our test methods. If there's no audio device present,
# winsound.Beep returns 0 and GetLastError() returns 127, which
# is: ERROR_PROC_NOT_FOUND ("The specified procedure could not
# be found"). (FWIW, virtual/Hyper-V systems fall under this
# scenario as they have no sound devices whatsoever (not even
# a legacy Beep device).)
def test_errors(self):
self.assertRaises(TypeError, winsound.Beep)
self.assertRaises(ValueError, winsound.Beep, 36, 75)
self.assertRaises(ValueError, winsound.Beep, 32768, 75)
def test_extremes(self):
self._beep(37, 75)
self._beep(32767, 75)
def test_increasingfrequency(self):
for i in range(100, 2000, 100):
self._beep(i, 75)
def _beep(self, *args):
# these tests used to use _have_soundcard(), but it's quite
# possible to have a soundcard, and yet have the beep driver
# disabled. So basically, we have no way of knowing whether
# a beep should be produced or not, so currently if these
# tests fail we're ignoring them
#
# XXX the right fix for this is to define something like
# _have_enabled_beep_driver() and use that instead of the
# try/except below
try:
winsound.Beep(*args)
except RuntimeError:
pass
class MessageBeepTest(unittest.TestCase):
def tearDown(self):
time.sleep(0.5)
def test_default(self):
self.assertRaises(TypeError, winsound.MessageBeep, "bad")
self.assertRaises(TypeError, winsound.MessageBeep, 42, 42)
winsound.MessageBeep()
def test_ok(self):
winsound.MessageBeep(winsound.MB_OK)
def test_asterisk(self):
winsound.MessageBeep(winsound.MB_ICONASTERISK)
def test_exclamation(self):
winsound.MessageBeep(winsound.MB_ICONEXCLAMATION)
def test_hand(self):
winsound.MessageBeep(winsound.MB_ICONHAND)
def test_question(self):
winsound.MessageBeep(winsound.MB_ICONQUESTION)
class PlaySoundTest(unittest.TestCase):
def test_errors(self):
self.assertRaises(TypeError, winsound.PlaySound)
self.assertRaises(TypeError, winsound.PlaySound, "bad", "bad")
self.assertRaises(
RuntimeError,
winsound.PlaySound,
"none", winsound.SND_ASYNC | winsound.SND_MEMORY
)
@unittest.skipUnless(has_sound("SystemAsterisk"),
"No default SystemAsterisk")
def test_alias_asterisk(self):
if _have_soundcard():
winsound.PlaySound('SystemAsterisk', winsound.SND_ALIAS)
else:
self.assertRaises(
RuntimeError,
winsound.PlaySound,
'SystemAsterisk', winsound.SND_ALIAS
)
@unittest.skipUnless(has_sound("SystemExclamation"),
"No default SystemExclamation")
def test_alias_exclamation(self):
if _have_soundcard():
winsound.PlaySound('SystemExclamation', winsound.SND_ALIAS)
else:
self.assertRaises(
RuntimeError,
winsound.PlaySound,
'SystemExclamation', winsound.SND_ALIAS
)
@unittest.skipUnless(has_sound("SystemExit"), "No default SystemExit")
def test_alias_exit(self):
if _have_soundcard():
winsound.PlaySound('SystemExit', winsound.SND_ALIAS)
else:
self.assertRaises(
RuntimeError,
winsound.PlaySound,
'SystemExit', winsound.SND_ALIAS
)
@unittest.skipUnless(has_sound("SystemHand"), "No default SystemHand")
def test_alias_hand(self):
if _have_soundcard():
winsound.PlaySound('SystemHand', winsound.SND_ALIAS)
else:
self.assertRaises(
RuntimeError,
winsound.PlaySound,
'SystemHand', winsound.SND_ALIAS
)
@unittest.skipUnless(has_sound("SystemQuestion"),
"No default SystemQuestion")
def test_alias_question(self):
if _have_soundcard():
winsound.PlaySound('SystemQuestion', winsound.SND_ALIAS)
else:
self.assertRaises(
RuntimeError,
winsound.PlaySound,
'SystemQuestion', winsound.SND_ALIAS
)
def test_alias_fallback(self):
# This test can't be expected to work on all systems. The MS
# PlaySound() docs say:
#
# If it cannot find the specified sound, PlaySound uses the
# default system event sound entry instead. If the function
# can find neither the system default entry nor the default
# sound, it makes no sound and returns FALSE.
#
# It's known to return FALSE on some real systems.
# winsound.PlaySound('!"$%&/(#+*', winsound.SND_ALIAS)
return
def test_alias_nofallback(self):
if _have_soundcard():
# Note that this is not the same as asserting RuntimeError
# will get raised: you cannot convert this to
# self.assertRaises(...) form. The attempt may or may not
# raise RuntimeError, but it shouldn't raise anything other
# than RuntimeError, and that's all we're trying to test
# here. The MS docs aren't clear about whether the SDK
# PlaySound() with SND_ALIAS and SND_NODEFAULT will return
# True or False when the alias is unknown. On Tim's WinXP
# box today, it returns True (no exception is raised). What
# we'd really like to test is that no sound is played, but
# that requires first wiring an eardrum class into unittest
# <wink>.
try:
winsound.PlaySound(
'!"$%&/(#+*',
winsound.SND_ALIAS | winsound.SND_NODEFAULT
)
except RuntimeError:
pass
else:
self.assertRaises(
RuntimeError,
winsound.PlaySound,
'!"$%&/(#+*', winsound.SND_ALIAS | winsound.SND_NODEFAULT
)
def test_stopasync(self):
if _have_soundcard():
winsound.PlaySound(
'SystemQuestion',
winsound.SND_ALIAS | winsound.SND_ASYNC | winsound.SND_LOOP
)
time.sleep(0.5)
try:
winsound.PlaySound(
'SystemQuestion',
winsound.SND_ALIAS | winsound.SND_NOSTOP
)
except RuntimeError:
pass
else: # the first sound might already be finished
pass
winsound.PlaySound(None, winsound.SND_PURGE)
else:
# Issue 8367: PlaySound(None, winsound.SND_PURGE)
# does not raise on systems without a sound card.
pass
def _get_cscript_path():
"""Return the full path to cscript.exe or None."""
for dir in os.environ.get("PATH", "").split(os.pathsep):
cscript_path = os.path.join(dir, "cscript.exe")
if os.path.exists(cscript_path):
return cscript_path
__have_soundcard_cache = None
def _have_soundcard():
"""Return True iff this computer has a soundcard."""
global __have_soundcard_cache
if __have_soundcard_cache is None:
cscript_path = _get_cscript_path()
if cscript_path is None:
# Could not find cscript.exe to run our VBScript helper. Default
# to True: most computers these days *do* have a soundcard.
return True
check_script = os.path.join(os.path.dirname(__file__),
"check_soundcard.vbs")
p = subprocess.Popen([cscript_path, check_script],
stdout=subprocess.PIPE)
__have_soundcard_cache = not p.wait()
p.stdout.close()
return __have_soundcard_cache
def test_main():
support.run_unittest(BeepTest, MessageBeepTest, PlaySoundTest)
if __name__=="__main__":
test_main()
| bsd-3-clause |
theDarkForce/websearch | webseach_book.py | 1 | 2428 | # -*- coding: UTF-8 -*-
# webseach
# create at 2015/10/30
# autor: qianqians
import sys
reload(sys)
sys.setdefaultencoding('utf8')
sys.path.append('../')
from webget import gethtml
import pymongo
from doclex import doclex
import time
collection_key = None
def seach(urllist):
def process_keyurl(keyurl):
if keyurl is not None:
for key, urllist in keyurl.iteritems():
for url in urllist:
urlinfo = gethtml.process_url(url)
if urlinfo is None:
continue
list, keyurl1 = urlinfo
if list is not None:
gethtml.collection.insert({'key':key, 'url':url, 'timetmp':time.time()})
if keyurl1 is not None:
process_keyurl(keyurl1)
def process_urllist(url_list):
for url in url_list:
#print url,"sub url"
urlinfo = gethtml.process_url(url)
if urlinfo is None:
continue
list, keyurl = urlinfo
if list is not None:
process_urllist(list)
if keyurl is not None:
process_keyurl(keyurl)
time.sleep(0.1)
suburl = []
subkeyurl = {}
for url in urllist:
print url, "root url"
urlinfo = gethtml.process_url(url)
if urlinfo is None:
continue
list, keyurl = urlinfo
suburl.extend(list)
subkeyurl.update(keyurl)
try:
process_urllist(suburl)
process_keyurl(subkeyurl)
except:
import traceback
traceback.print_exc()
urllist = ["http://www.qidian.com/Default.aspx",
"http://www.zongheng.com/",
"http://chuangshi.qq.com/"
]
def refkeywords():
c = collection_key.find()
keywords = []
for it in c:
keywords.append(it["key"])
doclex.keykorks = keywords
if __name__ == '__main__':
conn = pymongo.Connection('localhost',27017)
db = conn.webseach
gethtml.collection = db.webpage
gethtml.collection_url_profile = db.urlprofile
gethtml.collection_url_title = db.urltitle
collection_key = db.keys
t = 0
while True:
timetmp = time.time()-t
if timetmp > 86400:
refkeywords()
t = time.time()
#urllist = seach(urllist)
seach(urllist) | bsd-2-clause |
bestwpw/BDA_py_demos | demos_ch5/demo5_2.py | 19 | 3326 | """Bayesian Data Analysis, 3rd ed
Chapter 5, demo 2
Hierarchical model for SAT-example data (BDA3, p. 102)
"""
from __future__ import division
import numpy as np
from scipy.stats import norm
import scipy.io # For importing a matlab file
import matplotlib.pyplot as plt
# Edit default plot settings (colours from colorbrewer2.org)
plt.rc('font', size=14)
plt.rc('lines', color='#377eb8', linewidth=2)
plt.rc('axes', color_cycle=(plt.rcParams['lines.color'],)) # Disable color cycle
# SAT-example data (BDA3 p. 120)
# y is the estimated treatment effect
# s is the standard error of effect estimate
y = np.array([28, 8, -3, 7, -1, 1, 18, 12])
s = np.array([15, 10, 16, 11, 9, 11, 10, 18])
M = len(y)
# load the pre-computed results for the hierarchical model
# replace this with your own code in Ex 5.1*
hres_path = '../utilities_and_data/demo5_2.mat'
hres = scipy.io.loadmat(hres_path)
''' Content information of the precalculated results:
>>> scipy.io.whosmat('demo5_2.mat')
[('pxm', (8, 500), 'double'),
('t', (1, 1000), 'double'),
('tp', (1, 1000), 'double'),
('tsd', (8, 1000), 'double'),
('tm', (8, 1000), 'double')]
'''
pxm = hres['pxm']
t = hres['t'][0]
tp = hres['tp'][0]
tsd = hres['tsd']
tm = hres['tm']
# plot the separate, pooled and hierarchical models
fig, axes = plt.subplots(3, 1, sharex=True, figsize=(8,10))
x = np.linspace(-40, 60, 500)
# separate
lines = axes[0].plot(x, norm.pdf(x[:,None], y[1:], s[1:]), linewidth=1)
line, = axes[0].plot(x, norm.pdf(x, y[0], s[0]), 'r')
axes[0].legend((line, lines[1]), ('school A', 'other schools'),
loc='upper left')
axes[0].set_yticks(())
axes[0].set_title('separate model')
# pooled
axes[1].plot(
x,
norm.pdf(
x,
np.sum(y/s**2)/np.sum(1/s**2),
np.sqrt(1/np.sum(1/s**2))
),
label='All schools'
)
axes[1].legend(loc='upper left')
axes[1].set_yticks(())
axes[1].set_title('pooled model')
# hierarchical
lines = axes[2].plot(x, pxm[1:].T, linewidth=1)
line, = axes[2].plot(x, pxm[0], 'r')
axes[2].legend((line, lines[1]), ('school A', 'other schools'),
loc='upper left')
axes[2].set_yticks(())
axes[2].set_title('hierarchical model')
axes[2].set_xlabel('Treatment effect')
# plot various marginal and conditional posterior summaries
fig, axes = plt.subplots(3, 1, sharex=True, figsize=(8,10))
axes[0].plot(t, tp)
axes[0].set_yticks(())
axes[0].set_title(r'marginal posterior density $p(\tau|y)$')
axes[0].set_ylabel(r'$p(\tau|y)$', fontsize=20)
axes[0].set_xlim([0,35])
lines = axes[1].plot(t, tm[1:].T, linewidth=1)
line, = axes[1].plot(t, tm[0].T, 'r')
axes[1].legend((line, lines[1]), ('school A', 'other schools'),
loc='upper left')
axes[1].set_title(r'conditional posterior means of effects '
r'$\operatorname{E}(\theta_j|\tau,y)$')
axes[1].set_ylabel(r'$\operatorname{E}(\theta_j|\tau,y)$', fontsize=20)
lines = axes[2].plot(t, tsd[1:].T, linewidth=1)
line, = axes[2].plot(t, tsd[0].T, 'r')
axes[2].legend((line, lines[1]), ('school A', 'other schools'),
loc='upper left')
axes[2].set_title(r'standard deviations of effects '
r'$\operatorname{sd}(\theta_j|\tau,y)$')
axes[2].set_ylabel(r'$\operatorname{sd}(\theta_j|\tau,y)$', fontsize=20)
axes[2].set_xlabel(r'$\tau$', fontsize=20)
plt.show()
| gpl-3.0 |
gsehub/edx-platform | common/djangoapps/entitlements/tasks.py | 17 | 2794 | """
This file contains celery tasks for entitlements-related functionality.
"""
from celery import task
from celery.utils.log import get_task_logger
from django.conf import settings
from entitlements.models import CourseEntitlement
LOGGER = get_task_logger(__name__)
# Under cms the following setting is not defined, leading to errors during tests.
ROUTING_KEY = getattr(settings, 'ENTITLEMENTS_EXPIRATION_ROUTING_KEY', None)
# Maximum number of retries before giving up on awarding credentials.
# For reference, 11 retries with exponential backoff yields a maximum waiting
# time of 2047 seconds (about 30 minutes). Setting this to None could yield
# unwanted behavior: infinite retries.
MAX_RETRIES = 11
@task(bind=True, ignore_result=True, routing_key=ROUTING_KEY)
def expire_old_entitlements(self, start, end, logid='...'):
"""
This task is designed to be called to process a bundle of entitlements
that might be expired and confirm if we can do so. This is useful when
checking if an entitlement has just been abandoned by the learner and needs
to be expired. (In the normal course of a learner using the platform, the
entitlement will expire itself. But if a learner doesn't log in... So we
run this task every now and then to clear the backlog.)
Args:
start (int): The beginning id in the database to examine
end (int): The id in the database to stop examining at (i.e. range is exclusive)
logid (str): A string to identify this task in the logs
Returns:
None
"""
LOGGER.info('Running task expire_old_entitlements %d:%d [%s]', start, end, logid)
# This query could be optimized to return a more narrow set, but at a
# complexity cost. See bug LEARNER-3451 about improving it.
entitlements = CourseEntitlement.objects.filter(expired_at__isnull=True, id__gte=start, id__lt=end)
countdown = 2 ** self.request.retries
try:
for entitlement in entitlements:
# This property request will update the expiration if necessary as
# a side effect. We could manually call update_expired_at(), but
# let's use the same API the rest of the LMS does, to mimic normal
# usage and allow the update call to be an internal detail.
if entitlement.expired_at_datetime:
LOGGER.info('Expired entitlement with id %d [%s]', entitlement.id, logid)
except Exception as exc:
LOGGER.exception('Failed to expire entitlements [%s]', logid)
# The call above is idempotent, so retry at will
raise self.retry(exc=exc, countdown=countdown, max_retries=MAX_RETRIES)
LOGGER.info('Successfully completed the task expire_old_entitlements after examining %d entries [%s]', entitlements.count(), logid)
| agpl-3.0 |
mmw125/MuDimA | server/database_reader.py | 1 | 7747 | """Functions for reading from the database."""
import constants
import database_utils
import models
def get_urls():
"""Get all of the urls in articles in the database."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT link FROM article;")
urls = set(item[0] for item in cursor.fetchall())
cursor.execute("SELECT link FROM bad_article;")
return urls.union(item[0] for item in cursor.fetchall())
def get_number_topics(category=None):
"""Get just the number of topics from the database."""
with database_utils.DatabaseConnection() as (connection, cursor):
if category is None:
cursor.execute("SELECT 1 FROM article, topic WHERE article.topic_id = topic.id AND "
"article.topic_id IS NOT NULL GROUP BY topic.id ORDER BY count(*) DESC;")
else:
cursor.execute("SELECT 1 FROM article, topic WHERE article.topic_id = topic.id AND article.category = ? AND"
" article.topic_id IS NOT NULL GROUP BY topic.id ORDER BY count(*) DESC;", (category,))
return len(cursor.fetchall())
def get_topics(category=None, page_number=0, articles_per_page=constants.ARTICLES_PER_PAGE):
"""Get the topics for the given page."""
with database_utils.DatabaseConnection() as (connection, cursor):
start = page_number * articles_per_page
end = (page_number + 1) * articles_per_page
total_items = get_number_topics()
if category is None:
cursor.execute("SELECT topic.name, topic.id, topic.image_url, topic.category, count(*) FROM article, topic "
"WHERE article.topic_id = topic.id AND article.topic_id IS NOT NULL "
"GROUP BY topic.id ORDER BY count(*) DESC;")
else:
cursor.execute("SELECT topic.name, topic.id, topic.image_url, topic.category, count(*) FROM article, topic "
"WHERE article.topic_id = topic.id AND topic.category = ? AND article.topic_id IS NOT NULL "
"GROUP BY topic.id ORDER BY count(*) DESC;", (category,))
return sorted([{"total_items": total_items, "title": item[0], "id": item[1],
"image": item[2], "category": item[3], "count": item[4]}
for item in cursor.fetchall()[start:end]], key=lambda x: -x["count"])
def get_sources():
"""Get all of the stories for the topic with the given topic id. Returns empty dict if topic not in database."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT source, count(1) FROM article GROUP BY source")
return cursor.fetchall()
def get_stories_for_topic(topic_id):
"""Get all of the stories for the topic with the given topic id. Returns empty dict if topic not in database."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT name FROM topic WHERE id=?", (topic_id,))
db_item = cursor.fetchone()
if db_item is not None:
title = db_item[0]
cursor.execute("SELECT name, link, image_url, group_fit_x, group_fit_y, popularity, source, favicon "
"FROM article WHERE topic_id=?",
(topic_id,))
items = cursor.fetchall()
else:
title, items = None, []
return {"title": title, "articles": [{"name": item[0], "link": item[1], "image": item[2], "x": item[3],
"y": item[4], "popularity": item[5], "source": item[6], "favicon": item[7]
} for item in items]}
def get_ungrouped_articles():
"""Get the items in the database and puts them into Article and Grouping objects."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT name, link, article_text FROM article "
"WHERE article_text != '' AND topic_id IS NULL;")
articles = []
for item in cursor.fetchall():
name, url, article_text = item
articles.append(models.Article(url=url, title=name, text=article_text, in_database=True,
keywords=_get_article_keywords(url, cursor)))
return articles
def get_top_keywords(num=constants.DEFAULT_NUM_KEYWORDS):
"""Get the top keywords used in the database."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT keyword, COUNT(1) AS c FROM keyword GROUP BY keyword ORDER BY c DESC LIMIT ?;", (num,))
return [item[0] for item in cursor.fetchall()]
def get_groups_with_unfit_articles():
"""Get the ids of the groups in the database that have articles that are not fit."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT topic_id FROM article WHERE group_fit_x IS NULL AND topic_id IS NOT NULL "
"GROUP BY topic_id;")
return [i[0] for i in cursor.fetchall()]
def get_number_articles_without_overall_fit():
"""Get the number of articles in the database without an overall fit."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT topic_id FROM article WHERE group_fit_x IS NULL AND topic_id IS NOT NULL;")
return len(cursor.fetchall())
def _get_article_keywords(article_url, cursor):
"""Get the keywords for the given article."""
cursor.execute("SELECT keyword FROM keyword WHERE article_link = ?;", (article_url,))
return set(item[0] for item in cursor.fetchall())
def get_grouped_articles():
"""Get the items in the database and puts them into Article and Grouping objects."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT name, topic_id, link, article_text, image_url FROM article "
"WHERE article_text != '' AND topic_id IS NOT NULL;")
groups = {}
for item in cursor.fetchall():
name, id, url, article_text, image_url = item
article = models.Article(url=url, title=name, text=article_text, urlToImage=image_url, in_database=True)
article.set_keywords(_get_article_keywords(url, cursor))
if id in groups:
groups.get(id).add_article(article, new_article=False)
else:
groups[id] = models.Grouping(article, uuid=id, in_database=True, has_new_articles=False)
return list(groups.values())
def get_articles(keyword, page=0, limit=10, order_by=None, descending=True):
"""Get the items in the database and puts them into Article and Grouping objects."""
order_by = "date" if order_by is None else order_by
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT name, link, image_url, fit_x, fit_y, popularity, source, favicon "
"FROM keyword JOIN article ON keyword.article_link = article.link "
"WHERE keyword = ? OR ? GROUP BY article_link ORDER BY ? DESC;",
(keyword, keyword is None, order_by))
items = [item for item in cursor.fetchall()]
num_items = len(items)
if not descending:
items.reverse()
start = limit * page
items = items[start:start + limit]
return {"num": num_items, "articles": [{
"name": item[0], "link": item[1], "image": item[2], "x": item[3], "y": item[4],
"popularity": item[5], "source": item[6], "favicon": item[7]} for item in items]}
| gpl-3.0 |
graphite/TeX4Web-INVENIO | modules/bibsword/lib/bibsword_webinterface.py | 31 | 22937 | '''
Forward to ArXiv.org source code
'''
## This file is part of Invenio.
## Copyright (C) 2010, 2011 CERN.
##
## Invenio 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.
##
## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
__revision__ = "$Id$"
__lastupdated__ = """$Date$"""
import os
from invenio.access_control_engine import acc_authorize_action
from invenio.config import CFG_SITE_URL, CFG_TMPDIR
from invenio.webuser import page_not_authorized, collect_user_info
from invenio.bibsword_client import perform_display_sub_status, \
perform_display_server_list, \
perform_display_collection_list, \
perform_display_category_list, \
perform_display_metadata, \
perform_submit_record, \
perform_display_server_infos, \
list_remote_servers
from invenio.webpage import page
from invenio.messages import gettext_set_language
from invenio.webinterface_handler import wash_urlargd, WebInterfaceDirectory
from invenio.websubmit_functions.Get_Recid import \
get_existing_records_for_reportnumber
from invenio.search_engine_utils import get_fieldvalues
from invenio.bibsword_config import CFG_MARC_REPORT_NUMBER, CFG_MARC_ADDITIONAL_REPORT_NUMBER
class WebInterfaceSword(WebInterfaceDirectory):
""" Handle /bibsword set of pages."""
_exports = ['', 'remoteserverinfos']
def __init__(self, reqid=None):
'''Initialize'''
self.reqid = reqid
def __call__(self, req, form):
errors = []
warnings = []
body = ''
error_messages = []
#***********************************************************************
# Get values from the form
#***********************************************************************
argd = wash_urlargd(form, {
'ln' : (str, ''),
# information of the state of the form submission
'status' : (str, ''),
'submit' : (str, ''),
'last_row' : (str, ''),
'first_row' : (str, ''),
'offset' : (int, ''),
'total_rows' : (str, ''),
# mendatory informations
'id_record' : (str, ''),
'recid' : (int, 0),
'id_remote_server' : (str, ''),
'id_collection' : (str, ''),
'id_primary' : (str, ''),
'id_categories' : (list, []),
'id' : (str, ''),
'title' : (str, ''),
'summary' : (str, ''),
'author_name' : (str, ''),
'author_email' : (str, ''),
'contributor_name' : (list, []),
'contributor_email' : (list, []),
'contributor_affiliation' : (list, []),
# optionnal informations
'comment' : (str, ''),
'doi' : (str, ''),
'type' : (str, ''),
'journal_refs' : (list, []),
'report_nos' : (list, []),
'media' : (list, []),
'new_media' : (str, ''),
'filename' : (str, '')
})
# set language for i18n text auto generation
_ = gettext_set_language(argd['ln'])
#authentication
(auth_code, auth_message) = self.check_credential(req)
if auth_code != 0:
return page_not_authorized(req=req, referer='/bibsword',
text=auth_message, navtrail='')
user_info = collect_user_info(req)
#Build contributor tuples {name, email and affiliation(s)}
contributors = []
contributor_id = 0
affiliation_id = 0
for name in argd['contributor_name']:
contributor = {}
contributor['name'] = name
contributor['email'] = argd['contributor_email'][contributor_id]
contributor['affiliation'] = []
is_last_affiliation = False
while is_last_affiliation == False and \
affiliation_id < len(argd['contributor_affiliation']):
if argd['contributor_affiliation'][affiliation_id] == 'next':
is_last_affiliation = True
elif argd['contributor_affiliation'][affiliation_id] != '':
contributor['affiliation'].append(\
argd['contributor_affiliation'][affiliation_id])
affiliation_id += 1
contributors.append(contributor)
contributor_id += 1
argd['contributors'] = contributors
# get the uploaded file(s) (if there is one)
for key, formfields in form.items():
if key == "new_media" and hasattr(formfields, "filename") and formfields.filename:
filename = formfields.filename
fp = open(os.path.join(CFG_TMPDIR, filename), "w")
fp.write(formfields.file.read())
fp.close()
argd['media'].append(os.path.join(CFG_TMPDIR, filename))
argd['filename'] = os.path.join(CFG_TMPDIR, filename)
# Prepare navtrail
navtrail = '''<a class="navtrail" ''' \
'''href="%(CFG_SITE_URL)s/help/admin">Admin Area</a>''' \
% {'CFG_SITE_URL': CFG_SITE_URL}
title = _("BibSword Admin Interface")
#***********************************************************************
# Display admin main page
#***********************************************************************
if argd['status'] == '' and argd['recid'] != '' and argd['id_remote_server'] != '':
remote_servers = list_remote_servers(argd['id_remote_server'])
if len(remote_servers) == 0:
error_messages.append("No corresponding remote server could be found")
(body, errors, warnings) = perform_display_server_list(
error_messages,
argd['id_record'])
else:
title = _("Export with BibSword: Step 2/4")
navtrail += ''' > <a class="navtrail" ''' \
'''href="%(CFG_SITE_URL)s/bibsword">''' \
'''SWORD Interface</a>''' % \
{'CFG_SITE_URL' : CFG_SITE_URL}
(body, errors, warnings) = perform_display_collection_list(
argd['id_remote_server'],
argd['id_record'],
argd['recid'],
error_messages)
elif argd['status'] == '' or argd['submit'] == "Cancel":
(body, errors, warnings) = perform_display_sub_status()
elif argd['status'] == 'display_submission':
if argd['submit'] == 'Refresh all':
(body, errors, warnings) = \
perform_display_sub_status(1, argd['offset'], "refresh_all")
elif argd['submit'] == 'Select':
first_row = 1
(body, errors, warnings) = \
perform_display_sub_status(first_row, argd['offset'])
elif argd['submit'] == 'Next':
first_row = int(argd['last_row']) + 1
(body, errors, warnings) = \
perform_display_sub_status(first_row, argd['offset'])
elif argd['submit'] == 'Prev':
first_row = int(argd['first_row']) - int(argd['offset'])
(body, errors, warnings) = \
perform_display_sub_status(first_row, argd['offset'])
elif argd['submit'] == 'First':
(body, errors, warnings) = \
perform_display_sub_status(1, argd['offset'])
elif argd['submit'] == 'Last':
first_row = int(argd['total_rows']) - int(argd['offset']) + 1
(body, errors, warnings) = \
perform_display_sub_status(first_row, argd['offset'])
#***********************************************************************
# Select remote server
#***********************************************************************
# when the user validated the metadata, display
elif argd['submit'] == 'New submission':
title = _("Export with BibSword: Step 1/4")
navtrail += ''' > <a class="navtrail" ''' \
'''href="%(CFG_SITE_URL)s/bibsword">''' \
'''SWORD Interface</a>''' % \
{'CFG_SITE_URL' : CFG_SITE_URL}
(body, errors, warnings) = \
perform_display_server_list(error_messages)
# check if the user has selected a remote server
elif argd['status'] == 'select_server':
title = _("Export with BibSword: Step 1/4")
navtrail += ''' > <a class="navtrail" ''' \
'''href="%(CFG_SITE_URL)s/bibsword">''' \
'''SWORD Interface</a>''' % \
{'CFG_SITE_URL' : CFG_SITE_URL}
# check if given id_record exist and convert it in recid
if argd['recid'] != 0:
report_numbers = get_fieldvalues(argd['recid'], CFG_MARC_REPORT_NUMBER)
report_numbers.extend(get_fieldvalues(argd['recid'], CFG_MARC_ADDITIONAL_REPORT_NUMBER))
if report_numbers:
argd['id_record'] = report_numbers[0]
elif argd['id_record'] == '':
error_messages.append("You must specify a report number")
else:
recids = \
get_existing_records_for_reportnumber(argd['id_record'])
if len(recids) == 0:
error_messages.append(\
"No document found with the given report number")
elif len(recids) > 1:
error_messages.append(\
"Several documents have been found with given the report number")
else:
argd['recid'] = recids[0]
if argd['id_remote_server'] in ['0', '']:
error_messages.append("No remote server was selected")
if not argd['id_remote_server'] in ['0', '']:
# get the server's name and host
remote_servers = list_remote_servers(argd['id_remote_server'])
if len(remote_servers) == 0:
error_messages.append("No corresponding remote server could be found")
argd['id_remote_server'] = '0'
if argd['id_remote_server'] in ['0', ''] or argd['recid'] == 0:
(body, errors, warnings) = perform_display_server_list(
error_messages,
argd['id_record'])
else:
title = _("Export with BibSword: Step 2/4")
(body, errors, warnings) = perform_display_collection_list(
argd['id_remote_server'],
argd['id_record'],
argd['recid'],
error_messages)
#***********************************************************************
# Select collection
#***********************************************************************
# check if the user wants to change the remote server
elif argd['submit'] == 'Modify server':
title = _("Export with BibSword: Step 1/4")
navtrail += ''' > <a class="navtrail" ''' \
'''href="%(CFG_SITE_URL)s/bibsword">''' \
'''SWORD Interface</a>''' % \
{'CFG_SITE_URL' : CFG_SITE_URL}
(body, errors, warnings) = \
perform_display_server_list(error_messages, argd['id_record'])
# check if the user has selected a collection
elif argd['status'] == 'select_collection':
title = _("Export with BibSword: Step 2/4")
navtrail += ''' > <a class="navtrail" ''' \
'''href="%(CFG_SITE_URL)s/bibsword">''' \
'''SWORD Interface</a>''' % \
{'CFG_SITE_URL': CFG_SITE_URL}
if argd['id_collection'] == '0':
error_messages.append("No collection was selected")
(body, errors, warnings) = perform_display_collection_list(
argd['id_remote_server'],
argd['id_record'],
argd['recid'],
error_messages)
else:
title = _("Export with BibSword: Step 3/4")
(body, errors, warnings) = perform_display_category_list(
argd['id_remote_server'],
argd['id_collection'],
argd['id_record'],
argd['recid'],
error_messages)
#***********************************************************************
# Select primary
#***********************************************************************
# check if the user wants to change the collection
elif argd['submit'] == 'Modify collection':
title = _("Export with BibSword: Step 2/4")
navtrail += ''' > <a class="navtrail" ''' \
'''href="%(CFG_SITE_URL)s/bibsword">''' \
'''SWORD Interface</a>''' % \
{'CFG_SITE_URL': CFG_SITE_URL}
(body, errors, warnings) = perform_display_collection_list(
argd['id_remote_server'],
argd['id_record'],
argd['recid'],
error_messages)
# check if the user has selected a primary category
elif argd['status'] == 'select_primary_category':
title = _("Export with BibSword: Step 3/4")
navtrail += ''' > <a class="navtrail" ''' \
'''href="%(CFG_SITE_URL)s/bibsword">''' \
'''SWORD Interface</a>''' % \
{'CFG_SITE_URL' : CFG_SITE_URL}
if argd['id_primary'] == '0':
error_messages.append("No primary category selected")
(body, errors, warnings) = perform_display_category_list(
argd['id_remote_server'],
argd['id_collection'],
argd['id_record'],
argd['recid'],
error_messages)
else:
title = _("Export with BibSword: Step 4/4")
(body, errors, warnings) = perform_display_metadata(user_info,
str(argd['id_remote_server']),
str(argd['id_collection']),
str(argd['id_primary']),
argd['id_categories'],
argd['id_record'],
argd['recid'],
error_messages)
#***********************************************************************
# Check record media and metadata
#***********************************************************************
# check if the user wants to change the collection
elif argd['submit'] == 'Modify destination':
title = _("Export with BibSword: Step 3/4")
navtrail += ''' > <a class="navtrail" ''' \
'''href="%(CFG_SITE_URL)s/bibsword">''' \
'''SWORD Interface</a>''' % \
{'CFG_SITE_URL' : CFG_SITE_URL}
(body, errors, warnings) = perform_display_category_list(
argd['id_remote_server'],
argd['id_collection'],
argd['id_record'],
argd['recid'],
error_messages)
# check if the metadata are complet and well-formed
elif argd['status'] == 'check_submission':
title = _("Export with BibSword: Step 4/4")
navtrail += ''' > <a class="navtrail" ''' \
'''href="%(CFG_SITE_URL)s/bibsword">''' \
'''SWORD Interface</a>''' % \
{'CFG_SITE_URL' : CFG_SITE_URL}
if argd['submit'] == "Upload":
error_messages.append("Media loaded")
if argd['id'] == '':
error_messages.append("Id is missing")
if argd['title'] == '':
error_messages.append("Title is missing")
if argd['summary'] == '':
error_messages.append("summary is missing")
elif len(argd['summary']) < 25:
error_messages.append("summary must have at least 25 character")
if argd['author_name'] == '':
error_messages.append("No submitter name specified")
if argd['author_email'] == '':
error_messages.append("No submitter email specified")
if len(argd['contributors']) == 0:
error_messages.append("No author specified")
if len(error_messages) > 0:
(body, errors, warnings) = perform_display_metadata(user_info,
str(argd['id_remote_server']),
str(argd['id_collection']),
str(argd['id_primary']),
argd['id_categories'],
argd['id_record'],
argd['recid'],
error_messages,
argd)
else:
title = _("Export with BibSword: Acknowledgement")
navtrail += ''' > <a class="navtrail" ''' \
'''href="%(CFG_SITE_URL)s/bibsword">''' \
'''SWORD Interface</a>''' % \
{'CFG_SITE_URL' : CFG_SITE_URL}
(body, errors, warnings) = perform_submit_record(user_info,
str(argd['id_remote_server']),
str(argd['id_collection']),
str(argd['id_primary']),
argd['id_categories'],
argd['recid'],
argd)
# return of all the updated informations to be display
return page(title = title,
body = body,
navtrail = navtrail,
#uid = uid,
lastupdated = __lastupdated__,
req = req,
language = argd['ln'],
#errors = errors,
warnings = warnings,
navmenuid = "yourmessages")
def remoteserverinfos(self, req, form):
'''
This method handle the /bibsword/remoteserverinfos call
'''
argd = wash_urlargd(form, {
'ln' : (str, ''),
'id' : (str, '')
})
#authentication
(auth_code, auth_message) = self.check_credential(req)
if auth_code != 0:
return page_not_authorized(req=req, referer='/bibsword',
text=auth_message, navtrail='')
body = perform_display_server_infos(argd['id'])
navtrail = ''' > <a class="navtrail" ''' \
'''href="%(CFG_SITE_URL)s/bibsword">''' \
'''SWORD Interface</a>''' % \
{'CFG_SITE_URL' : CFG_SITE_URL}
# return of all the updated informations to be display
return page(title = 'Remote server infos',
body = body,
navtrail = navtrail,
#uid = uid,
lastupdated = __lastupdated__,
req = req,
language = argd['ln'],
errors = '',
warnings = '',
navmenuid = "yourmessages")
def check_credential(self, req):
'''
This method check if the user has the right to get into this
function
'''
auth_code, auth_message = acc_authorize_action(req, 'runbibswordclient')
return (auth_code, auth_message)
index = __call__
| gpl-2.0 |
andrius-preimantas/odoo | openerp/addons/base/tests/test_base.py | 64 | 33559 | import unittest2
import openerp.tests.common as common
from openerp.osv.orm import except_orm
class test_base(common.TransactionCase):
def setUp(self):
super(test_base,self).setUp()
self.res_partner = self.registry('res.partner')
self.res_users = self.registry('res.users')
self.res_partner_title = self.registry('res.partner.title')
# samples use effective TLDs from the Mozilla public suffix
# list at http://publicsuffix.org
self.samples = [
('"Raoul Grosbedon" <raoul@chirurgiens-dentistes.fr> ', 'Raoul Grosbedon', 'raoul@chirurgiens-dentistes.fr'),
('ryu+giga-Sushi@aizubange.fukushima.jp', '', 'ryu+giga-Sushi@aizubange.fukushima.jp'),
('Raoul chirurgiens-dentistes.fr', 'Raoul chirurgiens-dentistes.fr', ''),
(" Raoul O'hara <!@historicalsociety.museum>", "Raoul O'hara", '!@historicalsociety.museum')
]
def test_00_res_partner_name_create(self):
cr, uid = self.cr, self.uid
parse = self.res_partner._parse_partner_name
for text, name, mail in self.samples:
self.assertEqual((name,mail), parse(text), 'Partner name parsing failed')
partner_id, dummy = self.res_partner.name_create(cr, uid, text)
partner = self.res_partner.browse(cr, uid, partner_id)
self.assertEqual(name or mail, partner.name, 'Partner name incorrect')
self.assertEqual(mail or False, partner.email, 'Partner email incorrect')
def test_10_res_partner_find_or_create(self):
cr,uid = self.cr, self.uid
email = self.samples[0][0]
partner_id, dummy = self.res_partner.name_create(cr, uid, email)
found_id = self.res_partner.find_or_create(cr, uid, email)
self.assertEqual(partner_id, found_id, 'find_or_create failed')
new_id = self.res_partner.find_or_create(cr, uid, self.samples[1][0])
self.assertTrue(new_id > partner_id, 'find_or_create failed - should have created new one')
new_id2 = self.res_partner.find_or_create(cr, uid, self.samples[2][0])
self.assertTrue(new_id2 > new_id, 'find_or_create failed - should have created new one again')
def test_15_res_partner_name_search(self):
cr,uid = self.cr, self.uid
for name, active in [
('"A Raoul Grosbedon" <raoul@chirurgiens-dentistes.fr>', False),
('B Raoul chirurgiens-dentistes.fr', True),
("C Raoul O'hara <!@historicalsociety.museum>", True),
('ryu+giga-Sushi@aizubange.fukushima.jp', True),
]:
partner_id, dummy = self.res_partner.name_create(cr, uid, name, context={'default_active': active})
partners = self.res_partner.name_search(cr, uid, 'Raoul')
self.assertEqual(len(partners), 2, 'Incorrect search number result for name_search')
partners = self.res_partner.name_search(cr, uid, 'Raoul', limit=1)
self.assertEqual(len(partners), 1, 'Incorrect search number result for name_search with a limit')
self.assertEqual(partners[0][1], 'B Raoul chirurgiens-dentistes.fr', 'Incorrect partner returned, should be the first active')
def test_20_res_partner_address_sync(self):
cr, uid = self.cr, self.uid
ghoststep = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid,
{'name': 'GhostStep',
'is_company': True,
'street': 'Main Street, 10',
'phone': '123456789',
'email': 'info@ghoststep.com',
'vat': 'BE0477472701',
'type': 'default'}))
p1 = self.res_partner.browse(cr, uid, self.res_partner.name_create(cr, uid, 'Denis Bladesmith <denis.bladesmith@ghoststep.com>')[0])
self.assertEqual(p1.type, 'contact', 'Default type must be "contact"')
p1phone = '123456789#34'
p1.write({'phone': p1phone,
'parent_id': ghoststep.id,
'use_parent_address': True})
p1.refresh()
self.assertEqual(p1.street, ghoststep.street, 'Address fields must be synced')
self.assertEqual(p1.phone, p1phone, 'Phone should be preserved after address sync')
self.assertEqual(p1.type, 'contact', 'Type should be preserved after address sync')
self.assertEqual(p1.email, 'denis.bladesmith@ghoststep.com', 'Email should be preserved after sync')
# turn off sync
p1street = 'Different street, 42'
p1.write({'street': p1street,
'use_parent_address': False})
p1.refresh(), ghoststep.refresh()
self.assertEqual(p1.street, p1street, 'Address fields must not be synced after turning sync off')
self.assertNotEqual(ghoststep.street, p1street, 'Parent address must never be touched')
# turn on sync again
p1.write({'use_parent_address': True})
p1.refresh()
self.assertEqual(p1.street, ghoststep.street, 'Address fields must be synced again')
self.assertEqual(p1.phone, p1phone, 'Phone should be preserved after address sync')
self.assertEqual(p1.type, 'contact', 'Type should be preserved after address sync')
self.assertEqual(p1.email, 'denis.bladesmith@ghoststep.com', 'Email should be preserved after sync')
# Modify parent, sync to children
ghoststreet = 'South Street, 25'
ghoststep.write({'street': ghoststreet})
p1.refresh()
self.assertEqual(p1.street, ghoststreet, 'Address fields must be synced automatically')
self.assertEqual(p1.phone, p1phone, 'Phone should not be synced')
self.assertEqual(p1.email, 'denis.bladesmith@ghoststep.com', 'Email should be preserved after sync')
p1street = 'My Street, 11'
p1.write({'street': p1street})
ghoststep.refresh()
self.assertEqual(ghoststep.street, ghoststreet, 'Touching contact should never alter parent')
def test_30_res_partner_first_contact_sync(self):
""" Test initial creation of company/contact pair where contact address gets copied to
company """
cr, uid = self.cr, self.uid
ironshield = self.res_partner.browse(cr, uid, self.res_partner.name_create(cr, uid, 'IronShield')[0])
self.assertFalse(ironshield.is_company, 'Partners are not companies by default')
self.assertFalse(ironshield.use_parent_address, 'use_parent_address defaults to False')
self.assertEqual(ironshield.type, 'contact', 'Default type must be "contact"')
ironshield.write({'type': 'default'}) # force default type to double-check sync
p1 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid,
{'name': 'Isen Hardearth',
'street': 'Strongarm Avenue, 12',
'parent_id': ironshield.id}))
self.assertEquals(p1.type, 'contact', 'Default type must be "contact", not the copied parent type')
ironshield.refresh()
self.assertEqual(ironshield.street, p1.street, 'Address fields should be copied to company')
self.assertTrue(ironshield.is_company, 'Company flag should be turned on after first contact creation')
def test_40_res_partner_address_getc(self):
""" Test address_get address resolution mechanism: it should first go down through descendants,
stopping when encountering another is_copmany entity, then go up, stopping again at the first
is_company entity or the root ancestor and if nothing matches, it should use the provided partner
itself """
cr, uid = self.cr, self.uid
elmtree = self.res_partner.browse(cr, uid, self.res_partner.name_create(cr, uid, 'Elmtree')[0])
branch1 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Branch 1',
'parent_id': elmtree.id,
'is_company': True}))
leaf10 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Leaf 10',
'parent_id': branch1.id,
'type': 'invoice'}))
branch11 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Branch 11',
'parent_id': branch1.id,
'type': 'other'}))
leaf111 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Leaf 111',
'parent_id': branch11.id,
'type': 'delivery'}))
branch11.write({'is_company': False}) # force is_company after creating 1rst child
branch2 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Branch 2',
'parent_id': elmtree.id,
'is_company': True}))
leaf21 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Leaf 21',
'parent_id': branch2.id,
'type': 'delivery'}))
leaf22 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Leaf 22',
'parent_id': branch2.id}))
leaf23 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Leaf 23',
'parent_id': branch2.id,
'type': 'default'}))
# go up, stop at branch1
self.assertEqual(self.res_partner.address_get(cr, uid, [leaf111.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': leaf111.id,
'invoice': leaf10.id,
'contact': branch1.id,
'other': branch11.id,
'default': leaf111.id}, 'Invalid address resolution')
self.assertEqual(self.res_partner.address_get(cr, uid, [branch11.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': leaf111.id,
'invoice': leaf10.id,
'contact': branch1.id,
'other': branch11.id,
'default': branch11.id}, 'Invalid address resolution')
# go down, stop at at all child companies
self.assertEqual(self.res_partner.address_get(cr, uid, [elmtree.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': elmtree.id,
'invoice': elmtree.id,
'contact': elmtree.id,
'other': elmtree.id,
'default': elmtree.id}, 'Invalid address resolution')
# go down through children
self.assertEqual(self.res_partner.address_get(cr, uid, [branch1.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': leaf111.id,
'invoice': leaf10.id,
'contact': branch1.id,
'other': branch11.id,
'default': branch1.id}, 'Invalid address resolution')
self.assertEqual(self.res_partner.address_get(cr, uid, [branch2.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': leaf21.id,
'invoice': leaf23.id,
'contact': branch2.id,
'other': leaf23.id,
'default': leaf23.id}, 'Invalid address resolution')
# go up then down through siblings
self.assertEqual(self.res_partner.address_get(cr, uid, [leaf21.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': leaf21.id,
'invoice': leaf23.id,
'contact': branch2.id,
'other': leaf23.id,
'default': leaf23.id
}, 'Invalid address resolution, should scan commercial entity ancestor and its descendants')
self.assertEqual(self.res_partner.address_get(cr, uid, [leaf22.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': leaf21.id,
'invoice': leaf23.id,
'contact': leaf22.id,
'other': leaf23.id,
'default': leaf23.id}, 'Invalid address resolution, should scan commercial entity ancestor and its descendants')
self.assertEqual(self.res_partner.address_get(cr, uid, [leaf23.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': leaf21.id,
'invoice': leaf23.id,
'contact': branch2.id,
'other': leaf23.id,
'default': leaf23.id}, 'Invalid address resolution, `default` should only override if no partner with specific type exists')
# empty adr_pref means only 'default'
self.assertEqual(self.res_partner.address_get(cr, uid, [elmtree.id], []),
{'default': elmtree.id}, 'Invalid address resolution, no default means commercial entity ancestor')
self.assertEqual(self.res_partner.address_get(cr, uid, [leaf111.id], []),
{'default': leaf111.id}, 'Invalid address resolution, no default means contact itself')
branch11.write({'type': 'default'})
self.assertEqual(self.res_partner.address_get(cr, uid, [leaf111.id], []),
{'default': branch11.id}, 'Invalid address resolution, branch11 should now be default')
def test_50_res_partner_commercial_sync(self):
cr, uid = self.cr, self.uid
p0 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid,
{'name': 'Sigurd Sunknife',
'email': 'ssunknife@gmail.com'}))
sunhelm = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid,
{'name': 'Sunhelm',
'is_company': True,
'street': 'Rainbow Street, 13',
'phone': '1122334455',
'email': 'info@sunhelm.com',
'vat': 'BE0477472701',
'child_ids': [(4, p0.id),
(0, 0, {'name': 'Alrik Greenthorn',
'email': 'agr@sunhelm.com'})],
}))
p1 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid,
{'name': 'Otto Blackwood',
'email': 'otto.blackwood@sunhelm.com',
'parent_id': sunhelm.id}))
p11 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid,
{'name': 'Gini Graywool',
'email': 'ggr@sunhelm.com',
'parent_id': p1.id}))
p2 = self.res_partner.browse(cr, uid, self.res_partner.search(cr, uid,
[('email', '=', 'agr@sunhelm.com')])[0])
for p in (p0, p1, p11, p2):
p.refresh()
self.assertEquals(p.commercial_partner_id, sunhelm, 'Incorrect commercial entity resolution')
self.assertEquals(p.vat, sunhelm.vat, 'Commercial fields must be automatically synced')
sunhelmvat = 'BE0123456789'
sunhelm.write({'vat': sunhelmvat})
for p in (p0, p1, p11, p2):
p.refresh()
self.assertEquals(p.vat, sunhelmvat, 'Commercial fields must be automatically and recursively synced')
p1vat = 'BE0987654321'
p1.write({'vat': p1vat})
for p in (sunhelm, p0, p11, p2):
p.refresh()
self.assertEquals(p.vat, sunhelmvat, 'Sync to children should only work downstream and on commercial entities')
# promote p1 to commercial entity
vals = p1.onchange_type(is_company=True)['value']
p1.write(dict(vals, parent_id=sunhelm.id,
is_company=True,
name='Sunhelm Subsidiary'))
p1.refresh()
self.assertEquals(p1.vat, p1vat, 'Setting is_company should stop auto-sync of commercial fields')
self.assertEquals(p1.commercial_partner_id, p1, 'Incorrect commercial entity resolution after setting is_company')
# writing on parent should not touch child commercial entities
sunhelmvat2 = 'BE0112233445'
sunhelm.write({'vat': sunhelmvat2})
p1.refresh()
self.assertEquals(p1.vat, p1vat, 'Setting is_company should stop auto-sync of commercial fields')
p0.refresh()
self.assertEquals(p0.vat, sunhelmvat2, 'Commercial fields must be automatically synced')
def test_60_read_group(self):
cr, uid = self.cr, self.uid
title_sir = self.res_partner_title.create(cr, uid, {'name': 'Sir', 'domain': 'contact'})
title_lady = self.res_partner_title.create(cr, uid, {'name': 'Lady', 'domain': 'contact'})
test_users = [
{'name': 'Alice', 'login': 'alice', 'color': 1, 'function': 'Friend', 'date': '2015-03-28', 'title': title_lady},
{'name': 'Alice', 'login': 'alice2', 'color': 0, 'function': 'Friend', 'date': '2015-01-28', 'title': title_lady},
{'name': 'Bob', 'login': 'bob', 'color': 2, 'function': 'Friend', 'date': '2015-03-02', 'title': title_sir},
{'name': 'Eve', 'login': 'eve', 'color': 3, 'function': 'Eavesdropper', 'date': '2015-03-20', 'title': title_lady},
{'name': 'Nab', 'login': 'nab', 'color': -3, 'function': '5$ Wrench', 'date': '2014-09-10', 'title': title_sir},
{'name': 'Nab', 'login': 'nab-she', 'color': 6, 'function': '5$ Wrench', 'date': '2014-01-02', 'title': title_lady},
]
ids = [self.res_users.create(cr, uid, u) for u in test_users]
domain = [('id', 'in', ids)]
# group on local char field without domain and without active_test (-> empty WHERE clause)
groups_data = self.res_users.read_group(cr, uid, [], fields=['login'], groupby=['login'], orderby='login DESC', context={'active_test': False})
self.assertGreater(len(groups_data), 6, "Incorrect number of results when grouping on a field")
# group on local char field with limit
groups_data = self.res_users.read_group(cr, uid, domain, fields=['login'], groupby=['login'], orderby='login DESC', limit=3, offset=3)
self.assertEqual(len(groups_data), 3, "Incorrect number of results when grouping on a field with limit")
self.assertEqual(['bob', 'alice2', 'alice'], [g['login'] for g in groups_data], 'Result mismatch')
# group on inherited char field, aggregate on int field (second groupby ignored on purpose)
groups_data = self.res_users.read_group(cr, uid, domain, fields=['name', 'color', 'function'], groupby=['function', 'login'])
self.assertEqual(len(groups_data), 3, "Incorrect number of results when grouping on a field")
self.assertEqual(['5$ Wrench', 'Eavesdropper', 'Friend'], [g['function'] for g in groups_data], 'incorrect read_group order')
for group_data in groups_data:
self.assertIn('color', group_data, "Aggregated data for the column 'color' is not present in read_group return values")
self.assertEqual(group_data['color'], 3, "Incorrect sum for aggregated data for the column 'color'")
# group on inherited char field, reverse order
groups_data = self.res_users.read_group(cr, uid, domain, fields=['name', 'color'], groupby='name', orderby='name DESC')
self.assertEqual(['Nab', 'Eve', 'Bob', 'Alice'], [g['name'] for g in groups_data], 'Incorrect ordering of the list')
# group on int field, default ordering
groups_data = self.res_users.read_group(cr, uid, domain, fields=['color'], groupby='color')
self.assertEqual([-3, 0, 1, 2, 3, 6], [g['color'] for g in groups_data], 'Incorrect ordering of the list')
# multi group, second level is int field, should still be summed in first level grouping
groups_data = self.res_users.read_group(cr, uid, domain, fields=['name', 'color'], groupby=['name', 'color'], orderby='name DESC')
self.assertEqual(['Nab', 'Eve', 'Bob', 'Alice'], [g['name'] for g in groups_data], 'Incorrect ordering of the list')
self.assertEqual([3, 3, 2, 1], [g['color'] for g in groups_data], 'Incorrect ordering of the list')
# group on inherited char field, multiple orders with directions
groups_data = self.res_users.read_group(cr, uid, domain, fields=['name', 'color'], groupby='name', orderby='color DESC, name')
self.assertEqual(len(groups_data), 4, "Incorrect number of results when grouping on a field")
self.assertEqual(['Eve', 'Nab', 'Bob', 'Alice'], [g['name'] for g in groups_data], 'Incorrect ordering of the list')
self.assertEqual([1, 2, 1, 2], [g['name_count'] for g in groups_data], 'Incorrect number of results')
# group on inherited date column (res_partner.date) -> Year-Month, default ordering
groups_data = self.res_users.read_group(cr, uid, domain, fields=['function', 'color', 'date'], groupby=['date'])
self.assertEqual(len(groups_data), 4, "Incorrect number of results when grouping on a field")
self.assertEqual(['January 2014', 'September 2014', 'January 2015', 'March 2015'], [g['date'] for g in groups_data], 'Incorrect ordering of the list')
self.assertEqual([1, 1, 1, 3], [g['date_count'] for g in groups_data], 'Incorrect number of results')
# group on inherited date column (res_partner.date) -> Year-Month, custom order
groups_data = self.res_users.read_group(cr, uid, domain, fields=['function', 'color', 'date'], groupby=['date'], orderby='date DESC')
self.assertEqual(len(groups_data), 4, "Incorrect number of results when grouping on a field")
self.assertEqual(['March 2015', 'January 2015', 'September 2014', 'January 2014'], [g['date'] for g in groups_data], 'Incorrect ordering of the list')
self.assertEqual([3, 1, 1, 1], [g['date_count'] for g in groups_data], 'Incorrect number of results')
# group on inherited many2one (res_partner.title), default order
groups_data = self.res_users.read_group(cr, uid, domain, fields=['function', 'color', 'title'], groupby=['title'])
self.assertEqual(len(groups_data), 2, "Incorrect number of results when grouping on a field")
# m2o is returned as a (id, label) pair
self.assertEqual([(title_lady, 'Lady'), (title_sir, 'Sir')], [g['title'] for g in groups_data], 'Incorrect ordering of the list')
self.assertEqual([4, 2], [g['title_count'] for g in groups_data], 'Incorrect number of results')
self.assertEqual([10, -1], [g['color'] for g in groups_data], 'Incorrect aggregation of int column')
# group on inherited many2one (res_partner.title), reversed natural order
groups_data = self.res_users.read_group(cr, uid, domain, fields=['function', 'color', 'title'], groupby=['title'], orderby="title desc")
self.assertEqual(len(groups_data), 2, "Incorrect number of results when grouping on a field")
# m2o is returned as a (id, label) pair
self.assertEqual([(title_sir, 'Sir'), (title_lady, 'Lady')], [g['title'] for g in groups_data], 'Incorrect ordering of the list')
self.assertEqual([2, 4], [g['title_count'] for g in groups_data], 'Incorrect number of results')
self.assertEqual([-1, 10], [g['color'] for g in groups_data], 'Incorrect aggregation of int column')
# group on inherited many2one (res_partner.title), multiple orders with m2o in second position
groups_data = self.res_users.read_group(cr, uid, domain, fields=['function', 'color', 'title'], groupby=['title'], orderby="color desc, title desc")
self.assertEqual(len(groups_data), 2, "Incorrect number of results when grouping on a field")
# m2o is returned as a (id, label) pair
self.assertEqual([(title_lady, 'Lady'), (title_sir, 'Sir')], [g['title'] for g in groups_data], 'Incorrect ordering of the result')
self.assertEqual([4, 2], [g['title_count'] for g in groups_data], 'Incorrect number of results')
self.assertEqual([10, -1], [g['color'] for g in groups_data], 'Incorrect aggregation of int column')
# group on inherited many2one (res_partner.title), ordered by other inherited field (color)
groups_data = self.res_users.read_group(cr, uid, domain, fields=['function', 'color', 'title'], groupby=['title'], orderby='color')
self.assertEqual(len(groups_data), 2, "Incorrect number of results when grouping on a field")
# m2o is returned as a (id, label) pair
self.assertEqual([(title_sir, 'Sir'), (title_lady, 'Lady')], [g['title'] for g in groups_data], 'Incorrect ordering of the list')
self.assertEqual([2, 4], [g['title_count'] for g in groups_data], 'Incorrect number of results')
self.assertEqual([-1, 10], [g['color'] for g in groups_data], 'Incorrect aggregation of int column')
class test_partner_recursion(common.TransactionCase):
def setUp(self):
super(test_partner_recursion,self).setUp()
self.res_partner = self.registry('res.partner')
cr, uid = self.cr, self.uid
self.p1 = self.res_partner.name_create(cr, uid, 'Elmtree')[0]
self.p2 = self.res_partner.create(cr, uid, {'name': 'Elmtree Child 1', 'parent_id': self.p1})
self.p3 = self.res_partner.create(cr, uid, {'name': 'Elmtree Grand-Child 1.1', 'parent_id': self.p2})
# split 101, 102, 103 tests to force SQL rollback between them
def test_101_res_partner_recursion(self):
cr, uid, p1, p3 = self.cr, self.uid, self.p1, self.p3
self.assertRaises(except_orm, self.res_partner.write, cr, uid, [p1], {'parent_id': p3})
def test_102_res_partner_recursion(self):
cr, uid, p2, p3 = self.cr, self.uid, self.p2, self.p3
self.assertRaises(except_orm, self.res_partner.write, cr, uid, [p2], {'parent_id': p3})
def test_103_res_partner_recursion(self):
cr, uid, p3 = self.cr, self.uid, self.p3
self.assertRaises(except_orm, self.res_partner.write, cr, uid, [p3], {'parent_id': p3})
def test_104_res_partner_recursion_indirect_cycle(self):
""" Indirect hacky write to create cycle in children """
cr, uid, p2, p3 = self.cr, self.uid, self.p2, self.p3
p3b = self.res_partner.create(cr, uid, {'name': 'Elmtree Grand-Child 1.2', 'parent_id': self.p2})
self.assertRaises(except_orm, self.res_partner.write, cr, uid, [p2],
{'child_ids': [(1, p3, {'parent_id': p3b}), (1, p3b, {'parent_id': p3})]})
def test_110_res_partner_recursion_multi_update(self):
""" multi-write on several partners in same hierarchy must not trigger a false cycle detection """
cr, uid, p1, p2, p3 = self.cr, self.uid, self.p1, self.p2, self.p3
self.assertTrue(self.res_partner.write(cr, uid, [p1,p2,p3], {'phone': '123456'}))
class test_translation(common.TransactionCase):
def setUp(self):
super(test_translation, self).setUp()
self.res_category = self.registry('res.partner.category')
self.ir_translation = self.registry('ir.translation')
cr, uid = self.cr, self.uid
self.registry('ir.translation').load_module_terms(cr, ['base'], ['fr_FR'])
self.cat_id = self.res_category.create(cr, uid, {'name': 'Customers'})
self.ir_translation.create(cr, uid, {'name': 'res.partner.category,name', 'module':'base',
'value': 'Clients', 'res_id': self.cat_id, 'lang':'fr_FR', 'state':'translated', 'type': 'model'})
def test_101_create_translated_record(self):
cr, uid = self.cr, self.uid
no_context_cat = self.res_category.browse(cr, uid, self.cat_id)
self.assertEqual(no_context_cat.name, 'Customers', "Error in basic name_get")
fr_context_cat = self.res_category.browse(cr, uid, self.cat_id, context={'lang':'fr_FR'})
self.assertEqual(fr_context_cat.name, 'Clients', "Translation not found")
def test_102_duplicate_record(self):
cr, uid = self.cr, self.uid
self.new_cat_id = self.res_category.copy(cr, uid, self.cat_id, context={'lang':'fr_FR'})
no_context_cat = self.res_category.browse(cr, uid, self.new_cat_id)
self.assertEqual(no_context_cat.name, 'Customers', "Duplication did not set untranslated value")
fr_context_cat = self.res_category.browse(cr, uid, self.new_cat_id, context={'lang':'fr_FR'})
self.assertEqual(fr_context_cat.name, 'Clients', "Did not found translation for initial value")
def test_103_duplicate_record_fr(self):
cr, uid = self.cr, self.uid
self.new_fr_cat_id = self.res_category.copy(cr, uid, self.cat_id, default={'name': 'Clients (copie)'}, context={'lang':'fr_FR'})
no_context_cat = self.res_category.browse(cr, uid, self.new_fr_cat_id)
self.assertEqual(no_context_cat.name, 'Customers', "Duplication erased original untranslated value")
fr_context_cat = self.res_category.browse(cr, uid, self.new_fr_cat_id, context={'lang':'fr_FR'})
self.assertEqual(fr_context_cat.name, 'Clients (copie)', "Did not used default value for translated value")
test_state = None
#: Stores state information across multiple test classes
def setUpModule():
global test_state
test_state = {}
def tearDownModule():
global test_state
test_state = None
class TestPhaseInstall00(unittest2.TestCase):
"""
WARNING: Relies on tests being run in alphabetical order
"""
@classmethod
def setUpClass(cls):
cls.state = None
def test_00_setup(self):
type(self).state = 'init'
@common.at_install(False)
def test_01_no_install(self):
type(self).state = 'error'
def test_02_check(self):
self.assertEqual(
self.state, 'init',
"Testcase state should not have been transitioned from 00")
class TestPhaseInstall01(unittest2.TestCase):
at_install = False
def test_default_norun(self):
self.fail("An unmarket test in a non-at-install case should not run")
@common.at_install(True)
def test_set_run(self):
test_state['set_at_install'] = True
class TestPhaseInstall02(unittest2.TestCase):
"""
Can't put the check for test_set_run in the same class: if
@common.at_install does not work for test_set_run, it won't work for
the other one either. Thus move checking of whether test_set_run has
correctly run indeed to a separate class.
Warning: relies on *classes* being run in alphabetical order in test
modules
"""
def test_check_state(self):
self.assertTrue(
test_state.get('set_at_install'),
"The flag should be set if local overriding of runstate")
if __name__ == '__main__':
unittest2.main()
| agpl-3.0 |
jamiefolsom/edx-platform | common/djangoapps/xblock_django/migrations/0001_initial.py | 79 | 4946 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'XBlockDisableConfig'
db.create_table('xblock_django_xblockdisableconfig', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('change_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
('changed_by', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], null=True, on_delete=models.PROTECT)),
('enabled', self.gf('django.db.models.fields.BooleanField')(default=False)),
('disabled_blocks', self.gf('django.db.models.fields.TextField')(default='', blank=True)),
))
db.send_create_signal('xblock_django', ['XBlockDisableConfig'])
def backwards(self, orm):
# Deleting model 'XBlockDisableConfig'
db.delete_table('xblock_django_xblockdisableconfig')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'xblock_django.xblockdisableconfig': {
'Meta': {'ordering': "('-change_date',)", 'object_name': 'XBlockDisableConfig'},
'change_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'on_delete': 'models.PROTECT'}),
'disabled_blocks': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['xblock_django'] | agpl-3.0 |
edespino/gpdb | gpMgmt/bin/gppylib/test/unit/test_unit_gpstop.py | 4 | 22040 | import imp
import os
import sys
from gparray import GpDB, GpArray, Segment
from mock import Mock, patch
from gppylib.test.unit.gp_unittest import GpTestCase, run_tests
from gppylib.commands.gp import GpSegStopCmd
from gppylib.mainUtils import ProgramArgumentValidationException
class GpStop(GpTestCase):
def setUp(self):
# because gpstop does not have a .py extension,
# we have to use imp to import it
# if we had a gpstop.py, this is equivalent to:
# import gpstop
# self.subject = gpstop
gpstop_file = os.path.abspath(os.path.dirname(__file__) + "/../../../gpstop")
self.subject = imp.load_source('gpstop', gpstop_file)
self.subject.logger = Mock(spec=['log', 'warn', 'info', 'debug', 'error', 'warning', 'fatal'])
self.mock_gp = Mock()
self.mock_pgconf = Mock()
self.mock_os = Mock()
self.mock_conn = Mock()
self.mock_catalog = Mock()
self.mock_gperafile = Mock()
self.mock_unix = Mock()
self.gparray = self.createGpArrayWith4Primary4Mirrors()
self.apply_patches([
patch('gpstop.gp', return_value=self.mock_gp),
patch.object(GpSegStopCmd, "__init__", return_value=None),
patch('gpstop.pgconf', return_value=self.mock_pgconf),
patch('gpstop.os', return_value=self.mock_os),
patch('gpstop.dbconn.connect', return_value=self.mock_conn),
patch('gpstop.catalog', return_value=self.mock_catalog),
patch('gpstop.unix', return_value=self.mock_unix),
patch('gpstop.GpEraFile', return_value=self.mock_gperafile),
patch('gpstop.GpArray.initFromCatalog'),
patch('gpstop.gphostcache.unix.Ping'),
patch('gpstop.RemoteOperation'),
patch('gpstop.base.WorkerPool'),
])
sys.argv = ["gpstop"] # reset to relatively empty args list
# TODO: We are not unit testing how we report the segment stops. We've currently mocked it out
self.mock_workerpool = self.get_mock_from_apply_patch('WorkerPool')
self.mock_GpSegStopCmdInit = self.get_mock_from_apply_patch('__init__')
self.mock_gparray = self.get_mock_from_apply_patch('initFromCatalog')
self.mock_gparray.return_value = self.gparray
def tearDown(self):
super(GpStop, self).tearDown()
def createGpArrayWith4Primary4Mirrors(self):
self.master = GpDB.initFromString(
"1|-1|p|p|s|u|mdw|mdw|5432|None|/data/master||/data/master/base/10899,/data/master/base/1,/data/master/base/10898,/data/master/base/25780,/data/master/base/34782")
self.primary0 = GpDB.initFromString(
"2|0|p|p|s|u|sdw1|sdw1|40000|41000|/data/primary0||/data/primary0/base/10899,/data/primary0/base/1,/data/primary0/base/10898,/data/primary0/base/25780,/data/primary0/base/34782")
self.primary1 = GpDB.initFromString(
"3|1|p|p|s|u|sdw1|sdw1|40001|41001|/data/primary1||/data/primary1/base/10899,/data/primary1/base/1,/data/primary1/base/10898,/data/primary1/base/25780,/data/primary1/base/34782")
self.primary2 = GpDB.initFromString(
"4|2|p|p|s|u|sdw2|sdw2|40002|41002|/data/primary2||/data/primary2/base/10899,/data/primary2/base/1,/data/primary2/base/10898,/data/primary2/base/25780,/data/primary2/base/34782")
self.primary3 = GpDB.initFromString(
"5|3|p|p|s|u|sdw2|sdw2|40003|41003|/data/primary3||/data/primary3/base/10899,/data/primary3/base/1,/data/primary3/base/10898,/data/primary3/base/25780,/data/primary3/base/34782")
self.mirror0 = GpDB.initFromString(
"6|0|m|m|s|u|sdw2|sdw2|50000|51000|/data/mirror0||/data/mirror0/base/10899,/data/mirror0/base/1,/data/mirror0/base/10898,/data/mirror0/base/25780,/data/mirror0/base/34782")
self.mirror1 = GpDB.initFromString(
"7|1|m|m|s|u|sdw2|sdw2|50001|51001|/data/mirror1||/data/mirror1/base/10899,/data/mirror1/base/1,/data/mirror1/base/10898,/data/mirror1/base/25780,/data/mirror1/base/34782")
self.mirror2 = GpDB.initFromString(
"8|2|m|m|s|u|sdw1|sdw1|50002|51002|/data/mirror2||/data/mirror2/base/10899,/data/mirror2/base/1,/data/mirror2/base/10898,/data/mirror2/base/25780,/data/mirror2/base/34782")
self.mirror3 = GpDB.initFromString(
"9|3|m|m|s|u|sdw1|sdw1|50003|51003|/data/mirror3||/data/mirror3/base/10899,/data/mirror3/base/1,/data/mirror3/base/10898,/data/mirror3/base/25780,/data/mirror3/base/34782")
return GpArray([self.master, self.primary0, self.primary1, self.primary2, self.primary3, self.mirror0, self.mirror1, self.mirror2, self.mirror3])
def get_info_messages(self):
return [args[0][0] for args in self.subject.logger.info.call_args_list]
def get_error_messages(self):
return [args[0][0] for args in self.subject.logger.error.call_args_list]
@patch('gpstop.userinput', return_value=Mock(spec=['ask_yesno']))
def test_option_master_success_without_auto_accept(self, mock_userinput):
sys.argv = ["gpstop", "-m"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
mock_userinput.ask_yesno.return_value = True
gpstop = self.subject.GpStop.createProgram(options, args)
gpstop.run()
self.assertEqual(mock_userinput.ask_yesno.call_count, 1)
mock_userinput.ask_yesno.assert_called_once_with(None, '\nContinue with master-only shutdown', 'N')
@patch('gpstop.userinput', return_value=Mock(spec=['ask_yesno']))
def test_option_master_success_with_auto_accept(self, mock_userinput):
sys.argv = ["gpstop", "-m", "-a"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
mock_userinput.ask_yesno.return_value = True
gpstop = self.subject.GpStop.createProgram(options, args)
gpstop.run()
self.assertEqual(mock_userinput.ask_yesno.call_count, 0)
def test_option_hostonly_succeeds(self):
sys.argv = ["gpstop", "-a", "--host", "sdw1"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
gpstop = self.subject.GpStop.createProgram(options, args)
gpstop.run()
log_messages = self.get_info_messages()
self.assertNotIn("sdw1 /data/mirror1 50001 u", log_messages)
self.assertIn("Targeting dbid %s for shutdown" % [self.primary0.getSegmentDbId(),
self.primary1.getSegmentDbId(),
self.mirror2.getSegmentDbId(),
self.mirror3.getSegmentDbId()], log_messages)
self.assertIn("Successfully shutdown 4 of 8 segment instances ", log_messages)
def test_host_missing_from_config(self):
sys.argv = ["gpstop", "-a", "--host", "nothere"]
host_names = self.gparray.getSegmentsByHostName(self.gparray.getDbList()).keys()
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
gpstop = self.subject.GpStop.createProgram(options, args)
with self.assertRaises(SystemExit) as cm:
gpstop.run()
self.assertEquals(cm.exception.code, 1)
error_msgs = self.get_error_messages()
self.assertIn("host 'nothere' is not found in gp_segment_configuration", error_msgs)
self.assertIn("hosts in cluster config: %s" % host_names, error_msgs)
@patch('gpstop.userinput', return_value=Mock(spec=['ask_yesno']))
def test_happypath_in_interactive_mode(self, mock_userinput):
sys.argv = ["gpstop", "--host", "sdw1"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
mock_userinput.ask_yesno.return_value = True
gpstop = self.subject.GpStop.createProgram(options, args)
gpstop.run()
log_messages = self.get_info_messages()
# two calls per host, first for primaries then for mirrors
self.assertEquals(2, self.mock_GpSegStopCmdInit.call_count)
self.assertIn("Targeting dbid %s for shutdown" % [self.primary0.getSegmentDbId(),
self.primary1.getSegmentDbId(),
self.mirror2.getSegmentDbId(),
self.mirror3.getSegmentDbId()], log_messages)
# call_obj[0] returns all unnamed arguments -> ['arg1', 'arg2']
# In this case, we have an object as an argument to poo.addCommand
# call_obj[1] returns a dict for all named arguments -> {key='arg3', key2='arg4'}
self.assertEquals(self.mock_GpSegStopCmdInit.call_args_list[0][1]['dbs'][0], self.primary0)
self.assertEquals(self.mock_GpSegStopCmdInit.call_args_list[0][1]['dbs'][1], self.primary1)
self.assertEquals(self.mock_GpSegStopCmdInit.call_args_list[1][1]['dbs'][0], self.mirror2)
self.assertEquals(self.mock_GpSegStopCmdInit.call_args_list[1][1]['dbs'][1], self.mirror3)
self.assertIn(" sdw1 /data/primary0 40000 u", log_messages)
self.assertIn(" sdw1 /data/primary1 40001 u", log_messages)
self.assertIn(" sdw1 /data/mirror2 50002 u", log_messages)
self.assertIn(" sdw1 /data/mirror3 50003 u", log_messages)
for line in log_messages:
self.assertNotRegexpMatches(line, "sdw2")
self.assertIn("Successfully shutdown 4 of 8 segment instances ", log_messages)
def test_host_option_segment_in_change_tracking_mode_fails(self):
sys.argv = ["gpstop", "-a", "--host", "sdw1"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
self.primary0 = GpDB.initFromString(
"2|0|p|p|c|u|sdw1|sdw1|40000|41000|/data/primary0||/data/primary0/base/10899,/data/primary0/base/1,/data/primary0/base/10898,/data/primary0/base/25780,/data/primary0/base/34782")
self.mirror0 = GpDB.initFromString(
"6|0|m|m|s|d|sdw2|sdw2|50000|51000|/data/mirror0||/data/mirror0/base/10899,/data/mirror0/base/1,/data/mirror0/base/10898,/data/mirror0/base/25780,/data/mirror0/base/34782")
self.mock_gparray.return_value = GpArray([self.master, self.primary0,
self.primary1, self.primary2,
self.primary3, self.mirror0,
self.mirror1, self.mirror2,
self.mirror3])
gpstop = self.subject.GpStop.createProgram(options, args)
with self.assertRaisesRegexp(Exception,"Segment '%s' not synchronized. Aborting." % self.primary0):
gpstop.run()
self.assertEquals(0, self.mock_GpSegStopCmdInit.call_count)
def test_host_option_segment_in_resynchronizing_mode_fails(self):
sys.argv = ["gpstop", "-a", "--host", "sdw1"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
self.primary0 = GpDB.initFromString(
"2|0|p|p|r|u|sdw1|sdw1|40000|41000|/data/primary0||/data/primary0/base/10899,/data/primary0/base/1,/data/primary0/base/10898,/data/primary0/base/25780,/data/primary0/base/34782")
self.mirror0 = GpDB.initFromString(
"6|0|m|m|r|u|sdw2|sdw2|50000|51000|/data/mirror0||/data/mirror0/base/10899,/data/mirror0/base/1,/data/mirror0/base/10898,/data/mirror0/base/25780,/data/mirror0/base/34782")
self.mock_gparray.return_value = GpArray([self.master, self.primary0,
self.primary1, self.primary2,
self.primary3, self.mirror0,
self.mirror1, self.mirror2,
self.mirror3])
gpstop = self.subject.GpStop.createProgram(options, args)
with self.assertRaisesRegexp(Exception,"Segment '%s' not synchronized. Aborting." % self.primary0):
gpstop.run()
self.assertEquals(0, self.mock_GpSegStopCmdInit.call_count)
def test_host_option_segment_down_is_skipped_succeeds(self):
sys.argv = ["gpstop", "-a", "--host", "sdw1"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
self.primary0 = GpDB.initFromString(
"2|0|m|p|s|d|sdw1|sdw1|40000|41000|/data/primary0||/data/primary0/base/10899,/data/primary0/base/1,/data/primary0/base/10898,/data/primary0/base/25780,/data/primary0/base/34782")
self.mirror0 = GpDB.initFromString(
"6|0|p|m|c|u|sdw2|sdw2|50000|51000|/data/mirror0||/data/mirror0/base/10899,/data/mirror0/base/1,/data/mirror0/base/10898,/data/mirror0/base/25780,/data/mirror0/base/34782")
self.mock_gparray.return_value = GpArray([self.master, self.primary0,
self.primary1, self.primary2,
self.primary3, self.mirror0,
self.mirror1, self.mirror2,
self.mirror3])
gpstop = self.subject.GpStop.createProgram(options, args)
gpstop.run()
log_messages = self.get_info_messages()
self.assertEquals(2, self.mock_GpSegStopCmdInit.call_count)
self.assertIn("Targeting dbid %s for shutdown" % [self.primary1.getSegmentDbId(),
self.mirror2.getSegmentDbId(),
self.mirror3.getSegmentDbId()], log_messages)
self.assertIn("Successfully shutdown 3 of 8 segment instances ", log_messages)
def test_host_option_segment_on_same_host_with_mirror_fails(self):
sys.argv = ["gpstop", "-a", "--host", "sdw1"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
self.master = GpDB.initFromString(
"1|-1|p|p|s|u|mdw|mdw|5432|None|/data/master||/data/master/base/10899,/data/master/base/1,/data/master/base/10898,/data/master/base/25780,/data/master/base/34782")
self.primary0 = GpDB.initFromString(
"2|0|p|p|s|u|sdw1|sdw1|40000|41000|/data/primary0||/data/primary0/base/10899,/data/primary0/base/1,/data/primary0/base/10898,/data/primary0/base/25780,/data/primary0/base/34782")
self.mirror0 = GpDB.initFromString(
"3|0|m|m|s|u|sdw1|sdw1|50000|51000|/data/mirror0||/data/mirror0/base/10899,/data/mirror0/base/1,/data/mirror0/base/10898,/data/mirror0/base/25780,/data/mirror0/base/34782")
self.mock_gparray.return_value = GpArray([self.master, self.primary0, self.mirror0])
gpstop = self.subject.GpStop.createProgram(options, args)
with self.assertRaisesRegexp(Exception,"Segment host '%s' has both of corresponding primary '%s' and mirror '%s'. Aborting." % (self.primary0.getSegmentHostName(), self.primary0, self.mirror0)):
gpstop.run()
self.assertEquals(0, self.mock_GpSegStopCmdInit.call_count)
def test_host_option_if_master_running_on_the_host_fails(self):
sys.argv = ["gpstop", "-a", "--host", "mdw"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
self.master = GpDB.initFromString(
"1|-1|p|p|s|u|mdw|mdw|5432|None|/data/master||/data/master/base/10899,/data/master/base/1,/data/master/base/10898,/data/master/base/25780,/data/master/base/34782")
self.primary0 = GpDB.initFromString(
"2|0|p|p|s|u|sdw1|sdw1|40000|41000|/data/primary0||/data/primary0/base/10899,/data/primary0/base/1,/data/primary0/base/10898,/data/primary0/base/25780,/data/primary0/base/34782")
self.mirror0 = GpDB.initFromString(
"3|0|m|m|s|u|sdw1|sdw1|50000|51000|/data/mirror0||/data/mirror0/base/10899,/data/mirror0/base/1,/data/mirror0/base/10898,/data/mirror0/base/25780,/data/mirror0/base/34782")
self.mock_gparray.return_value = GpArray([self.master, self.primary0, self.mirror0])
gpstop = self.subject.GpStop.createProgram(options, args)
with self.assertRaisesRegexp(Exception,"Specified host '%s' has the master or standby master on it. This node can only be stopped as part of a full-cluster gpstop, without '--host'." %
self.master.getSegmentHostName()):
gpstop.run()
self.assertEquals(0, self.mock_GpSegStopCmdInit.call_count)
def test_host_option_if_standby_running_on_the_host_fails(self):
sys.argv = ["gpstop", "-a", "--host", "sdw1"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
self.master = GpDB.initFromString(
"1|-1|p|p|s|u|mdw|mdw|5432|None|/data/master||/data/master/base/10899,/data/master/base/1,/data/master/base/10898,/data/master/base/25780,/data/master/base/34782")
self.standby = GpDB.initFromString(
"2|-1|m|m|s|u|sdw1|sdw1|25432|None|/data/master||/data/master/base/10899,/data/master/base/1,/data/master/base/10898,/data/master/base/25780,/data/master/base/34782")
self.primary0 = GpDB.initFromString(
"3|0|p|p|s|u|sdw1|sdw1|40000|41000|/data/primary0||/data/primary0/base/10899,/data/primary0/base/1,/data/primary0/base/10898,/data/primary0/base/25780,/data/primary0/base/34782")
self.mirror0 = GpDB.initFromString(
"4|0|m|m|s|u|sdw2|sdw2|50000|51000|/data/mirror0||/data/mirror0/base/10899,/data/mirror0/base/1,/data/mirror0/base/10898,/data/mirror0/base/25780,/data/mirror0/base/34782")
self.mock_gparray.return_value = GpArray([self.master, self.standby, self.primary0, self.mirror0])
gpstop = self.subject.GpStop.createProgram(options, args)
with self.assertRaisesRegexp(Exception,"Specified host '%s' has the master or standby master on it. This node can only be stopped as part of a full-cluster gpstop, without '--host'." %
self.standby.getSegmentHostName()):
gpstop.run()
self.assertEquals(0, self.mock_GpSegStopCmdInit.call_count)
def test_host_option_if_no_mirrors_fails(self):
sys.argv = ["gpstop", "-a", "--host", "sdw2"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
self.master = GpDB.initFromString(
"1|-1|p|p|s|u|mdw|mdw|5432|None|/data/master||/data/master/base/10899,/data/master/base/1,/data/master/base/10898,/data/master/base/25780,/data/master/base/34782")
self.standby = GpDB.initFromString(
"2|-1|m|m|s|u|sdw1|sdw1|25432|None|/data/master||/data/master/base/10899,/data/master/base/1,/data/master/base/10898,/data/master/base/25780,/data/master/base/34782")
self.primary0 = GpDB.initFromString(
"3|0|p|p|s|u|sdw1|sdw1|40000|41000|/data/primary0||/data/primary0/base/10899,/data/primary0/base/1,/data/primary0/base/10898,/data/primary0/base/25780,/data/primary0/base/34782")
self.primary1 = GpDB.initFromString(
"4|0|p|p|s|u|sdw2|sdw2|40001|41001|/data/primary1||/data/primary1/base/10899,/data/primary1/base/1,/data/primary1/base/10898,/data/primary1/base/25780,/data/primary1/base/34782")
self.mock_gparray.return_value = GpArray([self.master, self.standby, self.primary0, self.primary1])
gpstop = self.subject.GpStop.createProgram(options, args)
with self.assertRaisesRegexp(Exception,"Cannot perform host-specific gpstop on a cluster without segment mirroring."):
gpstop.run()
self.assertEquals(0, self.mock_GpSegStopCmdInit.call_count)
def test_host_option_with_master_option_fails(self):
sys.argv = ["gpstop", "--host", "sdw1", "-m"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
with self.assertRaisesRegexp(ProgramArgumentValidationException, "Incompatible flags. Cannot mix '--host' "
"option with '-m' for master-only."):
self.subject.GpStop.createProgram(options, args)
def test_host_option_with_restart_option_fails(self):
sys.argv = ["gpstop", "--host", "sdw1", "-r"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
with self.assertRaisesRegexp(ProgramArgumentValidationException, "Incompatible flags. Cannot mix '--host' "
"option with '-r' for restart."):
self.subject.GpStop.createProgram(options, args)
def test_host_option_with_request_sighup_option_fails(self):
sys.argv = ["gpstop", "--host", "sdw1", "-u"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
with self.assertRaisesRegexp(ProgramArgumentValidationException, "Incompatible flags. Cannot mix '--host' "
"option with '-u' for config reload."):
self.subject.GpStop.createProgram(options, args)
def test_host_option_with_stop_standby_option_fails(self):
sys.argv = ["gpstop", "--host", "sdw1", "-y"]
parser = self.subject.GpStop.createParser()
options, args = parser.parse_args()
with self.assertRaisesRegexp(ProgramArgumentValidationException, "Incompatible flags. Cannot mix '--host' "
"option with '-y' for skipping standby."):
self.subject.GpStop.createProgram(options, args)
if __name__ == '__main__':
run_tests()
| apache-2.0 |
KeyWeeUsr/kivy | kivy/uix/dropdown.py | 16 | 12790 | '''
Drop-Down List
==============
.. image:: images/dropdown.gif
:align: right
.. versionadded:: 1.4.0
A versatile drop-down list that can be used with custom widgets. It allows you
to display a list of widgets under a displayed widget. Unlike other toolkits,
the list of widgets can contain any type of widget: simple buttons,
images etc.
The positioning of the drop-down list is fully automatic: we will always try to
place the dropdown list in a way that the user can select an item in the list.
Basic example
-------------
A button with a dropdown list of 10 possible values. All the buttons within the
dropdown list will trigger the dropdown :meth:`DropDown.select` method. After
being called, the main button text will display the selection of the
dropdown. ::
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.base import runTouchApp
# create a dropdown with 10 buttons
dropdown = DropDown()
for index in range(10):
# When adding widgets, we need to specify the height manually
# (disabling the size_hint_y) so the dropdown can calculate
# the area it needs.
btn = Button(text='Value %d' % index, size_hint_y=None, height=44)
# for each button, attach a callback that will call the select() method
# on the dropdown. We'll pass the text of the button as the data of the
# selection.
btn.bind(on_release=lambda btn: dropdown.select(btn.text))
# then add the button inside the dropdown
dropdown.add_widget(btn)
# create a big main button
mainbutton = Button(text='Hello', size_hint=(None, None))
# show the dropdown menu when the main button is released
# note: all the bind() calls pass the instance of the caller (here, the
# mainbutton instance) as the first argument of the callback (here,
# dropdown.open.).
mainbutton.bind(on_release=dropdown.open)
# one last thing, listen for the selection in the dropdown list and
# assign the data to the button text.
dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
runTouchApp(mainbutton)
Extending dropdown in Kv
------------------------
You could create a dropdown directly from your kv::
#:kivy 1.4.0
<CustomDropDown>:
Button:
text: 'My first Item'
size_hint_y: None
height: 44
on_release: root.select('item1')
Label:
text: 'Unselectable item'
size_hint_y: None
height: 44
Button:
text: 'My second Item'
size_hint_y: None
height: 44
on_release: root.select('item2')
And then, create the associated python class and use it::
class CustomDropDown(DropDown):
pass
dropdown = CustomDropDown()
mainbutton = Button(text='Hello', size_hint=(None, None))
mainbutton.bind(on_release=dropdown.open)
dropdown.bind(on_select=lambda instance, x: setattr(mainbutton, 'text', x))
'''
__all__ = ('DropDown', )
from kivy.uix.scrollview import ScrollView
from kivy.properties import ObjectProperty, NumericProperty, BooleanProperty
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.clock import Clock
from kivy.config import Config
_grid_kv = '''
GridLayout:
size_hint_y: None
height: self.minimum_size[1]
cols: 1
'''
class DropDownException(Exception):
'''DropDownException class.
'''
pass
class DropDown(ScrollView):
'''DropDown class. See module documentation for more information.
:Events:
`on_select`: data
Fired when a selection is done. The data of the selection is passed
in as the first argument and is what you pass in the :meth:`select`
method as the first argument.
`on_dismiss`:
.. versionadded:: 1.8.0
Fired when the DropDown is dismissed, either on selection or on
touching outside the widget.
'''
auto_width = BooleanProperty(True)
'''By default, the width of the dropdown will be the same as the width of
the attached widget. Set to False if you want to provide your own width.
:attr:`auto_width` is a :class:`~kivy.properties.BooleanProperty`
and defaults to True.
'''
max_height = NumericProperty(None, allownone=True)
'''Indicate the maximum height that the dropdown can take. If None, it will
take the maximum height available until the top or bottom of the screen
is reached.
:attr:`max_height` is a :class:`~kivy.properties.NumericProperty` and
defaults to None.
'''
dismiss_on_select = BooleanProperty(True)
'''By default, the dropdown will be automatically dismissed when a
selection has been done. Set to False to prevent the dismiss.
:attr:`dismiss_on_select` is a :class:`~kivy.properties.BooleanProperty`
and defaults to True.
'''
auto_dismiss = BooleanProperty(True)
'''By default, the dropdown will be automatically dismissed when a
touch happens outside of it, this option allows to disable this
feature
:attr:`auto_dismiss` is a :class:`~kivy.properties.BooleanProperty`
and defaults to True.
.. versionadded:: 1.8.0
'''
min_state_time = NumericProperty(0)
'''Minimum time before the :class:`~kivy.uix.DropDown` is dismissed.
This is used to allow for the widget inside the dropdown to display
a down state or for the :class:`~kivy.uix.DropDown` itself to
display a animation for closing.
:attr:`min_state_time` is a :class:`~kivy.properties.NumericProperty`
and defaults to the `Config` value `min_state_time`.
.. versionadded:: 1.10.0
'''
attach_to = ObjectProperty(allownone=True)
'''(internal) Property that will be set to the widget to which the
drop down list is attached.
The :meth:`open` method will automatically set this property whilst
:meth:`dismiss` will set it back to None.
'''
container = ObjectProperty()
'''(internal) Property that will be set to the container of the dropdown
list. It is a :class:`~kivy.uix.gridlayout.GridLayout` by default.
'''
__events__ = ('on_select', 'on_dismiss')
def __init__(self, **kwargs):
self._win = None
if 'min_state_time' not in kwargs:
self.min_state_time = float(
Config.get('graphics', 'min_state_time'))
if 'container' not in kwargs:
c = self.container = Builder.load_string(_grid_kv)
else:
c = None
if 'do_scroll_x' not in kwargs:
self.do_scroll_x = False
if 'size_hint' not in kwargs:
if 'size_hint_x' not in kwargs:
self.size_hint_x = None
if 'size_hint_y' not in kwargs:
self.size_hint_y = None
super(DropDown, self).__init__(**kwargs)
if c is not None:
super(DropDown, self).add_widget(c)
self.on_container(self, c)
Window.bind(
on_key_down=self.on_key_down,
size=self._reposition)
self.fbind('size', self._reposition)
def on_key_down(self, instance, key, scancode, codepoint, modifiers):
if key == 27 and self.get_parent_window():
self.dismiss()
return True
def on_container(self, instance, value):
if value is not None:
self.container.bind(minimum_size=self._reposition)
def open(self, widget):
'''Open the dropdown list and attach it to a specific widget.
Depending on the position of the widget within the window and
the height of the dropdown, the dropdown might be above or below
that widget.
'''
# ensure we are not already attached
if self.attach_to is not None:
self.dismiss()
# we will attach ourself to the main window, so ensure the
# widget we are looking for have a window
self._win = widget.get_parent_window()
if self._win is None:
raise DropDownException(
'Cannot open a dropdown list on a hidden widget')
self.attach_to = widget
widget.bind(pos=self._reposition, size=self._reposition)
self._reposition()
# attach ourself to the main window
self._win.add_widget(self)
def dismiss(self, *largs):
'''Remove the dropdown widget from the window and detach it from
the attached widget.
'''
Clock.schedule_once(lambda dt: self._real_dismiss(),
self.min_state_time)
def _real_dismiss(self):
if self.parent:
self.parent.remove_widget(self)
if self.attach_to:
self.attach_to.unbind(pos=self._reposition, size=self._reposition)
self.attach_to = None
self.dispatch('on_dismiss')
def on_dismiss(self):
pass
def select(self, data):
'''Call this method to trigger the `on_select` event with the `data`
selection. The `data` can be anything you want.
'''
self.dispatch('on_select', data)
if self.dismiss_on_select:
self.dismiss()
def on_select(self, data):
pass
def add_widget(self, *largs):
if self.container:
return self.container.add_widget(*largs)
return super(DropDown, self).add_widget(*largs)
def remove_widget(self, *largs):
if self.container:
return self.container.remove_widget(*largs)
return super(DropDown, self).remove_widget(*largs)
def clear_widgets(self):
if self.container:
return self.container.clear_widgets()
return super(DropDown, self).clear_widgets()
def on_touch_down(self, touch):
if super(DropDown, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos):
return True
if (self.attach_to and self.attach_to.collide_point(
*self.attach_to.to_widget(*touch.pos))):
return True
if self.auto_dismiss:
self.dismiss()
def on_touch_up(self, touch):
if super(DropDown, self).on_touch_up(touch):
return True
if 'button' in touch.profile and touch.button.startswith('scroll'):
return
if self.collide_point(*touch.pos):
return True
if self.auto_dismiss:
self.dismiss()
def _reposition(self, *largs):
# calculate the coordinate of the attached widget in the window
# coordinate system
win = self._win
widget = self.attach_to
if not widget or not win:
return
wx, wy = widget.to_window(*widget.pos)
wright, wtop = widget.to_window(widget.right, widget.top)
# set width and x
if self.auto_width:
self.width = wright - wx
# ensure the dropdown list doesn't get out on the X axis, with a
# preference to 0 in case the list is too wide.
x = wx
if x + self.width > win.width:
x = win.width - self.width
if x < 0:
x = 0
self.x = x
# determine if we display the dropdown upper or lower to the widget
if self.max_height is not None:
height = min(self.max_height, self.container.minimum_height)
else:
height = self.container.minimum_height
h_bottom = wy - height
h_top = win.height - (wtop + height)
if h_bottom > 0:
self.top = wy
self.height = height
elif h_top > 0:
self.y = wtop
self.height = height
else:
# none of both top/bottom have enough place to display the
# widget at the current size. Take the best side, and fit to
# it.
if h_top < h_bottom:
self.top = self.height = wy
else:
self.y = wtop
self.height = win.height - wtop
if __name__ == '__main__':
from kivy.uix.button import Button
from kivy.base import runTouchApp
def show_dropdown(button, *largs):
dp = DropDown()
dp.bind(on_select=lambda instance, x: setattr(button, 'text', x))
for i in range(10):
item = Button(text='hello %d' % i, size_hint_y=None, height=44)
item.bind(on_release=lambda btn: dp.select(btn.text))
dp.add_widget(item)
dp.open(button)
def touch_move(instance, touch):
instance.center = touch.pos
btn = Button(text='SHOW', size_hint=(None, None), pos=(300, 200))
btn.bind(on_release=show_dropdown, on_touch_move=touch_move)
runTouchApp(btn)
| mit |
danilito19/django | tests/template_tests/filter_tests/test_addslashes.py | 473 | 1202 | from django.template.defaultfilters import addslashes
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import setup
class AddslashesTests(SimpleTestCase):
@setup({'addslashes01': '{% autoescape off %}{{ a|addslashes }} {{ b|addslashes }}{% endautoescape %}'})
def test_addslashes01(self):
output = self.engine.render_to_string('addslashes01', {"a": "<a>'", "b": mark_safe("<a>'")})
self.assertEqual(output, r"<a>\' <a>\'")
@setup({'addslashes02': '{{ a|addslashes }} {{ b|addslashes }}'})
def test_addslashes02(self):
output = self.engine.render_to_string('addslashes02', {"a": "<a>'", "b": mark_safe("<a>'")})
self.assertEqual(output, r"<a>\' <a>\'")
class FunctionTests(SimpleTestCase):
def test_quotes(self):
self.assertEqual(
addslashes('"double quotes" and \'single quotes\''),
'\\"double quotes\\" and \\\'single quotes\\\'',
)
def test_backslashes(self):
self.assertEqual(addslashes(r'\ : backslashes, too'), '\\\\ : backslashes, too')
def test_non_string_input(self):
self.assertEqual(addslashes(123), '123')
| bsd-3-clause |
gasman/wagtaildemo | wagtaildemo/wsgi.py | 17 | 1144 | """
WSGI config for wagtaildemo project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wagtaildemo.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| bsd-3-clause |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.5.0/Lib/email/mime/application.py | 414 | 1256 | # Copyright (C) 2001-2006 Python Software Foundation
# Author: Keith Dart
# Contact: email-sig@python.org
"""Class representing application/* type MIME documents."""
__all__ = ["MIMEApplication"]
from email import encoders
from email.mime.nonmultipart import MIMENonMultipart
class MIMEApplication(MIMENonMultipart):
"""Class for generating application/* MIME documents."""
def __init__(self, _data, _subtype='octet-stream',
_encoder=encoders.encode_base64, **_params):
"""Create an application/* type MIME document.
_data is a string containing the raw application data.
_subtype is the MIME content type subtype, defaulting to
'octet-stream'.
_encoder is a function which will perform the actual encoding for
transport of the application data, defaulting to base64 encoding.
Any additional keyword arguments are passed to the base class
constructor, which turns them into parameters on the Content-Type
header.
"""
if _subtype is None:
raise TypeError('Invalid application MIME subtype')
MIMENonMultipart.__init__(self, 'application', _subtype, **_params)
self.set_payload(_data)
_encoder(self)
| mit |
yufish/youtube-dl | youtube_dl/extractor/fivetv.py | 139 | 2959 | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import int_or_none
class FiveTVIE(InfoExtractor):
_VALID_URL = r'''(?x)
http://
(?:www\.)?5-tv\.ru/
(?:
(?:[^/]+/)+(?P<id>\d+)|
(?P<path>[^/?#]+)(?:[/?#])?
)
'''
_TESTS = [{
'url': 'http://5-tv.ru/news/96814/',
'md5': 'bbff554ad415ecf5416a2f48c22d9283',
'info_dict': {
'id': '96814',
'ext': 'mp4',
'title': 'Россияне выбрали имя для общенациональной платежной системы',
'description': 'md5:a8aa13e2b7ad36789e9f77a74b6de660',
'thumbnail': 're:^https?://.*\.jpg$',
'duration': 180,
},
}, {
'url': 'http://5-tv.ru/video/1021729/',
'info_dict': {
'id': '1021729',
'ext': 'mp4',
'title': '3D принтер',
'description': 'md5:d76c736d29ef7ec5c0cf7d7c65ffcb41',
'thumbnail': 're:^https?://.*\.jpg$',
'duration': 180,
},
}, {
'url': 'http://www.5-tv.ru/glavnoe/#itemDetails',
'info_dict': {
'id': 'glavnoe',
'ext': 'mp4',
'title': 'Итоги недели с 8 по 14 июня 2015 года',
'thumbnail': 're:^https?://.*\.jpg$',
},
}, {
'url': 'http://www.5-tv.ru/glavnoe/broadcasts/508645/',
'only_matching': True,
}, {
'url': 'http://5-tv.ru/films/1507502/',
'only_matching': True,
}, {
'url': 'http://5-tv.ru/programs/broadcast/508713/',
'only_matching': True,
}, {
'url': 'http://5-tv.ru/angel/',
'only_matching': True,
}, {
'url': 'http://www.5-tv.ru/schedule/?iframe=true&width=900&height=450',
'only_matching': True,
}]
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id') or mobj.group('path')
webpage = self._download_webpage(url, video_id)
video_url = self._search_regex(
r'<a[^>]+?href="([^"]+)"[^>]+?class="videoplayer"',
webpage, 'video url')
title = self._og_search_title(webpage, default=None) or self._search_regex(
r'<title>([^<]+)</title>', webpage, 'title')
duration = int_or_none(self._og_search_property(
'video:duration', webpage, 'duration', default=None))
return {
'id': video_id,
'url': video_url,
'title': title,
'description': self._og_search_description(webpage, default=None),
'thumbnail': self._og_search_thumbnail(webpage, default=None),
'duration': duration,
}
| unlicense |
squirrelo/qiita | qiita_pet/handlers/study_handlers/tests/test_prep_template.py | 1 | 2221 | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------------------------
from unittest import main
from json import loads
from qiita_pet.test.tornado_test_base import TestHandlerBase
class TestNewPrepTemplateAjax(TestHandlerBase):
def test_get(self):
response = self.get('/study/new_prep_template/', {'study_id': '1'})
self.assertEqual(response.code, 200)
class TestPrepTemplateGraphAJAX(TestHandlerBase):
def test_get(self):
response = self.get('/prep/graph/', {'prep_id': 1})
self.assertEqual(response.code, 200)
exp = {"status": "success",
"node_labels": [[1, "Raw data 1 - FASTQ"],
[3, "Demultiplexed 2 - Demultiplexed"],
[2, "Demultiplexed 1 - Demultiplexed"],
[4, "BIOM - BIOM"],
[5, "BIOM - BIOM"],
[6, "BIOM - BIOM"]],
"message": "",
"edge_list": [[1, 3], [1, 2], [2, 4], [2, 5], [2, 6]]}
obs = loads(response.body)
self.assertEqual(obs['status'], exp['status'])
self.assertEqual(obs['message'], exp['message'])
self.assertItemsEqual(obs['node_labels'], exp['node_labels'])
self.assertItemsEqual(obs['edge_list'], exp['edge_list'])
class TestPrepTemplateAJAXReadOnly(TestHandlerBase):
def test_get(self):
response = self.get('/study/description/prep_template/',
{'prep_id': 1, 'study_id': 1})
self.assertEqual(response.code, 200)
self.assertNotEqual(response.body, '')
class TestPrepFilesHandler(TestHandlerBase):
def test_get_files_not_allowed(self):
response = self.post(
'/study/prep_files/',
{'type': 'BIOM', 'prep_file': 'uploaded_file.txt', 'study_id': 1})
self.assertEqual(response.code, 405)
if __name__ == "__main__":
main()
| bsd-3-clause |
kbrebanov/ansible | lib/ansible/plugins/netconf/iosxr.py | 2 | 7442 | #
# (c) 2017 Red Hat Inc.
# (c) 2017 Kedar Kekan (kkekan@redhat.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/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import re
import sys
import collections
from io import BytesIO
from ansible.module_utils.six import StringIO
from ansible import constants as C
from ansible.module_utils.network.iosxr.iosxr import build_xml
from ansible.errors import AnsibleConnectionFailure, AnsibleError
from ansible.plugins.netconf import NetconfBase
from ansible.plugins.netconf import ensure_connected
try:
from ncclient import manager
from ncclient.operations import RPCError
from ncclient.transport.errors import SSHUnknownHostError
from ncclient.xml_ import to_ele, to_xml, new_ele
except ImportError:
raise AnsibleError("ncclient is not installed")
try:
from lxml import etree
except ImportError:
raise AnsibleError("lxml is not installed")
def transform_reply():
reply = '''<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
'''
if sys.version < '3':
return reply
else:
print("utf8")
return reply.encode('UTF-8')
# Note: Workaround for ncclient 0.5.3
def remove_namespaces(rpc_reply):
xslt = transform_reply()
parser = etree.XMLParser(remove_blank_text=True)
xslt_doc = etree.parse(BytesIO(xslt), parser)
transform = etree.XSLT(xslt_doc)
return etree.fromstring(str(transform(etree.parse(StringIO(str(rpc_reply))))))
class Netconf(NetconfBase):
@ensure_connected
def get_device_info(self):
device_info = {}
device_info['network_os'] = 'iosxr'
install_meta = collections.OrderedDict()
install_meta.update([
('boot-variables', {'xpath': 'install/boot-variables', 'tag': True}),
('boot-variable', {'xpath': 'install/boot-variables/boot-variable', 'tag': True, 'lead': True}),
('software', {'xpath': 'install/software', 'tag': True}),
('alias-devices', {'xpath': 'install/software/alias-devices', 'tag': True}),
('alias-device', {'xpath': 'install/software/alias-devices/alias-device', 'tag': True}),
('m:device-name', {'xpath': 'install/software/alias-devices/alias-device/device-name', 'value': 'disk0:'}),
])
install_filter = build_xml('install', install_meta, opcode='filter')
reply = self.get(install_filter)
ele_boot_variable = etree.fromstring(reply).find('.//boot-variable/boot-variable')
if ele_boot_variable:
device_info['network_os_image'] = re.split('[:|,]', ele_boot_variable.text)[1]
ele_package_name = etree.fromstring(reply).find('.//package-name')
if ele_package_name:
device_info['network_os_package'] = ele_package_name.text
device_info['network_os_version'] = re.split('-', ele_package_name.text)[-1]
hostname_filter = build_xml('host-names', opcode='filter')
reply = self.get(hostname_filter)
device_info['network_os_hostname'] = etree.fromstring(reply).find('.//host-name').text
return device_info
def get_capabilities(self):
result = dict()
result['rpc'] = self.get_base_rpc() + ['commit', 'discard_changes', 'validate', 'lock', 'unlock', 'get-schema']
result['network_api'] = 'netconf'
result['device_info'] = self.get_device_info()
result['server_capabilities'] = [c for c in self.m.server_capabilities]
result['client_capabilities'] = [c for c in self.m.client_capabilities]
result['session_id'] = self.m.session_id
return json.dumps(result)
@staticmethod
def guess_network_os(obj):
try:
m = manager.connect(
host=obj._play_context.remote_addr,
port=obj._play_context.port or 830,
username=obj._play_context.remote_user,
password=obj._play_context.password,
key_filename=str(obj.key_filename),
hostkey_verify=C.HOST_KEY_CHECKING,
look_for_keys=C.PARAMIKO_LOOK_FOR_KEYS,
allow_agent=obj.allow_agent,
timeout=obj._play_context.timeout
)
except SSHUnknownHostError as exc:
raise AnsibleConnectionFailure(str(exc))
guessed_os = None
for c in m.server_capabilities:
if re.search('IOS-XR', c):
guessed_os = 'iosxr'
break
m.close_session()
return guessed_os
# TODO: change .xml to .data_xml, when ncclient supports data_xml on all platforms
@ensure_connected
def get(self, *args, **kwargs):
try:
response = self.m.get(*args, **kwargs)
return to_xml(remove_namespaces(response))
except RPCError as exc:
raise Exception(to_xml(exc.xml))
@ensure_connected
def get_config(self, *args, **kwargs):
try:
response = self.m.get_config(*args, **kwargs)
return to_xml(remove_namespaces(response))
except RPCError as exc:
raise Exception(to_xml(exc.xml))
@ensure_connected
def edit_config(self, *args, **kwargs):
try:
response = self.m.edit_config(*args, **kwargs)
return to_xml(remove_namespaces(response))
except RPCError as exc:
raise Exception(to_xml(exc.xml))
@ensure_connected
def commit(self, *args, **kwargs):
try:
response = self.m.commit(*args, **kwargs)
return to_xml(remove_namespaces(response))
except RPCError as exc:
raise Exception(to_xml(exc.xml))
@ensure_connected
def validate(self, *args, **kwargs):
try:
response = self.m.validate(*args, **kwargs)
return to_xml(remove_namespaces(response))
except RPCError as exc:
raise Exception(to_xml(exc.xml))
@ensure_connected
def discard_changes(self, *args, **kwargs):
try:
response = self.m.discard_changes(*args, **kwargs)
return to_xml(remove_namespaces(response))
except RPCError as exc:
raise Exception(to_xml(exc.xml))
| gpl-3.0 |
jagg81/translate-toolkit | build/lib.linux-x86_64-2.6/translate/storage/statistics.py | 3 | 7920 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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.
#
# translate 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 translate; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""Module to provide statistics and related functionality.
@organization: Zuza Software Foundation
@copyright: 2007 Zuza Software Foundation
@license: U{GPL <http://www.fsf.org/licensing/licenses/gpl.html>}
"""
from translate import lang
from translate.lang import factory
# calling classifyunits() in the constructor is probably not ideal.
# idea: have a property for .classification that calls it if necessary
# If we add units or change translations, statistics are out of date
# Compare with modules/Status.py in pootling that uses a bitmask to
# filter units
# Add support for reading and writing Pootle style .stats files
# Consider providing quickstats
class Statistics(object):
"""Manages statistics for storage objects."""
def __init__(self, sourcelanguage='en', targetlanguage='en', checkerstyle=None):
self.sourcelanguage = sourcelanguage
self.targetlanguage = targetlanguage
self.language = lang.factory.getlanguage(self.sourcelanguage)
# self.init_checker(checkerstyle)
self.classification = {}
def init_checker(self, checkerstyle=None):
from translate.filters import checks
from translate.filters import pofilter
checkerclasses = [checkerstyle or checks.StandardChecker, pofilter.StandardPOChecker]
self.checker = pofilter.POTeeChecker(checkerclasses=checkerclasses)
def fuzzy_units(self):
"""Return a list of fuzzy units."""
if not self.classification:
self.classifyunits()
units = self.getunits()
return [units[item] for item in self.classification["fuzzy"]]
def fuzzy_unitcount(self):
"""Returns the number of fuzzy units."""
return len(self.fuzzy_units())
def translated_units(self):
"""Return a list of translated units."""
if not self.classification:
self.classifyunits()
units = self.getunits()
return [units[item] for item in self.classification["translated"]]
def translated_unitcount(self):
"""Returns the number of translated units."""
return len(self.translated_units())
def untranslated_units(self):
"""Return a list of untranslated units."""
if not self.classification:
self.classifyunits()
units = self.getunits()
return [units[item] for item in self.classification["blank"]]
def untranslated_unitcount(self):
"""Returns the number of untranslated units."""
return len(self.untranslated_units())
def getunits(self):
"""Returns a list of all units in this object."""
return []
def get_source_text(self, units):
"""Joins the unit source strings in a single string of text."""
source_text = ""
for unit in units:
source_text += unit.source + "\n"
plurals = getattr(unit.source, "strings", [])
if plurals:
source_text += "\n".join(plurals[1:])
return source_text
def wordcount(self, text):
"""Returns the number of words in the given text."""
return len(self.language.words(text))
def source_wordcount(self):
"""Returns the number of words in the source text."""
source_text = self.get_source_text(self.getunits())
return self.wordcount(source_text)
def translated_wordcount(self):
"""Returns the number of translated words in this object."""
text = self.get_source_text(self.translated_units())
return self.wordcount(text)
def untranslated_wordcount(self):
"""Returns the number of untranslated words in this object."""
text = self.get_source_text(self.untranslated_units())
return self.wordcount(text)
def classifyunit(self, unit):
"""Returns a list of the classes that the unit belongs to.
@param unit: the unit to classify
"""
classes = ["total"]
if unit.isfuzzy():
classes.append("fuzzy")
if unit.gettargetlen() == 0:
classes.append("blank")
if unit.istranslated():
classes.append("translated")
#TODO: we don't handle checking plurals at all yet, as this is tricky...
source = unit.source
target = unit.target
if isinstance(source, str) and isinstance(target, unicode):
source = source.decode(getattr(unit, "encoding", "utf-8"))
#TODO: decoding should not be done here
# checkresult = self.checker.run_filters(unit, source, target)
checkresult = {}
for checkname, checkmessage in checkresult.iteritems():
classes.append("check-" + checkname)
return classes
def classifyunits(self):
"""Makes a dictionary of which units fall into which classifications.
This method iterates over all units.
"""
self.classification = {}
self.classification["fuzzy"] = []
self.classification["blank"] = []
self.classification["translated"] = []
self.classification["has-suggestion"] = []
self.classification["total"] = []
# for checkname in self.checker.getfilters().keys():
# self.classification["check-" + checkname] = []
for item, unit in enumerate(self.unit_iter()):
classes = self.classifyunit(unit)
# if self.basefile.getsuggestions(item):
# classes.append("has-suggestion")
for classname in classes:
if classname in self.classification:
self.classification[classname].append(item)
else:
self.classification[classname] = item
self.countwords()
def countwords(self):
"""Counts the source and target words in each of the units."""
self.sourcewordcounts = []
self.targetwordcounts = []
for unit in self.unit_iter():
self.sourcewordcounts.append([self.wordcount(text) for text in getattr(unit.source, "strings", [""])])
self.targetwordcounts.append([self.wordcount(text) for text in getattr(unit.target, "strings", [""])])
def reclassifyunit(self, item):
"""Updates the classification of a unit in self.classification.
@param item: an integer that is an index in .getunits().
"""
unit = self.getunits()[item]
self.sourcewordcounts[item] = [self.wordcount(text) for text in unit.source.strings]
self.targetwordcounts[item] = [self.wordcount(text) for text in unit.target.strings]
classes = self.classifyunit(unit)
# if self.basefile.getsuggestions(item):
# classes.append("has-suggestion")
for classname, matchingitems in self.classification.items():
if (classname in classes) != (item in matchingitems):
if classname in classes:
self.classification[classname].append(item)
else:
self.classification[classname].remove(item)
self.classification[classname].sort()
# self.savestats()
| gpl-2.0 |
gcsolaroli/password-manager | backend/flask/src/clipperz/api.py | 2 | 26054 | """Clipperz API handler."""
import json
import random
import hashlib
from flask import jsonify, session, g
from datetime import datetime
from flask.ext.login import logout_user, current_user, login_user, \
login_required
from sqlalchemy.orm.exc import NoResultFound
from clipperz import app, db
from .exceptions import InvalidUsage
from .models import User, Record, RecordVersion, OneTimePassword
# ==============================================================================
# Helpers
# ==============================================================================
def randomSeed():
"""Generate a random seed."""
return hex(random.getrandbits(32*8))[2:-1]
def clipperzHash(aString):
"""Calculate a clipperz hash.
sha256(sha256(aString))
"""
firstRound = hashlib.sha256()
firstRound.update(aString)
result = hashlib.sha256()
result.update(firstRound.digest())
return result.hexdigest()
# ==============================================================================
# Method handlers
# ==============================================================================
class HandlerMixin:
"""Mixin for handling requests."""
def handle_request(self, request):
"""Default method to handle a request."""
parameters = json.loads(request.form['parameters'])
app.logger.debug('raw parameters: %s', parameters)
parameters = parameters['parameters']
if 'message' in parameters:
message = parameters['message']
app.logger.debug('message: %s', message)
app.logger.debug('parameters: %s', parameters)
try:
handler = getattr(self, message)
except AttributeError:
raise InvalidUsage(
'This message handler is not yet implemented for this method',
status_code=501)
return handler(parameters, request)
class registration(HandlerMixin):
"""Registration handler."""
def completeRegistration(self, parameters, request):
"""Complete a registration.
Create a new user.
"""
credentials = parameters['credentials']
data = parameters['user']
user = User()
user.updateCredentials(credentials)
user.update(data)
db.session.add(user)
db.session.commit()
return jsonify(lock=user.lock,
result='done')
class handshake(HandlerMixin):
"""Handshake handler.
This handles the logon process.
"""
srp_n = '115b8b692e0e045692cf280b436735c77a5a9e8a9e7ed56c965f87db5b2a2ece3'
srp_g = 2
srp_n = long(srp_n, 16)
def connect(self, parameters, request):
"""Process a connect request.
Attempt to log in by processing the parameters.
"""
result = {}
session['C'] = parameters['parameters']['C']
session['A'] = parameters['parameters']['A']
app.logger.debug('username: %s', session['C'])
user = User().query.filter_by(username=session['C']).one()
if user is not None and session['A'] != 0:
session['s'] = user.srp_s
session['v'] = user.srp_v
if 'otpid' in session:
try:
otpId = session['otpId']
one_time_password = OneTimePassword().filter_by(
id=otpId
).one()
if one_time_password.user.username != user.username:
one_time_password.reset('DISABLED')
raise Exception(("user mismatch between the current "
"session and 'one time password' "
"user"))
elif one_time_password.status != 'requested':
one_time_password.reset('DISABLED')
raise Exception(("Trying to use an 'one time password'"
" in the wrong state"))
one_time_password.reset("USED")
result['oneTimePassword'] = one_time_password.reference
db.session.add(one_time_password)
db.session.commit()
except Exception, detail:
app.logger.error("connect.optid: " + str(detail))
else:
# invalid user
invalid = ('112233445566778899aabbccddeeff00112233445566778899'
'aabbccddeeff00')
session['s'] = invalid
session['v'] = invalid
session['b'] = randomSeed()
k = '0x64398bff522814e306a97cb9bfc4364b7eed16a8c17c5208a40a2bad2933c8e'
k = long(k, 16)
app.logger.debug('k: %s (%s)', k, hex(k))
session['B'] = hex(k * long("0x%s" % session['v'], 16) +
pow(self.srp_g,
long("0x%s" % session['b'], 16),
self.srp_n)
)[2:-1]
result['s'] = session['s']
result['B'] = session['B']
app.logger.debug('Session: %s', session)
return jsonify({'result': result})
def credentialCheck(self, parameters, request):
"""Check credentials.
Handles the SRP process.
"""
country = 'US'
# hard-coded for development/personal use.
result = {
'accountInfo': {
'features': [
'UPDATE_CREDENTIALS',
'EDIT_CARD',
'CARD_DETAILS',
'ADD_CARD',
'DELETE_CARD',
'OFFLINE_COPY',
'LIST_CARDS'
],
'paramentVerificationPending': False,
'currentSubscriptionType': 'EARLY_ADOPTER',
'isExpiring': False,
'latestActiveLevel': 'EARLY_ADOPTER',
'payments': [],
'featureSet': 'FULL',
'latestActiveThreshold': -1.0,
'referenceDate': datetime.now(),
'isExpired': False,
'expirationDate': datetime(4001, 1, 1)
},
}
A = long("0x%s" % session['A'], 16)
B = long("0x%s" % session['B'], 16)
b = long("0x%s" % session['b'], 16)
v = long("0x%s" % session['v'], 16)
u = long("0x%s" % clipperzHash(str(A) + str(B)), 16)
s = long("0x%s" % session['s'], 16)
C = session['C']
n = self.srp_n
S = pow((A * pow(v, u, n)), b, n)
K = clipperzHash(str(S))
M1 = '{0}{1}{2}{3}{4}{5}{6}'.format(
'5976268709782868014401975621485889074340014836557888656093758064',
'39877501869636875571920406529',
clipperzHash(str(C)),
str(s),
str(A),
str(B),
str(K)
)
M1 = clipperzHash(M1)
if M1 == parameters['parameters']['M1']:
session['K'] = K
M2 = clipperzHash(str(A) + M1 + K)
result['M2'] = M2
result['connectionId'] = ''
result['loginInfo'] = {}
result['loginInfo']['current'] = {
'date': datetime.now(),
'ip': request.remote_addr,
'browser': request.user_agent.browser,
'operatingSystem': request.user_agent.platform,
'disconnectionType': 'STILL_CONNECTED',
'country': country
},
result['loginInfo']['latest'] = {}
result['offlineCopyNeeded'] = False
user = User().query.filter_by(username=session['C']).one()
result['lock'] = user.lock
login_user(user)
session['User'] = user
else:
result['error'] = '?'
result['s'] = session['s']
result['B'] = session['B']
return jsonify({'result': result})
def oneTimePassword(self, parameters, request):
"""Handle one time password logins."""
# "parameters": {
# "message": "oneTimePassword",
# "version": "0.2",
# "parameters": {
# "oneTimePasswordKey": "03bd882...396082c",
# "oneTimePasswordKeyChecksum": "f73f629...041031d"
# }
# }
result = {}
try:
key = parameters['parameters']['oneTimePasswordKey']
checksum = parameters['parameters']['oneTimePasswordKeyChecksum']
otp = OneTimePassword().query.filter_by(key_value=key).one()
if otp.status == 'ACTIVE':
if otp.key_checksum == checksum:
session['userId'] = otp.user.id
session['otpId'] = otp.id
result['data'] = otp.data
result['version'] = otp.version
otp.data = ''
otp.status = 'REQUESTED'
else:
otp.data = ''
otp.status = 'DISABLED'
db.session.add(otp)
db.session.commit()
except NoResultFound, details:
app.logger.debug('OTP No Results Found: ', details)
return jsonify({'result': result})
class message(HandlerMixin):
"""Handle messages once logged in."""
@login_required
def getUserDetails(self, parameters, request):
"""Get a user's details."""
app.logger.debug(parameters)
if 'srpSharedSecret' not in parameters:
raise InvalidUsage(
'Mal-formed message format.',
status_code=400)
srpSharedSecret = parameters['srpSharedSecret']
if srpSharedSecret != session['K']:
raise InvalidUsage(
'Your session is invalid, please re-authenticate',
status_code=401)
# Online results
# {"result":
# {
# "header": "{\"records\":{\"index\":{\"383036...eeefbe48\":\"0\"},\"data\":\"zrhb3/791SDdb48v3vXfPzeDrv0Jhs4rAaOKHx+jDF6pwm/qi9DGSR0JwrprOgwv3bjYJgU2xHA8cuA0bPvABHSHK6fnGwvhSlyYjskY2Cy/WbRJhcA4kw+VUsOjZPRxtM8bSJnSxViAXsghTcya6+5M3MdMJHE=\"},\"directLogins\":{\"index\":{},\"data\":\"s7KYzHwKISmjYufv9h0mpTiM\"},\"preferences\":{\"data\":\"mf8fWjpOQjlV18ukEO9FN3LP\"},\"oneTimePasswords\":{\"data\":\"8tV1yRHv30lsl3FadG9YnTOo\"},\"version\":\"0.1\"}", # NOQA
# "lock": "3D4B4501-D7A9-6E4F-A487-9428C0B6E79D",
# "version": "0.4",
# "recordsStats": {
# "383036...eeefbe48":{
# "updateDate": "Sun, 12 April 2015 17:11:01 UTC",
# "accessDate": "Sun, 12 April 2015 17:11:01 UTC"
# }
# },
# "offlineCopyNeeded":true,
# "statistics":"ByYItDeZMdZ+e/pafp14bGrR"
# }
# }
# Dev results
# {"result":
# {"header": "{\"records\":{\"index\":{\"843a95d8...5f734b\":\"1\"},\"data\":\"fKgc5Jt9JH/CibCIpcRmwyLuLIvufWchNJga7GoFcWT9K8LR+ai0BvzWBUxcPccivE9zPv2Swe5E8wPEIc+Lv0U73NobJEct7WqBcCdLxszBE1SokxPEZDUVdWVQtAiwgOS219inCFmI5CaB\"},\"directLogins\":{\"index\":{},\"data\":\"rnMQBB81ezh6JKNGXkDCyY+q\"},\"preferences\":{\"data\":\"9jzR9Goo5PGpXbAdmsXHuQGp\"},\"oneTimePasswords\":{\"data\":\"iXEUuQGskZhMyHEwU+3tRGQM\"},\"version\":\"0.1\"}", # NOQA
# "recordStats": {
# "843a95d8...5f734b": {
# "updateDate": "Sun, 12 Apr 2015 13:08:44 GMT"
# }
# },
# "statistics": "",
# "version": "0.4"}}
result = {}
user = User().query.filter_by(username=session['C']).one()
records_stats = {}
for record in user.records:
records_stats[record.reference] = {
'updateDate': record.update_date,
'accessDate': record.access_date
}
result['recordsStats'] = records_stats
result['header'] = user.header
result['statistics'] = user.statistics
result['version'] = user.version
result['offlineCopyNeeded'] = not user.offline_saved
result['lock'] = user.lock
return jsonify({'result': result})
@login_required
def saveChanges(self, parameters, request):
"""Save changes to a user's settings."""
result = {}
parameters = parameters['parameters']
if ('user' not in parameters
or 'records' not in parameters):
app.logger.debug('saveChanges parameters: %s', parameters)
raise InvalidUsage(
'Mal-formed message format.',
status_code=400)
user_data = parameters['user']
record_data = parameters['records']
user = User().query.filter_by(username=session['C']).one()
app.logger.debug('user_data: %s', user_data)
user.update(user_data)
db.session.add(user)
if 'updated' in record_data:
for entry in record_data['updated']:
reference = entry['record']['reference']
try:
record = Record().query.filter_by(reference=reference).one()
except NoResultFound:
record = Record(user=user)
record_version = RecordVersion(record=record)
record_version.update(entry)
db.session.add(record)
db.session.add(record_version)
if 'deleted' in record_data:
for reference in record_data['deleted']:
try:
record = Record().query.filter_by(reference=reference).one()
db.session.delete(record)
except NoResultFound:
pass
db.session.commit()
result['lock'] = user.lock
result['result'] = 'done'
return jsonify({'result': result})
@login_required
def getRecordDetail(self, parameters, request):
"""Get details about a record."""
# {
# "parameters": {
# "srpSharedSecret": "bf79ad3cf0c1...63462a9fb560",
# "message": "getRecordDetail",
# "parameters": {
# "reference": "e3a5856...20e080fc97f13c14c"
# }
# }
# }
app.logger.debug(parameters)
if 'srpSharedSecret' not in parameters:
raise InvalidUsage(
'Mal-formed message format.',
status_code=400)
srpSharedSecret = parameters['srpSharedSecret']
if (srpSharedSecret != session['K'] and session['User'] != g.user):
raise InvalidUsage(
'Your session is incorrect, please re-authenticate',
status_code=401)
reference = parameters['parameters']['reference']
result = {}
record = Record().query.filter_by(reference=reference).one()
app.logger.debug(record.current_record_version)
record_versions = {}
oldest_encryption_version = None
versions = RecordVersion().query.filter_by(record=record).all()
for record_version in versions:
version_entry = {}
version_entry['reference'] = record_version.reference
version_entry['data'] = record_version.data
version_entry['header'] = record_version.header
version_entry['version'] = record_version.api_version
version_entry['creationDate'] = record_version.creation_date
version_entry['updateDate'] = record_version.update_date
version_entry['accessDate'] = record_version.access_date
try:
previous_version = RecordVersion().query.filter_by(
id=record_version.previous_version_id).one()
reference = previous_version.reference
key = record_version.previous_version_key
version_entry['previousVersion'] = reference
version_entry['previousVersionKey'] = key
except NoResultFound:
pass
if (not oldest_encryption_version
or oldest_encryption_version > record_version.api_version):
oldest_encryption_version = record_version.api_version
record_versions[record_version.reference] = version_entry
result['reference'] = record.reference
result['data'] = record.data
result['version'] = record.api_version
result['creationDate'] = str(record.creation_date)
result['updateDate'] = str(record.update_date)
result['accessDate'] = str(record.access_date)
result['oldestUsedEncryptedVersion'] = oldest_encryption_version
result['versions'] = record_versions
result['currentVersion'] = record.current_record_version.reference
record.current_record_version.access()
record.access()
db.session.add(record)
db.session.add(record_version)
db.session.commit()
return jsonify({'result': result})
@login_required
def getOneTimePasswordsDetails(self, parameters, request):
"""Get details about a one time password."""
# {
# "parameters": {
# "srpSharedSecret": "bf79ad3cf0c1...63462a9fb560",
# "message": "getOneTimePasswordsDetails",
# "parameters": {}
# }
# }
if 'srpSharedSecret' not in parameters:
raise InvalidUsage(
'Mal-formed message format.',
status_code=400)
srpSharedSecret = parameters['srpSharedSecret']
if (srpSharedSecret != session['K'] and session['User'] != g.user):
raise InvalidUsage(
'Your session is incorrect, please re-authenticate',
status_code=401)
result = {}
otps = OneTimePassword().query.filter_by(user=current_user).all()
for otp in otps:
# {"e8541...af0c6b951":{"status":"ACTIVE"}}
result[otp.reference] = {'status': otp.status}
return jsonify({'result': result})
@login_required
def getLoginHistory(self, parameters, request):
"""Get login history.
Not currently fully implemented.
"""
# {
# "parameters": {
# "srpSharedSecret": "bf79ad3cf0c1...63462a9fb560",
# "message": "getOneTimePasswordsDetails",
# "parameters": {}
# }
# }
if 'srpSharedSecret' not in parameters:
raise InvalidUsage(
'Mal-formed message format.',
status_code=400)
srpSharedSecret = parameters['srpSharedSecret']
if (srpSharedSecret != session['K'] and session['User'] != g.user):
raise InvalidUsage(
'Your session is incorrect, please re-authenticate',
status_code=401)
result = {}
user = User().query.filter_by(username=session['C']).one()
if (user != g.user):
raise InvalidUsage(
'Your session is incorrect, please re-authenticate',
status_code=401)
return jsonify({'result': result})
@login_required
def addNewOneTimePassword(self, parameters, request):
"""Add a new one time password."""
# "parameters": {
# "message": "addNewOneTimePassword",
# "srpSharedSecret": "1e8e037a8...85680f931d45dfc20472cf9d1",
# "parameters": {
# "user": {
# "header": <header>
# "statistics": "WxHa6VSMmZunOjLCwAVQrkYI",
# "version": "0.4",
# "lock": "new lock"
# },
# "oneTimePassword": {
# "reference": "ffaec6f...7b123d39b8965e7e5",
# "key": "496dc431db...faec137698b16c",
# "keyChecksum": "f927c1...eb970552360a311dda",
# "data": "GcfCFsoSc5RT...MF8nstFXXHYSXF+Vyj4w=",
# "version": "0.4"
# }
# }
# }
# }
if 'srpSharedSecret' not in parameters:
raise InvalidUsage(
'Mal-formed message format.',
status_code=400)
srpSharedSecret = parameters['srpSharedSecret']
if (srpSharedSecret != session['K'] and session['User'] != g.user):
raise InvalidUsage(
'Your session is incorrect, please re-authenticate',
status_code=401)
result = {}
parameters = parameters['parameters']
user = User().query.filter_by(username=session['C']).one()
if (user != g.user):
raise InvalidUsage(
'Your session is incorrect, please re-authenticate',
status_code=401)
user_data = parameters['user']
app.logger.debug('user_data: %s', user_data)
user.update(user_data)
db.session.add(user)
one_time_password = parameters['oneTimePassword']
otp = OneTimePassword(
reference=one_time_password['reference'],
key_value=one_time_password['key'],
key_checksum=one_time_password['keyChecksum'],
data=one_time_password['data'],
version=one_time_password['version'],
user=user,
status='ACTIVE'
)
db.session.add(otp)
db.session.commit()
return jsonify({'result': result})
def echo(self, parameters, request):
"""Check the status of the session."""
result = {}
if 'srpSharedSecret' not in parameters:
raise InvalidUsage(
'Mal-formed message format.',
status_code=400)
srpSharedSecret = parameters['srpSharedSecret']
if (srpSharedSecret != session['K'] and session['User'] != g.user):
raise InvalidUsage(
'Your session is incorrect, please re-authenticate',
status_code=401)
user = User().query.filter_by(username=session['C']).one()
if (user != g.user):
raise InvalidUsage(
'Your session is incorrect, please re-authenticate',
status_code=401)
user.offline_saved = True
db.session.add(user)
db.session.commit()
return jsonify({'result': result})
@login_required
def deleteUser(self, parameters, request):
"""Delete a user and all of its records."""
result = {}
if 'srpSharedSecret' not in parameters:
raise InvalidUsage(
'Mal-formed message format.',
status_code=400)
srpSharedSecret = parameters['srpSharedSecret']
if (srpSharedSecret != session['K'] and session['User'] != g.user):
raise InvalidUsage(
'Your session is incorrect, please re-authenticate',
status_code=401)
user = User().query.filter_by(username=session['C']).one()
if (user != g.user):
raise InvalidUsage(
'Your session is incorrect, please re-authenticate',
status_code=401)
db.session.delete(user)
db.session.commit()
return jsonify({'result': result})
@login_required
def upgradeUserCredentials(self, parameters, request):
"""Upgrade a user's credentials to a new password."""
# {"parameters":{"message":"upgradeUserCredentials","srpSharedSecret":"36...d6","parameters":{"credentials":{"C":"59d02038fdb47cee5b7837a697bc8ff41cc66d8844c8fce844cdf45b0b08b1e4","s":"fe40513b99fbaca9bfe51b8d6e9b3eb42b1e01ce8b0ae32461bec0294c1030ed","v":"300b92f4a3e34034d78cd5081f8db36dbf2a4c5f7a41db6954518815a3554278","version":"0.2"},"user":{"header":"{\"records\":{\"index\":{},\"data\":\"VIIDc5vFNoIflyXF8syb8fRS\"},\"directLogins\":{\"index\":{},\"data\":\"9elg3tu2UqsJ0zbUAdQkLE69\"},\"preferences\":{\"data\":\"Sbwar35Ynd/XobuAm4K66lqj\"},\"oneTimePasswords\":{\"data\":\"tAcTsWVTwALSfxXvCChHi4FD\"},\"version\":\"0.1\"}","statistics":"","version":"0.4","lock":null}}}} # NOQA
result = {}
if 'srpSharedSecret' not in parameters:
raise InvalidUsage(
'Mal-formed message format.',
status_code=400)
srpSharedSecret = parameters['srpSharedSecret']
if (srpSharedSecret != session['K'] and session['User'] != g.user):
raise InvalidUsage(
'Your session is incorrect, please re-authenticate',
status_code=401)
user = User().query.filter_by(username=session['C']).one()
if (user != g.user):
raise InvalidUsage(
'Your session is incorrect, please re-authenticate',
status_code=401)
parameters = parameters['parameters']
user.updateCredentials(parameters['credentials'])
user.update(parameters['user'])
if 'oneTimePasswords' in parameters:
for otpRef in parameters['oneTimePasswords']:
try:
otp = OneTimePassword().query.filter_by(
reference=otpRef).one()
otp.data = parameters['oneTimePasswords'][otpRef]
db.session.add(otp)
except NoResultFound:
pass
db.session.add(user)
db.session.commit()
result['lock'] = user.lock
result['result'] = 'done'
return jsonify({'result': result})
@login_required
def getCertificatesStatus(self, parameters, request):
"""
Provides support for BTC Certificate feature.
No idea how it works.
"""
return jsonify({'result': {}})
class logout(HandlerMixin):
"""Logout handler."""
def handle_request(self, request):
"""Handle a logout request."""
result = {}
logout_user()
session.clear()
result['method'] = 'logout'
return jsonify({'result': result})
| agpl-3.0 |
sebdelsol/pyload | module/lib/jinja2/bccache.py | 284 | 9994 | # -*- coding: utf-8 -*-
"""
jinja2.bccache
~~~~~~~~~~~~~~
This module implements the bytecode cache system Jinja is optionally
using. This is useful if you have very complex template situations and
the compiliation of all those templates slow down your application too
much.
Situations where this is useful are often forking web applications that
are initialized on the first request.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD.
"""
from os import path, listdir
import marshal
import tempfile
import cPickle as pickle
import fnmatch
from cStringIO import StringIO
try:
from hashlib import sha1
except ImportError:
from sha import new as sha1
from jinja2.utils import open_if_exists
bc_version = 1
bc_magic = 'j2'.encode('ascii') + pickle.dumps(bc_version, 2)
class Bucket(object):
"""Buckets are used to store the bytecode for one template. It's created
and initialized by the bytecode cache and passed to the loading functions.
The buckets get an internal checksum from the cache assigned and use this
to automatically reject outdated cache material. Individual bytecode
cache subclasses don't have to care about cache invalidation.
"""
def __init__(self, environment, key, checksum):
self.environment = environment
self.key = key
self.checksum = checksum
self.reset()
def reset(self):
"""Resets the bucket (unloads the bytecode)."""
self.code = None
def load_bytecode(self, f):
"""Loads bytecode from a file or file like object."""
# make sure the magic header is correct
magic = f.read(len(bc_magic))
if magic != bc_magic:
self.reset()
return
# the source code of the file changed, we need to reload
checksum = pickle.load(f)
if self.checksum != checksum:
self.reset()
return
# now load the code. Because marshal is not able to load
# from arbitrary streams we have to work around that
if isinstance(f, file):
self.code = marshal.load(f)
else:
self.code = marshal.loads(f.read())
def write_bytecode(self, f):
"""Dump the bytecode into the file or file like object passed."""
if self.code is None:
raise TypeError('can\'t write empty bucket')
f.write(bc_magic)
pickle.dump(self.checksum, f, 2)
if isinstance(f, file):
marshal.dump(self.code, f)
else:
f.write(marshal.dumps(self.code))
def bytecode_from_string(self, string):
"""Load bytecode from a string."""
self.load_bytecode(StringIO(string))
def bytecode_to_string(self):
"""Return the bytecode as string."""
out = StringIO()
self.write_bytecode(out)
return out.getvalue()
class BytecodeCache(object):
"""To implement your own bytecode cache you have to subclass this class
and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of
these methods are passed a :class:`~jinja2.bccache.Bucket`.
A very basic bytecode cache that saves the bytecode on the file system::
from os import path
class MyCache(BytecodeCache):
def __init__(self, directory):
self.directory = directory
def load_bytecode(self, bucket):
filename = path.join(self.directory, bucket.key)
if path.exists(filename):
with open(filename, 'rb') as f:
bucket.load_bytecode(f)
def dump_bytecode(self, bucket):
filename = path.join(self.directory, bucket.key)
with open(filename, 'wb') as f:
bucket.write_bytecode(f)
A more advanced version of a filesystem based bytecode cache is part of
Jinja2.
"""
def load_bytecode(self, bucket):
"""Subclasses have to override this method to load bytecode into a
bucket. If they are not able to find code in the cache for the
bucket, it must not do anything.
"""
raise NotImplementedError()
def dump_bytecode(self, bucket):
"""Subclasses have to override this method to write the bytecode
from a bucket back to the cache. If it unable to do so it must not
fail silently but raise an exception.
"""
raise NotImplementedError()
def clear(self):
"""Clears the cache. This method is not used by Jinja2 but should be
implemented to allow applications to clear the bytecode cache used
by a particular environment.
"""
def get_cache_key(self, name, filename=None):
"""Returns the unique hash key for this template name."""
hash = sha1(name.encode('utf-8'))
if filename is not None:
if isinstance(filename, unicode):
filename = filename.encode('utf-8')
hash.update('|' + filename)
return hash.hexdigest()
def get_source_checksum(self, source):
"""Returns a checksum for the source."""
return sha1(source.encode('utf-8')).hexdigest()
def get_bucket(self, environment, name, filename, source):
"""Return a cache bucket for the given template. All arguments are
mandatory but filename may be `None`.
"""
key = self.get_cache_key(name, filename)
checksum = self.get_source_checksum(source)
bucket = Bucket(environment, key, checksum)
self.load_bytecode(bucket)
return bucket
def set_bucket(self, bucket):
"""Put the bucket into the cache."""
self.dump_bytecode(bucket)
class FileSystemBytecodeCache(BytecodeCache):
"""A bytecode cache that stores bytecode on the filesystem. It accepts
two arguments: The directory where the cache items are stored and a
pattern string that is used to build the filename.
If no directory is specified the system temporary items folder is used.
The pattern can be used to have multiple separate caches operate on the
same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s``
is replaced with the cache key.
>>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')
This bytecode cache supports clearing of the cache using the clear method.
"""
def __init__(self, directory=None, pattern='__jinja2_%s.cache'):
if directory is None:
directory = tempfile.gettempdir()
self.directory = directory
self.pattern = pattern
def _get_cache_filename(self, bucket):
return path.join(self.directory, self.pattern % bucket.key)
def load_bytecode(self, bucket):
f = open_if_exists(self._get_cache_filename(bucket), 'rb')
if f is not None:
try:
bucket.load_bytecode(f)
finally:
f.close()
def dump_bytecode(self, bucket):
f = open(self._get_cache_filename(bucket), 'wb')
try:
bucket.write_bytecode(f)
finally:
f.close()
def clear(self):
# imported lazily here because google app-engine doesn't support
# write access on the file system and the function does not exist
# normally.
from os import remove
files = fnmatch.filter(listdir(self.directory), self.pattern % '*')
for filename in files:
try:
remove(path.join(self.directory, filename))
except OSError:
pass
class MemcachedBytecodeCache(BytecodeCache):
"""This class implements a bytecode cache that uses a memcache cache for
storing the information. It does not enforce a specific memcache library
(tummy's memcache or cmemcache) but will accept any class that provides
the minimal interface required.
Libraries compatible with this class:
- `werkzeug <http://werkzeug.pocoo.org/>`_.contrib.cache
- `python-memcached <http://www.tummy.com/Community/software/python-memcached/>`_
- `cmemcache <http://gijsbert.org/cmemcache/>`_
(Unfortunately the django cache interface is not compatible because it
does not support storing binary data, only unicode. You can however pass
the underlying cache client to the bytecode cache which is available
as `django.core.cache.cache._client`.)
The minimal interface for the client passed to the constructor is this:
.. class:: MinimalClientInterface
.. method:: set(key, value[, timeout])
Stores the bytecode in the cache. `value` is a string and
`timeout` the timeout of the key. If timeout is not provided
a default timeout or no timeout should be assumed, if it's
provided it's an integer with the number of seconds the cache
item should exist.
.. method:: get(key)
Returns the value for the cache key. If the item does not
exist in the cache the return value must be `None`.
The other arguments to the constructor are the prefix for all keys that
is added before the actual cache key and the timeout for the bytecode in
the cache system. We recommend a high (or no) timeout.
This bytecode cache does not support clearing of used items in the cache.
The clear method is a no-operation function.
"""
def __init__(self, client, prefix='jinja2/bytecode/', timeout=None):
self.client = client
self.prefix = prefix
self.timeout = timeout
def load_bytecode(self, bucket):
code = self.client.get(self.prefix + bucket.key)
if code is not None:
bucket.bytecode_from_string(code)
def dump_bytecode(self, bucket):
args = (self.prefix + bucket.key, bucket.bytecode_to_string())
if self.timeout is not None:
args += (self.timeout,)
self.client.set(*args)
| gpl-3.0 |
was4444/chromium.src | native_client_sdk/src/build_tools/sdk_tools/config.py | 131 | 2128 | # Copyright (c) 2012 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 json
import logging
import urlparse
from sdk_update_common import Error
SOURCE_WHITELIST = [
'http://localhost/', # For testing.
'https://storage.googleapis.com/nativeclient-mirror/nacl/nacl_sdk',
]
def IsSourceValid(url):
# E1101: Instance of 'ParseResult' has no 'scheme' member
# pylint: disable=E1101
given = urlparse.urlparse(url)
for allowed_url in SOURCE_WHITELIST:
allowed = urlparse.urlparse(allowed_url)
if (given.scheme == allowed.scheme and
given.hostname == allowed.hostname and
given.path.startswith(allowed.path)):
return True
return False
class Config(dict):
def __init__(self, data=None):
dict.__init__(self)
if data:
self.update(data)
else:
self.sources = []
def LoadJson(self, json_data):
try:
self.update(json.loads(json_data))
except Exception as e:
raise Error('Error reading json config:\n%s' % str(e))
def ToJson(self):
try:
return json.dumps(self, sort_keys=False, indent=2)
except Exception as e:
raise Error('Json encoding error writing config:\n%s' % e)
def __getattr__(self, name):
if name in self:
return self[name]
else:
raise AttributeError('Config does not contain: %s' % name)
def __setattr__(self, name, value):
self[name] = value
def AddSource(self, source):
if not IsSourceValid(source):
logging.warn('Only whitelisted sources are allowed. Ignoring \"%s\".' % (
source,))
return
if source in self.sources:
logging.info('Source \"%s\" already in Config.' % (source,))
return
self.sources.append(source)
def RemoveSource(self, source):
if source not in self.sources:
logging.warn('Source \"%s\" not in Config.' % (source,))
return
self.sources.remove(source)
def RemoveAllSources(self):
if not self.sources:
logging.info('No sources to remove.')
return
self.sources = []
| bsd-3-clause |
kechie/python_koans | python3/libs/colorama/ansi.py | 527 | 1039 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
'''
This module generates ANSI character codes to printing colors to terminals.
See: http://en.wikipedia.org/wiki/ANSI_escape_code
'''
CSI = '\033['
def code_to_chars(code):
return CSI + str(code) + 'm'
class AnsiCodes(object):
def __init__(self, codes):
for name in dir(codes):
if not name.startswith('_'):
value = getattr(codes, name)
setattr(self, name, code_to_chars(value))
class AnsiFore:
BLACK = 30
RED = 31
GREEN = 32
YELLOW = 33
BLUE = 34
MAGENTA = 35
CYAN = 36
WHITE = 37
RESET = 39
class AnsiBack:
BLACK = 40
RED = 41
GREEN = 42
YELLOW = 43
BLUE = 44
MAGENTA = 45
CYAN = 46
WHITE = 47
RESET = 49
class AnsiStyle:
BRIGHT = 1
DIM = 2
NORMAL = 22
RESET_ALL = 0
Fore = AnsiCodes( AnsiFore )
Back = AnsiCodes( AnsiBack )
Style = AnsiCodes( AnsiStyle )
| mit |
shootstar/novatest | nova/api/openstack/compute/plugins/v3/extended_availability_zone.py | 15 | 3834 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Netease, LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""The Extended Availability Zone Status API extension."""
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova import availability_zones as avail_zone
ALIAS = "os-extended-availability-zone"
authorize = extensions.soft_extension_authorizer('compute',
'v3:' + ALIAS)
class ExtendedAZController(wsgi.Controller):
def _extend_server(self, context, server, instance):
key = "%s:availability_zone" % ExtendedAvailabilityZone.alias
az = avail_zone.get_instance_availability_zone(context, instance)
if not az and instance.get('availability_zone'):
# Likely hasn't reached a viable compute node yet so give back the
# desired availability_zone that *may* exist in the instance
# record itself.
az = instance['availability_zone']
server[key] = az
@wsgi.extends
def show(self, req, resp_obj, id):
context = req.environ['nova.context']
if authorize(context):
resp_obj.attach(xml=ExtendedAZTemplate())
server = resp_obj.obj['server']
db_instance = req.get_db_instance(server['id'])
self._extend_server(context, server, db_instance)
@wsgi.extends
def detail(self, req, resp_obj):
context = req.environ['nova.context']
if authorize(context):
resp_obj.attach(xml=ExtendedAZsTemplate())
servers = list(resp_obj.obj['servers'])
for server in servers:
db_instance = req.get_db_instance(server['id'])
self._extend_server(context, server, db_instance)
class ExtendedAvailabilityZone(extensions.V3APIExtensionBase):
"""Extended Server Attributes support."""
name = "ExtendedAvailabilityZone"
alias = ALIAS
namespace = ("http://docs.openstack.org/compute/ext/"
"extended_availability_zone/api/v3")
version = 1
def get_controller_extensions(self):
controller = ExtendedAZController()
extension = extensions.ControllerExtension(self, 'servers', controller)
return [extension]
def get_resources(self):
return []
def make_server(elem):
elem.set('{%s}availability_zone' % ExtendedAvailabilityZone.namespace,
'%s:availability_zone' % ExtendedAvailabilityZone.alias)
class ExtendedAZTemplate(xmlutil.TemplateBuilder):
def construct(self):
root = xmlutil.TemplateElement('server', selector='server')
make_server(root)
alias = ExtendedAvailabilityZone.alias
namespace = ExtendedAvailabilityZone.namespace
return xmlutil.SlaveTemplate(root, 1, nsmap={alias: namespace})
class ExtendedAZsTemplate(xmlutil.TemplateBuilder):
def construct(self):
root = xmlutil.TemplateElement('servers')
elem = xmlutil.SubTemplateElement(root, 'server', selector='servers')
make_server(elem)
alias = ExtendedAvailabilityZone.alias
namespace = ExtendedAvailabilityZone.namespace
return xmlutil.SlaveTemplate(root, 1, nsmap={alias: namespace})
| apache-2.0 |
Fireblend/chromium-crosswalk | third_party/mojo/src/mojo/public/tools/bindings/pylib/mojom/parse/ast.py | 34 | 13898 | # 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.
"""Node classes for the AST for a Mojo IDL file."""
# Note: For convenience of testing, you probably want to define __eq__() methods
# for all node types; it's okay to be slightly lax (e.g., not compare filename
# and lineno). You may also define __repr__() to help with analyzing test
# failures, especially for more complex types.
class NodeBase(object):
"""Base class for nodes in the AST."""
def __init__(self, filename=None, lineno=None):
self.filename = filename
self.lineno = lineno
def __eq__(self, other):
return type(self) == type(other)
# Make != the inverse of ==. (Subclasses shouldn't have to override this.)
def __ne__(self, other):
return not self == other
# TODO(vtl): Some of this is complicated enough that it should be tested.
class NodeListBase(NodeBase):
"""Represents a list of other nodes, all having the same type. (This is meant
to be subclassed, with subclasses defining _list_item_type to be the class (or
classes, in a tuple) of the members of the list.)"""
def __init__(self, item_or_items=None, **kwargs):
super(NodeListBase, self).__init__(**kwargs)
self.items = []
if item_or_items is None:
pass
elif isinstance(item_or_items, list):
for item in item_or_items:
assert isinstance(item, self._list_item_type)
self.Append(item)
else:
assert isinstance(item_or_items, self._list_item_type)
self.Append(item_or_items)
# Support iteration. For everything else, users should just access |items|
# directly. (We intentionally do NOT supply |__len__()| or |__nonzero__()|, so
# |bool(NodeListBase())| is true.)
def __iter__(self):
return self.items.__iter__()
def __eq__(self, other):
return super(NodeListBase, self).__eq__(other) and \
self.items == other.items
# Implement this so that on failure, we get slightly more sensible output.
def __repr__(self):
return self.__class__.__name__ + "([" + \
", ".join([repr(elem) for elem in self.items]) + "])"
def Insert(self, item):
"""Inserts item at the front of the list."""
assert isinstance(item, self._list_item_type)
self.items.insert(0, item)
self._UpdateFilenameAndLineno()
def Append(self, item):
"""Appends item to the end of the list."""
assert isinstance(item, self._list_item_type)
self.items.append(item)
self._UpdateFilenameAndLineno()
def _UpdateFilenameAndLineno(self):
if self.items:
self.filename = self.items[0].filename
self.lineno = self.items[0].lineno
class Definition(NodeBase):
"""Represents a definition of anything that has a global name (e.g., enums,
enum values, consts, structs, struct fields, interfaces). (This does not
include parameter definitions.) This class is meant to be subclassed."""
def __init__(self, name, **kwargs):
assert isinstance(name, str)
NodeBase.__init__(self, **kwargs)
self.name = name
################################################################################
class Attribute(NodeBase):
"""Represents an attribute."""
def __init__(self, key, value, **kwargs):
assert isinstance(key, str)
super(Attribute, self).__init__(**kwargs)
self.key = key
self.value = value
def __eq__(self, other):
return super(Attribute, self).__eq__(other) and \
self.key == other.key and \
self.value == other.value
class AttributeList(NodeListBase):
"""Represents a list attributes."""
_list_item_type = Attribute
class Const(Definition):
"""Represents a const definition."""
def __init__(self, name, typename, value, **kwargs):
# The typename is currently passed through as a string.
assert isinstance(typename, str)
# The value is either a literal (currently passed through as a string) or a
# "wrapped identifier".
assert isinstance(value, str) or isinstance(value, tuple)
super(Const, self).__init__(name, **kwargs)
self.typename = typename
self.value = value
def __eq__(self, other):
return super(Const, self).__eq__(other) and \
self.typename == other.typename and \
self.value == other.value
class Enum(Definition):
"""Represents an enum definition."""
def __init__(self, name, attribute_list, enum_value_list, **kwargs):
assert attribute_list is None or isinstance(attribute_list, AttributeList)
assert isinstance(enum_value_list, EnumValueList)
super(Enum, self).__init__(name, **kwargs)
self.attribute_list = attribute_list
self.enum_value_list = enum_value_list
def __eq__(self, other):
return super(Enum, self).__eq__(other) and \
self.attribute_list == other.attribute_list and \
self.enum_value_list == other.enum_value_list
class EnumValue(Definition):
"""Represents a definition of an enum value."""
def __init__(self, name, attribute_list, value, **kwargs):
# The optional value is either an int (which is current a string) or a
# "wrapped identifier".
assert attribute_list is None or isinstance(attribute_list, AttributeList)
assert value is None or isinstance(value, (str, tuple))
super(EnumValue, self).__init__(name, **kwargs)
self.attribute_list = attribute_list
self.value = value
def __eq__(self, other):
return super(EnumValue, self).__eq__(other) and \
self.attribute_list == other.attribute_list and \
self.value == other.value
class EnumValueList(NodeListBase):
"""Represents a list of enum value definitions (i.e., the "body" of an enum
definition)."""
_list_item_type = EnumValue
class Import(NodeBase):
"""Represents an import statement."""
def __init__(self, import_filename, **kwargs):
assert isinstance(import_filename, str)
super(Import, self).__init__(**kwargs)
self.import_filename = import_filename
def __eq__(self, other):
return super(Import, self).__eq__(other) and \
self.import_filename == other.import_filename
class ImportList(NodeListBase):
"""Represents a list (i.e., sequence) of import statements."""
_list_item_type = Import
class Interface(Definition):
"""Represents an interface definition."""
def __init__(self, name, attribute_list, body, **kwargs):
assert attribute_list is None or isinstance(attribute_list, AttributeList)
assert isinstance(body, InterfaceBody)
super(Interface, self).__init__(name, **kwargs)
self.attribute_list = attribute_list
self.body = body
def __eq__(self, other):
return super(Interface, self).__eq__(other) and \
self.attribute_list == other.attribute_list and \
self.body == other.body
class Method(Definition):
"""Represents a method definition."""
def __init__(self, name, attribute_list, ordinal, parameter_list,
response_parameter_list, **kwargs):
assert attribute_list is None or isinstance(attribute_list, AttributeList)
assert ordinal is None or isinstance(ordinal, Ordinal)
assert isinstance(parameter_list, ParameterList)
assert response_parameter_list is None or \
isinstance(response_parameter_list, ParameterList)
super(Method, self).__init__(name, **kwargs)
self.attribute_list = attribute_list
self.ordinal = ordinal
self.parameter_list = parameter_list
self.response_parameter_list = response_parameter_list
def __eq__(self, other):
return super(Method, self).__eq__(other) and \
self.attribute_list == other.attribute_list and \
self.ordinal == other.ordinal and \
self.parameter_list == other.parameter_list and \
self.response_parameter_list == other.response_parameter_list
# This needs to be declared after |Method|.
class InterfaceBody(NodeListBase):
"""Represents the body of (i.e., list of definitions inside) an interface."""
_list_item_type = (Const, Enum, Method)
class Module(NodeBase):
"""Represents a module statement."""
def __init__(self, name, attribute_list, **kwargs):
# |name| is either none or a "wrapped identifier".
assert name is None or isinstance(name, tuple)
assert attribute_list is None or isinstance(attribute_list, AttributeList)
super(Module, self).__init__(**kwargs)
self.name = name
self.attribute_list = attribute_list
def __eq__(self, other):
return super(Module, self).__eq__(other) and \
self.name == other.name and \
self.attribute_list == other.attribute_list
class Mojom(NodeBase):
"""Represents an entire .mojom file. (This is the root node.)"""
def __init__(self, module, import_list, definition_list, **kwargs):
assert module is None or isinstance(module, Module)
assert isinstance(import_list, ImportList)
assert isinstance(definition_list, list)
super(Mojom, self).__init__(**kwargs)
self.module = module
self.import_list = import_list
self.definition_list = definition_list
def __eq__(self, other):
return super(Mojom, self).__eq__(other) and \
self.module == other.module and \
self.import_list == other.import_list and \
self.definition_list == other.definition_list
def __repr__(self):
return "%s(%r, %r, %r)" % (self.__class__.__name__, self.module,
self.import_list, self.definition_list)
class Ordinal(NodeBase):
"""Represents an ordinal value labeling, e.g., a struct field."""
def __init__(self, value, **kwargs):
assert isinstance(value, int)
super(Ordinal, self).__init__(**kwargs)
self.value = value
def __eq__(self, other):
return super(Ordinal, self).__eq__(other) and \
self.value == other.value
class Parameter(NodeBase):
"""Represents a method request or response parameter."""
def __init__(self, name, attribute_list, ordinal, typename, **kwargs):
assert isinstance(name, str)
assert attribute_list is None or isinstance(attribute_list, AttributeList)
assert ordinal is None or isinstance(ordinal, Ordinal)
assert isinstance(typename, str)
super(Parameter, self).__init__(**kwargs)
self.name = name
self.attribute_list = attribute_list
self.ordinal = ordinal
self.typename = typename
def __eq__(self, other):
return super(Parameter, self).__eq__(other) and \
self.name == other.name and \
self.attribute_list == other.attribute_list and \
self.ordinal == other.ordinal and \
self.typename == other.typename
class ParameterList(NodeListBase):
"""Represents a list of (method request or response) parameters."""
_list_item_type = Parameter
class Struct(Definition):
"""Represents a struct definition."""
def __init__(self, name, attribute_list, body, **kwargs):
assert attribute_list is None or isinstance(attribute_list, AttributeList)
assert isinstance(body, StructBody)
super(Struct, self).__init__(name, **kwargs)
self.attribute_list = attribute_list
self.body = body
def __eq__(self, other):
return super(Struct, self).__eq__(other) and \
self.attribute_list == other.attribute_list and \
self.body == other.body
class StructField(Definition):
"""Represents a struct field definition."""
def __init__(self, name, attribute_list, ordinal, typename, default_value,
**kwargs):
assert isinstance(name, str)
assert attribute_list is None or isinstance(attribute_list, AttributeList)
assert ordinal is None or isinstance(ordinal, Ordinal)
assert isinstance(typename, str)
# The optional default value is currently either a value as a string or a
# "wrapped identifier".
assert default_value is None or isinstance(default_value, (str, tuple))
super(StructField, self).__init__(name, **kwargs)
self.attribute_list = attribute_list
self.ordinal = ordinal
self.typename = typename
self.default_value = default_value
def __eq__(self, other):
return super(StructField, self).__eq__(other) and \
self.attribute_list == other.attribute_list and \
self.ordinal == other.ordinal and \
self.typename == other.typename and \
self.default_value == other.default_value
# This needs to be declared after |StructField|.
class StructBody(NodeListBase):
"""Represents the body of (i.e., list of definitions inside) a struct."""
_list_item_type = (Const, Enum, StructField)
class Union(Definition):
"""Represents a union definition."""
def __init__(self, name, attribute_list, body, **kwargs):
assert attribute_list is None or isinstance(attribute_list, AttributeList)
assert isinstance(body, UnionBody)
super(Union, self).__init__(name, **kwargs)
self.attribute_list = attribute_list
self.body = body
def __eq__(self, other):
return super(Union, self).__eq__(other) and \
self.attribute_list == other.attribute_list and \
self.body == other.body
class UnionField(Definition):
def __init__(self, name, attribute_list, ordinal, typename, **kwargs):
assert isinstance(name, str)
assert attribute_list is None or isinstance(attribute_list, AttributeList)
assert ordinal is None or isinstance(ordinal, Ordinal)
assert isinstance(typename, str)
super(UnionField, self).__init__(name, **kwargs)
self.attribute_list = attribute_list
self.ordinal = ordinal
self.typename = typename
def __eq__(self, other):
return super(UnionField, self).__eq__(other) and \
self.attribute_list == other.attribute_list and \
self.ordinal == other.ordinal and \
self.typename == other.typename
class UnionBody(NodeListBase):
_list_item_type = UnionField
| bsd-3-clause |
varunarya10/boto | boto/cloudfront/__init__.py | 164 | 15176 | # Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# 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, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing 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 MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR 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 xml.sax
import time
import boto
from boto.connection import AWSAuthConnection
from boto import handler
from boto.cloudfront.distribution import Distribution, DistributionSummary, DistributionConfig
from boto.cloudfront.distribution import StreamingDistribution, StreamingDistributionSummary, StreamingDistributionConfig
from boto.cloudfront.identity import OriginAccessIdentity
from boto.cloudfront.identity import OriginAccessIdentitySummary
from boto.cloudfront.identity import OriginAccessIdentityConfig
from boto.cloudfront.invalidation import InvalidationBatch, InvalidationSummary, InvalidationListResultSet
from boto.resultset import ResultSet
from boto.cloudfront.exception import CloudFrontServerError
class CloudFrontConnection(AWSAuthConnection):
DefaultHost = 'cloudfront.amazonaws.com'
Version = '2010-11-01'
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
port=None, proxy=None, proxy_port=None,
host=DefaultHost, debug=0, security_token=None,
validate_certs=True, profile_name=None, https_connection_factory=None):
super(CloudFrontConnection, self).__init__(host,
aws_access_key_id, aws_secret_access_key,
True, port, proxy, proxy_port, debug=debug,
security_token=security_token,
validate_certs=validate_certs,
https_connection_factory=https_connection_factory,
profile_name=profile_name)
def get_etag(self, response):
response_headers = response.msg
for key in response_headers.keys():
if key.lower() == 'etag':
return response_headers[key]
return None
def _required_auth_capability(self):
return ['cloudfront']
# Generics
def _get_all_objects(self, resource, tags, result_set_class=None,
result_set_kwargs=None):
if not tags:
tags = [('DistributionSummary', DistributionSummary)]
response = self.make_request('GET', '/%s/%s' % (self.Version,
resource))
body = response.read()
boto.log.debug(body)
if response.status >= 300:
raise CloudFrontServerError(response.status, response.reason, body)
rs_class = result_set_class or ResultSet
rs_kwargs = result_set_kwargs or dict()
rs = rs_class(tags, **rs_kwargs)
h = handler.XmlHandler(rs, self)
xml.sax.parseString(body, h)
return rs
def _get_info(self, id, resource, dist_class):
uri = '/%s/%s/%s' % (self.Version, resource, id)
response = self.make_request('GET', uri)
body = response.read()
boto.log.debug(body)
if response.status >= 300:
raise CloudFrontServerError(response.status, response.reason, body)
d = dist_class(connection=self)
response_headers = response.msg
for key in response_headers.keys():
if key.lower() == 'etag':
d.etag = response_headers[key]
h = handler.XmlHandler(d, self)
xml.sax.parseString(body, h)
return d
def _get_config(self, id, resource, config_class):
uri = '/%s/%s/%s/config' % (self.Version, resource, id)
response = self.make_request('GET', uri)
body = response.read()
boto.log.debug(body)
if response.status >= 300:
raise CloudFrontServerError(response.status, response.reason, body)
d = config_class(connection=self)
d.etag = self.get_etag(response)
h = handler.XmlHandler(d, self)
xml.sax.parseString(body, h)
return d
def _set_config(self, distribution_id, etag, config):
if isinstance(config, StreamingDistributionConfig):
resource = 'streaming-distribution'
else:
resource = 'distribution'
uri = '/%s/%s/%s/config' % (self.Version, resource, distribution_id)
headers = {'If-Match': etag, 'Content-Type': 'text/xml'}
response = self.make_request('PUT', uri, headers, config.to_xml())
body = response.read()
boto.log.debug(body)
if response.status != 200:
raise CloudFrontServerError(response.status, response.reason, body)
return self.get_etag(response)
def _create_object(self, config, resource, dist_class):
response = self.make_request('POST', '/%s/%s' % (self.Version,
resource),
{'Content-Type': 'text/xml'},
data=config.to_xml())
body = response.read()
boto.log.debug(body)
if response.status == 201:
d = dist_class(connection=self)
h = handler.XmlHandler(d, self)
xml.sax.parseString(body, h)
d.etag = self.get_etag(response)
return d
else:
raise CloudFrontServerError(response.status, response.reason, body)
def _delete_object(self, id, etag, resource):
uri = '/%s/%s/%s' % (self.Version, resource, id)
response = self.make_request('DELETE', uri, {'If-Match': etag})
body = response.read()
boto.log.debug(body)
if response.status != 204:
raise CloudFrontServerError(response.status, response.reason, body)
# Distributions
def get_all_distributions(self):
tags = [('DistributionSummary', DistributionSummary)]
return self._get_all_objects('distribution', tags)
def get_distribution_info(self, distribution_id):
return self._get_info(distribution_id, 'distribution', Distribution)
def get_distribution_config(self, distribution_id):
return self._get_config(distribution_id, 'distribution',
DistributionConfig)
def set_distribution_config(self, distribution_id, etag, config):
return self._set_config(distribution_id, etag, config)
def create_distribution(self, origin, enabled, caller_reference='',
cnames=None, comment='', trusted_signers=None):
config = DistributionConfig(origin=origin, enabled=enabled,
caller_reference=caller_reference,
cnames=cnames, comment=comment,
trusted_signers=trusted_signers)
return self._create_object(config, 'distribution', Distribution)
def delete_distribution(self, distribution_id, etag):
return self._delete_object(distribution_id, etag, 'distribution')
# Streaming Distributions
def get_all_streaming_distributions(self):
tags = [('StreamingDistributionSummary', StreamingDistributionSummary)]
return self._get_all_objects('streaming-distribution', tags)
def get_streaming_distribution_info(self, distribution_id):
return self._get_info(distribution_id, 'streaming-distribution',
StreamingDistribution)
def get_streaming_distribution_config(self, distribution_id):
return self._get_config(distribution_id, 'streaming-distribution',
StreamingDistributionConfig)
def set_streaming_distribution_config(self, distribution_id, etag, config):
return self._set_config(distribution_id, etag, config)
def create_streaming_distribution(self, origin, enabled,
caller_reference='',
cnames=None, comment='',
trusted_signers=None):
config = StreamingDistributionConfig(origin=origin, enabled=enabled,
caller_reference=caller_reference,
cnames=cnames, comment=comment,
trusted_signers=trusted_signers)
return self._create_object(config, 'streaming-distribution',
StreamingDistribution)
def delete_streaming_distribution(self, distribution_id, etag):
return self._delete_object(distribution_id, etag,
'streaming-distribution')
# Origin Access Identity
def get_all_origin_access_identity(self):
tags = [('CloudFrontOriginAccessIdentitySummary',
OriginAccessIdentitySummary)]
return self._get_all_objects('origin-access-identity/cloudfront', tags)
def get_origin_access_identity_info(self, access_id):
return self._get_info(access_id, 'origin-access-identity/cloudfront',
OriginAccessIdentity)
def get_origin_access_identity_config(self, access_id):
return self._get_config(access_id,
'origin-access-identity/cloudfront',
OriginAccessIdentityConfig)
def set_origin_access_identity_config(self, access_id,
etag, config):
return self._set_config(access_id, etag, config)
def create_origin_access_identity(self, caller_reference='', comment=''):
config = OriginAccessIdentityConfig(caller_reference=caller_reference,
comment=comment)
return self._create_object(config, 'origin-access-identity/cloudfront',
OriginAccessIdentity)
def delete_origin_access_identity(self, access_id, etag):
return self._delete_object(access_id, etag,
'origin-access-identity/cloudfront')
# Object Invalidation
def create_invalidation_request(self, distribution_id, paths,
caller_reference=None):
"""Creates a new invalidation request
:see: http://goo.gl/8vECq
"""
# We allow you to pass in either an array or
# an InvalidationBatch object
if not isinstance(paths, InvalidationBatch):
paths = InvalidationBatch(paths)
paths.connection = self
uri = '/%s/distribution/%s/invalidation' % (self.Version,
distribution_id)
response = self.make_request('POST', uri,
{'Content-Type': 'text/xml'},
data=paths.to_xml())
body = response.read()
if response.status == 201:
h = handler.XmlHandler(paths, self)
xml.sax.parseString(body, h)
return paths
else:
raise CloudFrontServerError(response.status, response.reason, body)
def invalidation_request_status(self, distribution_id,
request_id, caller_reference=None):
uri = '/%s/distribution/%s/invalidation/%s' % (self.Version,
distribution_id,
request_id)
response = self.make_request('GET', uri, {'Content-Type': 'text/xml'})
body = response.read()
if response.status == 200:
paths = InvalidationBatch([])
h = handler.XmlHandler(paths, self)
xml.sax.parseString(body, h)
return paths
else:
raise CloudFrontServerError(response.status, response.reason, body)
def get_invalidation_requests(self, distribution_id, marker=None,
max_items=None):
"""
Get all invalidation requests for a given CloudFront distribution.
This returns an instance of an InvalidationListResultSet that
automatically handles all of the result paging, etc. from CF - you just
need to keep iterating until there are no more results.
:type distribution_id: string
:param distribution_id: The id of the CloudFront distribution
:type marker: string
:param marker: Use this only when paginating results and only in
follow-up request after you've received a response where
the results are truncated. Set this to the value of the
Marker element in the response you just received.
:type max_items: int
:param max_items: Use this only when paginating results and only in a
follow-up request to indicate the maximum number of
invalidation requests you want in the response. You
will need to pass the next_marker property from the
previous InvalidationListResultSet response in the
follow-up request in order to get the next 'page' of
results.
:rtype: :class:`boto.cloudfront.invalidation.InvalidationListResultSet`
:returns: An InvalidationListResultSet iterator that lists invalidation
requests for a given CloudFront distribution. Automatically
handles paging the results.
"""
uri = 'distribution/%s/invalidation' % distribution_id
params = dict()
if marker:
params['Marker'] = marker
if max_items:
params['MaxItems'] = max_items
if params:
uri += '?%s=%s' % params.popitem()
for k, v in params.items():
uri += '&%s=%s' % (k, v)
tags=[('InvalidationSummary', InvalidationSummary)]
rs_class = InvalidationListResultSet
rs_kwargs = dict(connection=self, distribution_id=distribution_id,
max_items=max_items, marker=marker)
return self._get_all_objects(uri, tags, result_set_class=rs_class,
result_set_kwargs=rs_kwargs)
| mit |
soycode/pattern | examples/04-search/06-optional.py | 21 | 1640 | import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from pattern.search import search
from pattern.en import parsetree
# Constraints ending in "?" are optional, matching one or no word.
# Pattern.search() uses a "greedy" approach:
# it will attempt to include as many optional constraints as possible.
# The following pattern scans for words whose part-of-speech tag is NN (i.e. nouns).
# A preceding adjective, adverb or determiner are picked up as well.
for s in (
"the cat", # DT NN
"the very black cat", # DT RB JJ NN
"tasty cat food", # JJ NN NN
"the funny black cat", # JJ NN
"very funny", # RB JJ => no match, since there is no noun.
"my cat is black and your cat is white"): # NN + NN
t = parsetree(s)
m = search("DT? RB? JJ? NN+", t)
print
print t
print m
if m:
for w in m[0].words:
print w, "matches", m[0].constraint(w)
# Before version 2.4, "( )" was used instead of "?".
# For example: "(JJ)" instead of "JJ?".
# The syntax was changed to resemble regular expressions, which use "?".
# The old syntax "(JJ)" still works in Pattern 2.4, but it may change later.
# Note: the above pattern could also be written as "DT|RB|JJ?+ NN+"
# to include multiple adverbs/adjectives.
# By combining "*", "?" and "+" patterns can become quite complex.
# Optional constraints are useful for very specific patterns, but slow.
# Also, depending on which parser you use (e.g. MBSP), words can be tagged differently
# and may not match in the way you expect.
# Consider using a simple, robust "NP" search pattern.
| bsd-3-clause |
bmotlaghFLT/FLT_PhantomJS | src/qt/qtwebkit/Source/WebCore/inspector/compile-front-end.py | 116 | 15388 | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import os
import os.path
import generate_protocol_externs
import shutil
import sys
import tempfile
inspector_path = "Source/WebCore/inspector"
inspector_frontend_path = inspector_path + "/front-end"
protocol_externs_path = inspector_frontend_path + "/protocol-externs.js"
generate_protocol_externs.generate_protocol_externs(protocol_externs_path, inspector_path + "/Inspector.json")
jsmodule_name_prefix = "jsmodule_"
modules = [
{
"name": "common",
"dependencies": [],
"sources": [
"Color.js",
"DOMExtension.js",
"Object.js",
"ParsedURL.js",
"Progress.js",
"Settings.js",
"UIString.js",
"UserMetrics.js",
"utilities.js",
]
},
{
"name": "sdk",
"dependencies": ["common"],
"sources": [
"ApplicationCacheModel.js",
"CompilerScriptMapping.js",
"ConsoleModel.js",
"ContentProvider.js",
"ContentProviderBasedProjectDelegate.js",
"ContentProviders.js",
"CookieParser.js",
"CSSMetadata.js",
"CSSStyleModel.js",
"BreakpointManager.js",
"Database.js",
"DOMAgent.js",
"DOMStorage.js",
"DebuggerModel.js",
"DebuggerScriptMapping.js",
"FileManager.js",
"FileMapping.js",
"FileSystemMapping.js",
"FileSystemModel.js",
"FileSystemProjectDelegate.js",
"FileUtils.js",
"HAREntry.js",
"IndexedDBModel.js",
"InspectorBackend.js",
"IsolatedFileSystemManager.js",
"IsolatedFileSystem.js",
"Linkifier.js",
"NetworkLog.js",
"NetworkUISourceCodeProvider.js",
"PresentationConsoleMessageHelper.js",
"RuntimeModel.js",
"SASSSourceMapping.js",
"Script.js",
"ScriptFormatter.js",
"ScriptSnippetModel.js",
"SimpleWorkspaceProvider.js",
"SnippetStorage.js",
"SourceMapping.js",
"StylesSourceMapping.js",
"TimelineManager.js",
"RemoteObject.js",
"Resource.js",
"DefaultScriptMapping.js",
"ResourceScriptMapping.js",
"LiveEditSupport.js",
"ResourceTreeModel.js",
"ResourceType.js",
"ResourceUtils.js",
"SourceMap.js",
"NetworkManager.js",
"NetworkRequest.js",
"UISourceCode.js",
"UserAgentSupport.js",
"Workspace.js",
"protocol-externs.js",
]
},
{
"name": "ui",
"dependencies": ["common"],
"sources": [
"Checkbox.js",
"ContextMenu.js",
"DOMSyntaxHighlighter.js",
"DataGrid.js",
"DefaultTextEditor.js",
"Dialog.js",
"DockController.js",
"Drawer.js",
"EmptyView.js",
"GoToLineDialog.js",
"HelpScreen.js",
"InspectorView.js",
"KeyboardShortcut.js",
"OverviewGrid.js",
"Panel.js",
"PanelEnablerView.js",
"Placard.js",
"Popover.js",
"ProgressIndicator.js",
"PropertiesSection.js",
"SearchController.js",
"Section.js",
"SidebarPane.js",
"SidebarTreeElement.js",
"ShortcutsScreen.js",
"ShowMoreDataGridNode.js",
"SidebarOverlay.js",
"SoftContextMenu.js",
"SourceTokenizer.js",
"Spectrum.js",
"SplitView.js",
"SidebarView.js",
"StatusBarButton.js",
"SuggestBox.js",
"TabbedPane.js",
"TextEditor.js",
"TextEditorHighlighter.js",
"TextEditorModel.js",
"TextPrompt.js",
"TextUtils.js",
"TimelineGrid.js",
"Toolbar.js",
"UIUtils.js",
"View.js",
"ViewportControl.js",
"treeoutline.js",
]
},
{
"name": "components",
"dependencies": ["sdk", "ui"],
"sources": [
"AdvancedSearchController.js",
"HandlerRegistry.js",
"ConsoleMessage.js",
"CookiesTable.js",
"DOMBreakpointsSidebarPane.js",
"DOMPresentationUtils.js",
"ElementsTreeOutline.js",
"FontView.js",
"ImageView.js",
"NativeBreakpointsSidebarPane.js",
"InspectElementModeController.js",
"ObjectPopoverHelper.js",
"ObjectPropertiesSection.js",
"SourceFrame.js",
"ResourceView.js",
]
},
{
"name": "elements",
"dependencies": ["components"],
"sources": [
"CSSNamedFlowCollectionsView.js",
"CSSNamedFlowView.js",
"ElementsPanel.js",
"ElementsPanelDescriptor.js",
"EventListenersSidebarPane.js",
"MetricsSidebarPane.js",
"PropertiesSidebarPane.js",
"StylesSidebarPane.js",
]
},
{
"name": "network",
"dependencies": ["components"],
"sources": [
"NetworkItemView.js",
"RequestCookiesView.js",
"RequestHeadersView.js",
"RequestHTMLView.js",
"RequestJSONView.js",
"RequestPreviewView.js",
"RequestResponseView.js",
"RequestTimingView.js",
"RequestView.js",
"ResourceWebSocketFrameView.js",
"NetworkPanel.js",
"NetworkPanelDescriptor.js",
]
},
{
"name": "resources",
"dependencies": ["components"],
"sources": [
"ApplicationCacheItemsView.js",
"CookieItemsView.js",
"DatabaseQueryView.js",
"DatabaseTableView.js",
"DirectoryContentView.js",
"DOMStorageItemsView.js",
"FileContentView.js",
"FileSystemView.js",
"IndexedDBViews.js",
"ResourcesPanel.js",
]
},
{
"name": "workers",
"dependencies": ["components"],
"sources": [
"WorkerManager.js",
]
},
{
"name": "scripts",
"dependencies": ["components", "workers"],
"sources": [
"BreakpointsSidebarPane.js",
"CallStackSidebarPane.js",
"FilteredItemSelectionDialog.js",
"JavaScriptSourceFrame.js",
"NavigatorOverlayController.js",
"NavigatorView.js",
"RevisionHistoryView.js",
"ScopeChainSidebarPane.js",
"ScriptsNavigator.js",
"ScriptsPanel.js",
"ScriptsPanelDescriptor.js",
"ScriptsSearchScope.js",
"SnippetJavaScriptSourceFrame.js",
"StyleSheetOutlineDialog.js",
"TabbedEditorContainer.js",
"UISourceCodeFrame.js",
"WatchExpressionsSidebarPane.js",
"WorkersSidebarPane.js",
]
},
{
"name": "console",
"dependencies": ["components"],
"sources": [
"ConsoleView.js",
"ConsolePanel.js",
]
},
{
"name": "timeline",
"dependencies": ["components"],
"sources": [
"DOMCountersGraph.js",
"MemoryStatistics.js",
"NativeMemoryGraph.js",
"TimelineModel.js",
"TimelineOverviewPane.js",
"TimelinePanel.js",
"TimelinePanelDescriptor.js",
"TimelinePresentationModel.js",
"TimelineFrameController.js"
]
},
{
"name": "audits",
"dependencies": ["components"],
"sources": [
"AuditCategories.js",
"AuditController.js",
"AuditFormatters.js",
"AuditLauncherView.js",
"AuditResultView.js",
"AuditRules.js",
"AuditsPanel.js",
]
},
{
"name": "extensions",
"dependencies": ["components"],
"sources": [
"ExtensionAPI.js",
"ExtensionAuditCategory.js",
"ExtensionPanel.js",
"ExtensionRegistryStub.js",
"ExtensionServer.js",
"ExtensionView.js",
]
},
{
"name": "settings",
"dependencies": ["components", "extensions"],
"sources": [
"SettingsScreen.js",
"OverridesView.js",
]
},
{
"name": "tests",
"dependencies": ["components"],
"sources": [
"TestController.js",
]
},
{
"name": "profiler",
"dependencies": ["components", "workers"],
"sources": [
"BottomUpProfileDataGridTree.js",
"CPUProfileView.js",
"CSSSelectorProfileView.js",
"FlameChart.js",
"HeapSnapshot.js",
"HeapSnapshotDataGrids.js",
"HeapSnapshotGridNodes.js",
"HeapSnapshotLoader.js",
"HeapSnapshotProxy.js",
"HeapSnapshotView.js",
"HeapSnapshotWorker.js",
"HeapSnapshotWorkerDispatcher.js",
"JSHeapSnapshot.js",
"NativeHeapSnapshot.js",
"ProfileDataGridTree.js",
"ProfilesPanel.js",
"ProfilesPanelDescriptor.js",
"ProfileLauncherView.js",
"TopDownProfileDataGridTree.js",
"CanvasProfileView.js",
]
},
{
"name": "host_stub",
"dependencies": ["components", "profiler", "timeline"],
"sources": [
"InspectorFrontendAPI.js",
"InspectorFrontendHostStub.js",
]
}
]
modules_by_name = {}
for module in modules:
modules_by_name[module["name"]] = module
def dump_module(name, recursively, processed_modules):
if name in processed_modules:
return ""
processed_modules[name] = True
module = modules_by_name[name]
command = ""
if recursively:
for dependency in module["dependencies"]:
command += dump_module(dependency, recursively, processed_modules)
command += " \\\n --module " + jsmodule_name_prefix + module["name"] + ":"
command += str(len(module["sources"]))
firstDependency = True
for dependency in module["dependencies"]:
if firstDependency:
command += ":"
else:
command += ","
firstDependency = False
command += jsmodule_name_prefix + dependency
for script in module["sources"]:
command += " \\\n --js " + inspector_frontend_path + "/" + script
return command
modules_dir = tempfile.mkdtemp()
compiler_command = "java -jar ~/closure/compiler.jar --summary_detail_level 3 --compilation_level SIMPLE_OPTIMIZATIONS --warning_level VERBOSE --language_in ECMASCRIPT5 --accept_const_keyword --module_output_path_prefix %s/ \\\n" % modules_dir
process_recursively = len(sys.argv) > 1
if process_recursively:
module_name = sys.argv[1]
if module_name != "all":
modules = []
for i in range(1, len(sys.argv)):
modules.append(modules_by_name[sys.argv[i]])
for module in modules:
command = compiler_command
command += " --externs " + inspector_frontend_path + "/externs.js"
command += dump_module(module["name"], True, {})
print "Compiling \"" + module["name"] + "\""
os.system(command)
else:
command = compiler_command
command += " --externs " + inspector_frontend_path + "/externs.js"
for module in modules:
command += dump_module(module["name"], False, {})
os.system(command)
if not process_recursively:
print "Compiling InjectedScriptSource.js..."
os.system("echo \"var injectedScriptValue = \" > " + inspector_path + "/" + "InjectedScriptSourceTmp.js")
os.system("cat " + inspector_path + "/" + "InjectedScriptSource.js" + " >> " + inspector_path + "/" + "InjectedScriptSourceTmp.js")
command = compiler_command
command += " --externs " + inspector_path + "/" + "InjectedScriptExterns.js" + " \\\n"
command += " --externs " + protocol_externs_path + " \\\n"
command += " --module " + jsmodule_name_prefix + "injected_script" + ":" + "1" + " \\\n"
command += " --js " + inspector_path + "/" + "InjectedScriptSourceTmp.js" + " \\\n"
command += "\n"
os.system(command)
os.system("rm " + inspector_path + "/" + "InjectedScriptSourceTmp.js")
print "Compiling InjectedScriptCanvasModuleSource.js..."
os.system("echo \"var injectedScriptCanvasModuleValue = \" > " + inspector_path + "/" + "InjectedScriptCanvasModuleSourceTmp.js")
os.system("cat " + inspector_path + "/" + "InjectedScriptCanvasModuleSource.js" + " >> " + inspector_path + "/" + "InjectedScriptCanvasModuleSourceTmp.js")
command = compiler_command
command += " --externs " + inspector_path + "/" + "InjectedScriptExterns.js" + " \\\n"
command += " --externs " + protocol_externs_path + " \\\n"
command += " --module " + jsmodule_name_prefix + "injected_script" + ":" + "1" + " \\\n"
command += " --js " + inspector_path + "/" + "InjectedScriptCanvasModuleSourceTmp.js" + " \\\n"
command += "\n"
os.system(command)
os.system("rm " + inspector_path + "/" + "InjectedScriptCanvasModuleSourceTmp.js")
shutil.rmtree(modules_dir)
#os.system("rm " + protocol_externs_path)
| bsd-3-clause |
idem2lyon/persomov | libs/html5lib/inputstream.py | 618 | 30855 | from __future__ import absolute_import, division, unicode_literals
from six import text_type
from six.moves import http_client
import codecs
import re
from .constants import EOF, spaceCharacters, asciiLetters, asciiUppercase
from .constants import encodings, ReparseException
from . import utils
from io import StringIO
try:
from io import BytesIO
except ImportError:
BytesIO = StringIO
try:
from io import BufferedIOBase
except ImportError:
class BufferedIOBase(object):
pass
# Non-unicode versions of constants for use in the pre-parser
spaceCharactersBytes = frozenset([item.encode("ascii") for item in spaceCharacters])
asciiLettersBytes = frozenset([item.encode("ascii") for item in asciiLetters])
asciiUppercaseBytes = frozenset([item.encode("ascii") for item in asciiUppercase])
spacesAngleBrackets = spaceCharactersBytes | frozenset([b">", b"<"])
invalid_unicode_re = re.compile("[\u0001-\u0008\u000B\u000E-\u001F\u007F-\u009F\uD800-\uDFFF\uFDD0-\uFDEF\uFFFE\uFFFF\U0001FFFE\U0001FFFF\U0002FFFE\U0002FFFF\U0003FFFE\U0003FFFF\U0004FFFE\U0004FFFF\U0005FFFE\U0005FFFF\U0006FFFE\U0006FFFF\U0007FFFE\U0007FFFF\U0008FFFE\U0008FFFF\U0009FFFE\U0009FFFF\U000AFFFE\U000AFFFF\U000BFFFE\U000BFFFF\U000CFFFE\U000CFFFF\U000DFFFE\U000DFFFF\U000EFFFE\U000EFFFF\U000FFFFE\U000FFFFF\U0010FFFE\U0010FFFF]")
non_bmp_invalid_codepoints = set([0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE,
0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF,
0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE,
0x8FFFF, 0x9FFFE, 0x9FFFF, 0xAFFFE, 0xAFFFF,
0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE,
0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF,
0x10FFFE, 0x10FFFF])
ascii_punctuation_re = re.compile("[\u0009-\u000D\u0020-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u007E]")
# Cache for charsUntil()
charsUntilRegEx = {}
class BufferedStream(object):
"""Buffering for streams that do not have buffering of their own
The buffer is implemented as a list of chunks on the assumption that
joining many strings will be slow since it is O(n**2)
"""
def __init__(self, stream):
self.stream = stream
self.buffer = []
self.position = [-1, 0] # chunk number, offset
def tell(self):
pos = 0
for chunk in self.buffer[:self.position[0]]:
pos += len(chunk)
pos += self.position[1]
return pos
def seek(self, pos):
assert pos <= self._bufferedBytes()
offset = pos
i = 0
while len(self.buffer[i]) < offset:
offset -= len(self.buffer[i])
i += 1
self.position = [i, offset]
def read(self, bytes):
if not self.buffer:
return self._readStream(bytes)
elif (self.position[0] == len(self.buffer) and
self.position[1] == len(self.buffer[-1])):
return self._readStream(bytes)
else:
return self._readFromBuffer(bytes)
def _bufferedBytes(self):
return sum([len(item) for item in self.buffer])
def _readStream(self, bytes):
data = self.stream.read(bytes)
self.buffer.append(data)
self.position[0] += 1
self.position[1] = len(data)
return data
def _readFromBuffer(self, bytes):
remainingBytes = bytes
rv = []
bufferIndex = self.position[0]
bufferOffset = self.position[1]
while bufferIndex < len(self.buffer) and remainingBytes != 0:
assert remainingBytes > 0
bufferedData = self.buffer[bufferIndex]
if remainingBytes <= len(bufferedData) - bufferOffset:
bytesToRead = remainingBytes
self.position = [bufferIndex, bufferOffset + bytesToRead]
else:
bytesToRead = len(bufferedData) - bufferOffset
self.position = [bufferIndex, len(bufferedData)]
bufferIndex += 1
rv.append(bufferedData[bufferOffset:bufferOffset + bytesToRead])
remainingBytes -= bytesToRead
bufferOffset = 0
if remainingBytes:
rv.append(self._readStream(remainingBytes))
return b"".join(rv)
def HTMLInputStream(source, encoding=None, parseMeta=True, chardet=True):
if isinstance(source, http_client.HTTPResponse):
# Work around Python bug #20007: read(0) closes the connection.
# http://bugs.python.org/issue20007
isUnicode = False
elif hasattr(source, "read"):
isUnicode = isinstance(source.read(0), text_type)
else:
isUnicode = isinstance(source, text_type)
if isUnicode:
if encoding is not None:
raise TypeError("Cannot explicitly set an encoding with a unicode string")
return HTMLUnicodeInputStream(source)
else:
return HTMLBinaryInputStream(source, encoding, parseMeta, chardet)
class HTMLUnicodeInputStream(object):
"""Provides a unicode stream of characters to the HTMLTokenizer.
This class takes care of character encoding and removing or replacing
incorrect byte-sequences and also provides column and line tracking.
"""
_defaultChunkSize = 10240
def __init__(self, source):
"""Initialises the HTMLInputStream.
HTMLInputStream(source, [encoding]) -> Normalized stream from source
for use by html5lib.
source can be either a file-object, local filename or a string.
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element)
parseMeta - Look for a <meta> element containing encoding information
"""
# Craziness
if len("\U0010FFFF") == 1:
self.reportCharacterErrors = self.characterErrorsUCS4
self.replaceCharactersRegexp = re.compile("[\uD800-\uDFFF]")
else:
self.reportCharacterErrors = self.characterErrorsUCS2
self.replaceCharactersRegexp = re.compile("([\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF])")
# List of where new lines occur
self.newLines = [0]
self.charEncoding = ("utf-8", "certain")
self.dataStream = self.openStream(source)
self.reset()
def reset(self):
self.chunk = ""
self.chunkSize = 0
self.chunkOffset = 0
self.errors = []
# number of (complete) lines in previous chunks
self.prevNumLines = 0
# number of columns in the last line of the previous chunk
self.prevNumCols = 0
# Deal with CR LF and surrogates split over chunk boundaries
self._bufferedCharacter = None
def openStream(self, source):
"""Produces a file object from source.
source can be either a file object, local filename or a string.
"""
# Already a file object
if hasattr(source, 'read'):
stream = source
else:
stream = StringIO(source)
return stream
def _position(self, offset):
chunk = self.chunk
nLines = chunk.count('\n', 0, offset)
positionLine = self.prevNumLines + nLines
lastLinePos = chunk.rfind('\n', 0, offset)
if lastLinePos == -1:
positionColumn = self.prevNumCols + offset
else:
positionColumn = offset - (lastLinePos + 1)
return (positionLine, positionColumn)
def position(self):
"""Returns (line, col) of the current position in the stream."""
line, col = self._position(self.chunkOffset)
return (line + 1, col)
def char(self):
""" Read one character from the stream or queue if available. Return
EOF when EOF is reached.
"""
# Read a new chunk from the input stream if necessary
if self.chunkOffset >= self.chunkSize:
if not self.readChunk():
return EOF
chunkOffset = self.chunkOffset
char = self.chunk[chunkOffset]
self.chunkOffset = chunkOffset + 1
return char
def readChunk(self, chunkSize=None):
if chunkSize is None:
chunkSize = self._defaultChunkSize
self.prevNumLines, self.prevNumCols = self._position(self.chunkSize)
self.chunk = ""
self.chunkSize = 0
self.chunkOffset = 0
data = self.dataStream.read(chunkSize)
# Deal with CR LF and surrogates broken across chunks
if self._bufferedCharacter:
data = self._bufferedCharacter + data
self._bufferedCharacter = None
elif not data:
# We have no more data, bye-bye stream
return False
if len(data) > 1:
lastv = ord(data[-1])
if lastv == 0x0D or 0xD800 <= lastv <= 0xDBFF:
self._bufferedCharacter = data[-1]
data = data[:-1]
self.reportCharacterErrors(data)
# Replace invalid characters
# Note U+0000 is dealt with in the tokenizer
data = self.replaceCharactersRegexp.sub("\ufffd", data)
data = data.replace("\r\n", "\n")
data = data.replace("\r", "\n")
self.chunk = data
self.chunkSize = len(data)
return True
def characterErrorsUCS4(self, data):
for i in range(len(invalid_unicode_re.findall(data))):
self.errors.append("invalid-codepoint")
def characterErrorsUCS2(self, data):
# Someone picked the wrong compile option
# You lose
skip = False
for match in invalid_unicode_re.finditer(data):
if skip:
continue
codepoint = ord(match.group())
pos = match.start()
# Pretty sure there should be endianness issues here
if utils.isSurrogatePair(data[pos:pos + 2]):
# We have a surrogate pair!
char_val = utils.surrogatePairToCodepoint(data[pos:pos + 2])
if char_val in non_bmp_invalid_codepoints:
self.errors.append("invalid-codepoint")
skip = True
elif (codepoint >= 0xD800 and codepoint <= 0xDFFF and
pos == len(data) - 1):
self.errors.append("invalid-codepoint")
else:
skip = False
self.errors.append("invalid-codepoint")
def charsUntil(self, characters, opposite=False):
""" Returns a string of characters from the stream up to but not
including any character in 'characters' or EOF. 'characters' must be
a container that supports the 'in' method and iteration over its
characters.
"""
# Use a cache of regexps to find the required characters
try:
chars = charsUntilRegEx[(characters, opposite)]
except KeyError:
if __debug__:
for c in characters:
assert(ord(c) < 128)
regex = "".join(["\\x%02x" % ord(c) for c in characters])
if not opposite:
regex = "^%s" % regex
chars = charsUntilRegEx[(characters, opposite)] = re.compile("[%s]+" % regex)
rv = []
while True:
# Find the longest matching prefix
m = chars.match(self.chunk, self.chunkOffset)
if m is None:
# If nothing matched, and it wasn't because we ran out of chunk,
# then stop
if self.chunkOffset != self.chunkSize:
break
else:
end = m.end()
# If not the whole chunk matched, return everything
# up to the part that didn't match
if end != self.chunkSize:
rv.append(self.chunk[self.chunkOffset:end])
self.chunkOffset = end
break
# If the whole remainder of the chunk matched,
# use it all and read the next chunk
rv.append(self.chunk[self.chunkOffset:])
if not self.readChunk():
# Reached EOF
break
r = "".join(rv)
return r
def unget(self, char):
# Only one character is allowed to be ungotten at once - it must
# be consumed again before any further call to unget
if char is not None:
if self.chunkOffset == 0:
# unget is called quite rarely, so it's a good idea to do
# more work here if it saves a bit of work in the frequently
# called char and charsUntil.
# So, just prepend the ungotten character onto the current
# chunk:
self.chunk = char + self.chunk
self.chunkSize += 1
else:
self.chunkOffset -= 1
assert self.chunk[self.chunkOffset] == char
class HTMLBinaryInputStream(HTMLUnicodeInputStream):
"""Provides a unicode stream of characters to the HTMLTokenizer.
This class takes care of character encoding and removing or replacing
incorrect byte-sequences and also provides column and line tracking.
"""
def __init__(self, source, encoding=None, parseMeta=True, chardet=True):
"""Initialises the HTMLInputStream.
HTMLInputStream(source, [encoding]) -> Normalized stream from source
for use by html5lib.
source can be either a file-object, local filename or a string.
The optional encoding parameter must be a string that indicates
the encoding. If specified, that encoding will be used,
regardless of any BOM or later declaration (such as in a meta
element)
parseMeta - Look for a <meta> element containing encoding information
"""
# Raw Stream - for unicode objects this will encode to utf-8 and set
# self.charEncoding as appropriate
self.rawStream = self.openStream(source)
HTMLUnicodeInputStream.__init__(self, self.rawStream)
self.charEncoding = (codecName(encoding), "certain")
# Encoding Information
# Number of bytes to use when looking for a meta element with
# encoding information
self.numBytesMeta = 512
# Number of bytes to use when using detecting encoding using chardet
self.numBytesChardet = 100
# Encoding to use if no other information can be found
self.defaultEncoding = "windows-1252"
# Detect encoding iff no explicit "transport level" encoding is supplied
if (self.charEncoding[0] is None):
self.charEncoding = self.detectEncoding(parseMeta, chardet)
# Call superclass
self.reset()
def reset(self):
self.dataStream = codecs.getreader(self.charEncoding[0])(self.rawStream,
'replace')
HTMLUnicodeInputStream.reset(self)
def openStream(self, source):
"""Produces a file object from source.
source can be either a file object, local filename or a string.
"""
# Already a file object
if hasattr(source, 'read'):
stream = source
else:
stream = BytesIO(source)
try:
stream.seek(stream.tell())
except:
stream = BufferedStream(stream)
return stream
def detectEncoding(self, parseMeta=True, chardet=True):
# First look for a BOM
# This will also read past the BOM if present
encoding = self.detectBOM()
confidence = "certain"
# If there is no BOM need to look for meta elements with encoding
# information
if encoding is None and parseMeta:
encoding = self.detectEncodingMeta()
confidence = "tentative"
# Guess with chardet, if avaliable
if encoding is None and chardet:
confidence = "tentative"
try:
try:
from charade.universaldetector import UniversalDetector
except ImportError:
from chardet.universaldetector import UniversalDetector
buffers = []
detector = UniversalDetector()
while not detector.done:
buffer = self.rawStream.read(self.numBytesChardet)
assert isinstance(buffer, bytes)
if not buffer:
break
buffers.append(buffer)
detector.feed(buffer)
detector.close()
encoding = detector.result['encoding']
self.rawStream.seek(0)
except ImportError:
pass
# If all else fails use the default encoding
if encoding is None:
confidence = "tentative"
encoding = self.defaultEncoding
# Substitute for equivalent encodings:
encodingSub = {"iso-8859-1": "windows-1252"}
if encoding.lower() in encodingSub:
encoding = encodingSub[encoding.lower()]
return encoding, confidence
def changeEncoding(self, newEncoding):
assert self.charEncoding[1] != "certain"
newEncoding = codecName(newEncoding)
if newEncoding in ("utf-16", "utf-16-be", "utf-16-le"):
newEncoding = "utf-8"
if newEncoding is None:
return
elif newEncoding == self.charEncoding[0]:
self.charEncoding = (self.charEncoding[0], "certain")
else:
self.rawStream.seek(0)
self.reset()
self.charEncoding = (newEncoding, "certain")
raise ReparseException("Encoding changed from %s to %s" % (self.charEncoding[0], newEncoding))
def detectBOM(self):
"""Attempts to detect at BOM at the start of the stream. If
an encoding can be determined from the BOM return the name of the
encoding otherwise return None"""
bomDict = {
codecs.BOM_UTF8: 'utf-8',
codecs.BOM_UTF16_LE: 'utf-16-le', codecs.BOM_UTF16_BE: 'utf-16-be',
codecs.BOM_UTF32_LE: 'utf-32-le', codecs.BOM_UTF32_BE: 'utf-32-be'
}
# Go to beginning of file and read in 4 bytes
string = self.rawStream.read(4)
assert isinstance(string, bytes)
# Try detecting the BOM using bytes from the string
encoding = bomDict.get(string[:3]) # UTF-8
seek = 3
if not encoding:
# Need to detect UTF-32 before UTF-16
encoding = bomDict.get(string) # UTF-32
seek = 4
if not encoding:
encoding = bomDict.get(string[:2]) # UTF-16
seek = 2
# Set the read position past the BOM if one was found, otherwise
# set it to the start of the stream
self.rawStream.seek(encoding and seek or 0)
return encoding
def detectEncodingMeta(self):
"""Report the encoding declared by the meta element
"""
buffer = self.rawStream.read(self.numBytesMeta)
assert isinstance(buffer, bytes)
parser = EncodingParser(buffer)
self.rawStream.seek(0)
encoding = parser.getEncoding()
if encoding in ("utf-16", "utf-16-be", "utf-16-le"):
encoding = "utf-8"
return encoding
class EncodingBytes(bytes):
"""String-like object with an associated position and various extra methods
If the position is ever greater than the string length then an exception is
raised"""
def __new__(self, value):
assert isinstance(value, bytes)
return bytes.__new__(self, value.lower())
def __init__(self, value):
self._position = -1
def __iter__(self):
return self
def __next__(self):
p = self._position = self._position + 1
if p >= len(self):
raise StopIteration
elif p < 0:
raise TypeError
return self[p:p + 1]
def next(self):
# Py2 compat
return self.__next__()
def previous(self):
p = self._position
if p >= len(self):
raise StopIteration
elif p < 0:
raise TypeError
self._position = p = p - 1
return self[p:p + 1]
def setPosition(self, position):
if self._position >= len(self):
raise StopIteration
self._position = position
def getPosition(self):
if self._position >= len(self):
raise StopIteration
if self._position >= 0:
return self._position
else:
return None
position = property(getPosition, setPosition)
def getCurrentByte(self):
return self[self.position:self.position + 1]
currentByte = property(getCurrentByte)
def skip(self, chars=spaceCharactersBytes):
"""Skip past a list of characters"""
p = self.position # use property for the error-checking
while p < len(self):
c = self[p:p + 1]
if c not in chars:
self._position = p
return c
p += 1
self._position = p
return None
def skipUntil(self, chars):
p = self.position
while p < len(self):
c = self[p:p + 1]
if c in chars:
self._position = p
return c
p += 1
self._position = p
return None
def matchBytes(self, bytes):
"""Look for a sequence of bytes at the start of a string. If the bytes
are found return True and advance the position to the byte after the
match. Otherwise return False and leave the position alone"""
p = self.position
data = self[p:p + len(bytes)]
rv = data.startswith(bytes)
if rv:
self.position += len(bytes)
return rv
def jumpTo(self, bytes):
"""Look for the next sequence of bytes matching a given sequence. If
a match is found advance the position to the last byte of the match"""
newPosition = self[self.position:].find(bytes)
if newPosition > -1:
# XXX: This is ugly, but I can't see a nicer way to fix this.
if self._position == -1:
self._position = 0
self._position += (newPosition + len(bytes) - 1)
return True
else:
raise StopIteration
class EncodingParser(object):
"""Mini parser for detecting character encoding from meta elements"""
def __init__(self, data):
"""string - the data to work on for encoding detection"""
self.data = EncodingBytes(data)
self.encoding = None
def getEncoding(self):
methodDispatch = (
(b"<!--", self.handleComment),
(b"<meta", self.handleMeta),
(b"</", self.handlePossibleEndTag),
(b"<!", self.handleOther),
(b"<?", self.handleOther),
(b"<", self.handlePossibleStartTag))
for byte in self.data:
keepParsing = True
for key, method in methodDispatch:
if self.data.matchBytes(key):
try:
keepParsing = method()
break
except StopIteration:
keepParsing = False
break
if not keepParsing:
break
return self.encoding
def handleComment(self):
"""Skip over comments"""
return self.data.jumpTo(b"-->")
def handleMeta(self):
if self.data.currentByte not in spaceCharactersBytes:
# if we have <meta not followed by a space so just keep going
return True
# We have a valid meta element we want to search for attributes
hasPragma = False
pendingEncoding = None
while True:
# Try to find the next attribute after the current position
attr = self.getAttribute()
if attr is None:
return True
else:
if attr[0] == b"http-equiv":
hasPragma = attr[1] == b"content-type"
if hasPragma and pendingEncoding is not None:
self.encoding = pendingEncoding
return False
elif attr[0] == b"charset":
tentativeEncoding = attr[1]
codec = codecName(tentativeEncoding)
if codec is not None:
self.encoding = codec
return False
elif attr[0] == b"content":
contentParser = ContentAttrParser(EncodingBytes(attr[1]))
tentativeEncoding = contentParser.parse()
if tentativeEncoding is not None:
codec = codecName(tentativeEncoding)
if codec is not None:
if hasPragma:
self.encoding = codec
return False
else:
pendingEncoding = codec
def handlePossibleStartTag(self):
return self.handlePossibleTag(False)
def handlePossibleEndTag(self):
next(self.data)
return self.handlePossibleTag(True)
def handlePossibleTag(self, endTag):
data = self.data
if data.currentByte not in asciiLettersBytes:
# If the next byte is not an ascii letter either ignore this
# fragment (possible start tag case) or treat it according to
# handleOther
if endTag:
data.previous()
self.handleOther()
return True
c = data.skipUntil(spacesAngleBrackets)
if c == b"<":
# return to the first step in the overall "two step" algorithm
# reprocessing the < byte
data.previous()
else:
# Read all attributes
attr = self.getAttribute()
while attr is not None:
attr = self.getAttribute()
return True
def handleOther(self):
return self.data.jumpTo(b">")
def getAttribute(self):
"""Return a name,value pair for the next attribute in the stream,
if one is found, or None"""
data = self.data
# Step 1 (skip chars)
c = data.skip(spaceCharactersBytes | frozenset([b"/"]))
assert c is None or len(c) == 1
# Step 2
if c in (b">", None):
return None
# Step 3
attrName = []
attrValue = []
# Step 4 attribute name
while True:
if c == b"=" and attrName:
break
elif c in spaceCharactersBytes:
# Step 6!
c = data.skip()
break
elif c in (b"/", b">"):
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrName.append(c.lower())
elif c is None:
return None
else:
attrName.append(c)
# Step 5
c = next(data)
# Step 7
if c != b"=":
data.previous()
return b"".join(attrName), b""
# Step 8
next(data)
# Step 9
c = data.skip()
# Step 10
if c in (b"'", b'"'):
# 10.1
quoteChar = c
while True:
# 10.2
c = next(data)
# 10.3
if c == quoteChar:
next(data)
return b"".join(attrName), b"".join(attrValue)
# 10.4
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
# 10.5
else:
attrValue.append(c)
elif c == b">":
return b"".join(attrName), b""
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c)
# Step 11
while True:
c = next(data)
if c in spacesAngleBrackets:
return b"".join(attrName), b"".join(attrValue)
elif c in asciiUppercaseBytes:
attrValue.append(c.lower())
elif c is None:
return None
else:
attrValue.append(c)
class ContentAttrParser(object):
def __init__(self, data):
assert isinstance(data, bytes)
self.data = data
def parse(self):
try:
# Check if the attr name is charset
# otherwise return
self.data.jumpTo(b"charset")
self.data.position += 1
self.data.skip()
if not self.data.currentByte == b"=":
# If there is no = sign keep looking for attrs
return None
self.data.position += 1
self.data.skip()
# Look for an encoding between matching quote marks
if self.data.currentByte in (b'"', b"'"):
quoteMark = self.data.currentByte
self.data.position += 1
oldPosition = self.data.position
if self.data.jumpTo(quoteMark):
return self.data[oldPosition:self.data.position]
else:
return None
else:
# Unquoted value
oldPosition = self.data.position
try:
self.data.skipUntil(spaceCharactersBytes)
return self.data[oldPosition:self.data.position]
except StopIteration:
# Return the whole remaining value
return self.data[oldPosition:]
except StopIteration:
return None
def codecName(encoding):
"""Return the python codec name corresponding to an encoding or None if the
string doesn't correspond to a valid encoding."""
if isinstance(encoding, bytes):
try:
encoding = encoding.decode("ascii")
except UnicodeDecodeError:
return None
if encoding:
canonicalName = ascii_punctuation_re.sub("", encoding).lower()
return encodings.get(canonicalName, None)
else:
return None
| gpl-3.0 |
rspavel/spack | var/spack/repos/builtin/packages/iwyu/package.py | 3 | 1350 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Iwyu(CMakePackage):
"""include-what-you-use: A tool for use with clang to analyze #includes in
C and C++ source files
"""
homepage = "https://include-what-you-use.org"
url = "https://include-what-you-use.org/downloads/include-what-you-use-0.13.src.tar.gz"
maintainers = ['sethrj']
version('0.14', sha256='43184397db57660c32e3298a6b1fd5ab82e808a1f5ab0591d6745f8d256200ef')
version('0.13', sha256='49294270aa64e8c04182369212cd919f3b3e0e47601b1f935f038c761c265bc9')
version('0.12', sha256='a5892fb0abccb820c394e4e245c00ef30fc94e4ae58a048b23f94047c0816025')
version('0.11', sha256='2d2877726c4aed9518cbb37673ffbc2b7da9c239bf8fe29432da35c1c0ec367a')
patch('iwyu-013-cmake.patch', when='@0.13:0.14')
depends_on('llvm+clang@10.0:10.999', when='@0.14')
depends_on('llvm+clang@9.0:9.999', when='@0.13')
depends_on('llvm+clang@8.0:8.999', when='@0.12')
depends_on('llvm+clang@7.0:7.999', when='@0.11')
@when('@0.14:')
def cmake_args(self):
return [self.define('CMAKE_CXX_STANDARD', 14),
self.define('CMAKE_CXX_EXTENSIONS', False)]
| lgpl-2.1 |
wschwa/Mr-Orange-Sick-Beard | lib/hachoir_parser/image/psd.py | 90 | 2430 | """
Photoshop parser (.psd file).
Creation date: 8 january 2006
Author: Victor Stinner
"""
from lib.hachoir_parser import Parser
from lib.hachoir_core.field import (FieldSet,
UInt16, UInt32, String, NullBytes, Enum, RawBytes)
from lib.hachoir_core.endian import BIG_ENDIAN
from lib.hachoir_parser.image.photoshop_metadata import Photoshop8BIM
class Config(FieldSet):
def __init__(self, *args):
FieldSet.__init__(self, *args)
self._size = (4 + self["size"].value) * 8
def createFields(self):
yield UInt32(self, "size")
while not self.eof:
yield Photoshop8BIM(self, "item[]")
class PsdFile(Parser):
endian = BIG_ENDIAN
PARSER_TAGS = {
"id": "psd",
"category": "image",
"file_ext": ("psd",),
"mime": (u"image/psd", u"image/photoshop", u"image/x-photoshop"),
"min_size": 4*8,
"magic": (("8BPS\0\1",0),),
"description": "Photoshop (PSD) picture",
}
COLOR_MODE = {
0: u"Bitmap",
1: u"Grayscale",
2: u"Indexed",
3: u"RGB color",
4: u"CMYK color",
7: u"Multichannel",
8: u"Duotone",
9: u"Lab Color",
}
COMPRESSION_NAME = {
0: "Raw data",
1: "RLE",
}
def validate(self):
if self.stream.readBytes(0, 4) != "8BPS":
return "Invalid signature"
return True
def createFields(self):
yield String(self, "signature", 4, "PSD signature (8BPS)", charset="ASCII")
yield UInt16(self, "version")
yield NullBytes(self, "reserved[]", 6)
yield UInt16(self, "nb_channels")
yield UInt32(self, "width")
yield UInt32(self, "height")
yield UInt16(self, "depth")
yield Enum(UInt16(self, "color_mode"), self.COLOR_MODE)
# Mode data
yield UInt32(self, "mode_data_size")
size = self["mode_data_size"].value
if size:
yield RawBytes(self, "mode_data", size)
# Resources
yield Config(self, "config")
# Reserved
yield UInt32(self, "reserved_data_size")
size = self["reserved_data_size"].value
if size:
yield RawBytes(self, "reserved_data", size)
yield Enum(UInt16(self, "compression"), self.COMPRESSION_NAME)
size = (self.size - self.current_size) // 8
if size:
yield RawBytes(self, "end", size)
| gpl-3.0 |
marctc/django | tests/urlpatterns_reverse/namespace_urls.py | 160 | 2533 | from django.conf.urls import include, url
from . import views
from .tests import URLObject
testobj1 = URLObject('testapp', 'test-ns1')
testobj2 = URLObject('testapp', 'test-ns2')
default_testobj = URLObject('testapp', 'testapp')
otherobj1 = URLObject('nodefault', 'other-ns1')
otherobj2 = URLObject('nodefault', 'other-ns2')
newappobj1 = URLObject('newapp')
urlpatterns = [
url(r'^normal/$', views.empty_view, name='normal-view'),
url(r'^normal/(?P<arg1>[0-9]+)/(?P<arg2>[0-9]+)/$', views.empty_view, name='normal-view'),
url(r'^resolver_match/$', views.pass_resolver_match_view, name='test-resolver-match'),
url(r'^\+\\\$\*/$', views.empty_view, name='special-view'),
url(r'^mixed_args/([0-9]+)/(?P<arg2>[0-9]+)/$', views.empty_view, name='mixed-args'),
url(r'^no_kwargs/([0-9]+)/([0-9]+)/$', views.empty_view, name='no-kwargs'),
url(r'^view_class/(?P<arg1>[0-9]+)/(?P<arg2>[0-9]+)/$', views.view_class_instance, name='view-class'),
url(r'^unnamed/normal/(?P<arg1>[0-9]+)/(?P<arg2>[0-9]+)/$', views.empty_view),
url(r'^unnamed/view_class/(?P<arg1>[0-9]+)/(?P<arg2>[0-9]+)/$', views.view_class_instance),
url(r'^test1/', include(testobj1.urls)),
url(r'^test2/', include(testobj2.urls)),
url(r'^default/', include(default_testobj.urls)),
url(r'^other1/', include(otherobj1.urls)),
url(r'^other[246]/', include(otherobj2.urls)),
url(r'^newapp1/', include(newappobj1.app_urls, 'new-ns1')),
url(r'^new-default/', include(newappobj1.app_urls)),
url(r'^app-included[135]/', include('urlpatterns_reverse.included_app_urls', namespace='app-ns1')),
url(r'^app-included2/', include('urlpatterns_reverse.included_app_urls', namespace='app-ns2')),
url(r'^ns-included[135]/', include('urlpatterns_reverse.included_namespace_urls', namespace='inc-ns1')),
url(r'^ns-included2/', include('urlpatterns_reverse.included_namespace_urls', namespace='inc-ns2')),
url(r'^app-included/', include('urlpatterns_reverse.included_namespace_urls', 'inc-app', 'inc-app')),
url(r'^included/', include('urlpatterns_reverse.included_namespace_urls')),
url(r'^inc(?P<outer>[0-9]+)/', include('urlpatterns_reverse.included_urls', namespace='inc-ns5')),
url(r'^included/([0-9]+)/', include('urlpatterns_reverse.included_namespace_urls')),
url(r'^ns-outer/(?P<outer>[0-9]+)/', include('urlpatterns_reverse.included_namespace_urls', namespace='inc-outer')),
url(r'^\+\\\$\*/', include('urlpatterns_reverse.namespace_urls', namespace='special')),
]
| bsd-3-clause |
andrew-rogers/DSP | GPS/file_reader.py | 1 | 1929 | #!/usr/bin/env python3
"""Global Position System (GPS) file reader for captured IQ signal
The Standard Positioning Service (SPS) spec can be found at
https://www.navcen.uscg.gov/pubs/gps/sigspec/gpssps1.pdf
"""
# Copyright (c) 2021 Andrew Rogers
#
# 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 numpy as np
class FileReader :
# Data file available from https://sourceforge.net/projects/gnss-sdr/files/data/
def __init__( self, filename='2013_04_04_GNSS_SIGNAL_at_CTTC_SPAIN/2013_04_04_GNSS_SIGNAL_at_CTTC_SPAIN.dat') :
self.offset = 0
self.filename = filename
def read( self, num_samples ) :
data=np.fromfile(self.filename, dtype=np.int16, offset=self.offset, count=num_samples*2)
self.offset = self.offset + 2 * len(data)
# Convert values to complex
data=data.reshape(num_samples,2)
data=np.matmul(data,[1,1j])
return data
| gpl-3.0 |
renzon/pypratico | setup.py | 1 | 4933 | import codecs
import os
import sys
from distutils.util import convert_path
from fnmatch import fnmatchcase
from setuptools import setup, find_packages
def read(fname):
return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read()
# Provided as an attribute, so you can append to these instead
# of replicating them:
standard_exclude = ["*.py", "*.pyc", "*$py.class", "*~", ".*", "*.bak"]
standard_exclude_directories = [
".*", "CVS", "_darcs", "./build", "./dist", "EGG-INFO", "*.egg-info"
]
# (c) 2005 Ian Bicking and contributors; written for Paste (
# http://pythonpaste.org)
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license.php
# Note: you may want to copy this into your setup.py file verbatim, as
# you can't import this from another package, when you don't know if
# that package is installed yet.
def find_package_data(
where=".",
package="",
exclude=standard_exclude,
exclude_directories=standard_exclude_directories,
only_in_packages=True,
show_ignored=False):
"""
Return a dictionary suitable for use in ``package_data``
in a distutils ``setup.py`` file.
The dictionary looks like::
{"package": [files]}
Where ``files`` is a list of all the files in that package that
don"t match anything in ``exclude``.
If ``only_in_packages`` is true, then top-level directories that
are not packages won"t be included (but directories under packages
will).
Directories matching any pattern in ``exclude_directories`` will
be ignored; by default directories with leading ``.``, ``CVS``,
and ``_darcs`` will be ignored.
If ``show_ignored`` is true, then all the files that aren"t
included in package data are shown on stderr (for debugging
purposes).
Note patterns use wildcards, or can be exact paths (including
leading ``./``), and all searching is case-insensitive.
"""
out = {}
stack = [(convert_path(where), "", package, only_in_packages)]
while stack:
where, prefix, package, only_in_packages = stack.pop(0)
for name in os.listdir(where):
fn = os.path.join(where, name)
if os.path.isdir(fn):
bad_name = False
for pattern in exclude_directories:
if (fnmatchcase(name, pattern)
or fn.lower() == pattern.lower()):
bad_name = True
if show_ignored:
print >> sys.stderr, (
"Directory %s ignored by pattern %s"
% (fn, pattern))
break
if bad_name:
continue
if (os.path.isfile(os.path.join(fn, "__init__.py"))
and not prefix):
if not package:
new_package = name
else:
new_package = package + "." + name
stack.append((fn, "", new_package, False))
else:
stack.append(
(fn, prefix + name + "/", package, only_in_packages))
elif package or not only_in_packages:
# is a file
bad_name = False
for pattern in exclude:
if (fnmatchcase(name, pattern)
or fn.lower() == pattern.lower()):
bad_name = True
if show_ignored:
print >> sys.stderr, (
"File %s ignored by pattern %s"
% (fn, pattern))
break
if bad_name:
continue
out.setdefault(package, []).append(prefix + name)
return out
PACKAGE = "pypraticot6"
DESCRIPTION = "Pacote de exemplo do curso pypratico"
NAME = PACKAGE
AUTHOR = "Renzo Nuccitelli"
AUTHOR_EMAIL = "renzo.n@gmail.com"
URL = "https://github.com/renzon/pypratico"
VERSION = __import__(PACKAGE).__version__
setup(
name=NAME,
version=VERSION,
description=DESCRIPTION,
long_description=URL,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
license="AGPL",
url=URL,
packages=find_packages(exclude=["tests.*", "tests"]),
package_data=find_package_data(PACKAGE, only_in_packages=False),
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU Affero General Public License v3 or "
"later (AGPLv3+)",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Framework :: Paste",
],
zip_safe=False,
install_requires=[
'requests>=2.13.0'
]
)
| agpl-3.0 |
mambocab/python-driver | tests/unit/cython/test_bytesio.py | 3 | 1259 | # Copyright DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from tests.unit.cython.utils import cyimport, cythontest
bytesio_testhelper = cyimport('tests.unit.cython.bytesio_testhelper')
try:
import unittest2 as unittest
except ImportError:
import unittest # noqa
class BytesIOTest(unittest.TestCase):
"""Test Cython BytesIO proxy"""
@cythontest
def test_reading(self):
bytesio_testhelper.test_read1(self.assertEqual, self.assertRaises)
bytesio_testhelper.test_read2(self.assertEqual, self.assertRaises)
bytesio_testhelper.test_read3(self.assertEqual, self.assertRaises)
@cythontest
def test_reading_error(self):
bytesio_testhelper.test_read_eof(self.assertEqual, self.assertRaises)
| apache-2.0 |
syndbg/ubuntu-make | tests/medium/test_web.py | 1 | 1847 | # -*- coding: utf-8 -*-
# Copyright (C) 2015 Canonical
#
# Authors:
# Didier Roche
#
# 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; version 3.
#
# 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
"""Tests for web category"""
from . import ContainerTests
import os
from ..large import test_web
class FirefoxDevContainer(ContainerTests, test_web.FirefoxDevTests):
"""This will test the Firefox dev integration inside a container"""
TIMEOUT_START = 20
TIMEOUT_STOP = 10
def setUp(self):
self.hostname = "download.mozilla.org"
self.port = "443"
super().setUp()
# override with container path
self.installed_path = os.path.expanduser("/home/{}/tools/web/firefox-dev".format(self.DOCKER_USER))
class VisualStudioCodeContainer(ContainerTests, test_web.VisualStudioCodeTest):
"""This will test the Visual Studio Code integration inside a container"""
TIMEOUT_START = 20
TIMEOUT_STOP = 10
def setUp(self):
self.hostname = "code.visualstudio.com"
self.port = "443"
self.apt_repo_override_path = os.path.join(self.APT_FAKE_REPO_PATH, 'vscode')
super().setUp()
# override with container path
self.installed_path = os.path.expanduser("/home/{}/tools/web/visual-studio-code".format(self.DOCKER_USER))
| gpl-3.0 |
gurneyalex/odoo | addons/auth_signup/models/res_partner.py | 4 | 7625 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import random
import werkzeug.urls
from collections import defaultdict
from datetime import datetime, timedelta
from odoo import api, exceptions, fields, models, _
class SignupError(Exception):
pass
def random_token():
# the token has an entropy of about 120 bits (6 bits/char * 20 chars)
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
return ''.join(random.SystemRandom().choice(chars) for _ in range(20))
def now(**kwargs):
return datetime.now() + timedelta(**kwargs)
class ResPartner(models.Model):
_inherit = 'res.partner'
signup_token = fields.Char(copy=False, groups="base.group_erp_manager")
signup_type = fields.Char(string='Signup Token Type', copy=False, groups="base.group_erp_manager")
signup_expiration = fields.Datetime(copy=False, groups="base.group_erp_manager")
signup_valid = fields.Boolean(compute='_compute_signup_valid', string='Signup Token is Valid')
signup_url = fields.Char(compute='_compute_signup_url', string='Signup URL')
@api.depends('signup_token', 'signup_expiration')
def _compute_signup_valid(self):
dt = now()
for partner, partner_sudo in zip(self, self.sudo()):
partner.signup_valid = bool(partner_sudo.signup_token) and \
(not partner_sudo.signup_expiration or dt <= partner_sudo.signup_expiration)
def _compute_signup_url(self):
""" proxy for function field towards actual implementation """
result = self.sudo()._get_signup_url_for_action()
for partner in self:
if any(u.has_group('base.group_user') for u in partner.user_ids if u != self.env.user):
self.env['res.users'].check_access_rights('write')
partner.signup_url = result.get(partner.id, False)
def _get_signup_url_for_action(self, url=None, action=None, view_type=None, menu_id=None, res_id=None, model=None):
""" generate a signup url for the given partner ids and action, possibly overriding
the url state components (menu_id, id, view_type) """
res = dict.fromkeys(self.ids, False)
for partner in self:
base_url = partner.get_base_url()
# when required, make sure the partner has a valid signup token
if self.env.context.get('signup_valid') and not partner.user_ids:
partner.sudo().signup_prepare()
route = 'login'
# the parameters to encode for the query
query = dict(db=self.env.cr.dbname)
signup_type = self.env.context.get('signup_force_type_in_url', partner.sudo().signup_type or '')
if signup_type:
route = 'reset_password' if signup_type == 'reset' else signup_type
if partner.sudo().signup_token and signup_type:
query['token'] = partner.sudo().signup_token
elif partner.user_ids:
query['login'] = partner.user_ids[0].login
else:
continue # no signup token, no user, thus no signup url!
if url:
query['redirect'] = url
else:
fragment = dict()
base = '/web#'
if action == '/mail/view':
base = '/mail/view?'
elif action:
fragment['action'] = action
if view_type:
fragment['view_type'] = view_type
if menu_id:
fragment['menu_id'] = menu_id
if model:
fragment['model'] = model
if res_id:
fragment['res_id'] = res_id
if fragment:
query['redirect'] = base + werkzeug.urls.url_encode(fragment)
url = "/web/%s?%s" % (route, werkzeug.urls.url_encode(query))
if not self.env.context.get('relative_url'):
url = werkzeug.urls.url_join(base_url, url)
res[partner.id] = url
return res
def action_signup_prepare(self):
return self.signup_prepare()
def signup_get_auth_param(self):
""" Get a signup token related to the partner if signup is enabled.
If the partner already has a user, get the login parameter.
"""
if not self.env.user.has_group('base.group_user') and not self.env.is_admin():
raise exceptions.AccessDenied()
res = defaultdict(dict)
allow_signup = self.env['res.users']._get_signup_invitation_scope() == 'b2c'
for partner in self:
partner = partner.sudo()
if allow_signup and not partner.user_ids:
partner.signup_prepare()
res[partner.id]['auth_signup_token'] = partner.signup_token
elif partner.user_ids:
res[partner.id]['auth_login'] = partner.user_ids[0].login
return res
def signup_cancel(self):
return self.write({'signup_token': False, 'signup_type': False, 'signup_expiration': False})
def signup_prepare(self, signup_type="signup", expiration=False):
""" generate a new token for the partners with the given validity, if necessary
:param expiration: the expiration datetime of the token (string, optional)
"""
for partner in self:
if expiration or not partner.signup_valid:
token = random_token()
while self._signup_retrieve_partner(token):
token = random_token()
partner.write({'signup_token': token, 'signup_type': signup_type, 'signup_expiration': expiration})
return True
@api.model
def _signup_retrieve_partner(self, token, check_validity=False, raise_exception=False):
""" find the partner corresponding to a token, and possibly check its validity
:param token: the token to resolve
:param check_validity: if True, also check validity
:param raise_exception: if True, raise exception instead of returning False
:return: partner (browse record) or False (if raise_exception is False)
"""
partner = self.search([('signup_token', '=', token)], limit=1)
if not partner:
if raise_exception:
raise exceptions.UserError(_("Signup token '%s' is not valid") % token)
return False
if check_validity and not partner.signup_valid:
if raise_exception:
raise exceptions.UserError(_("Signup token '%s' is no longer valid") % token)
return False
return partner
@api.model
def signup_retrieve_info(self, token):
""" retrieve the user info about the token
:return: a dictionary with the user information:
- 'db': the name of the database
- 'token': the token, if token is valid
- 'name': the name of the partner, if token is valid
- 'login': the user login, if the user already exists
- 'email': the partner email, if the user does not exist
"""
partner = self._signup_retrieve_partner(token, raise_exception=True)
res = {'db': self.env.cr.dbname}
if partner.signup_valid:
res['token'] = token
res['name'] = partner.name
if partner.user_ids:
res['login'] = partner.user_ids[0].login
else:
res['email'] = res['login'] = partner.email or ''
return res
| agpl-3.0 |
MOSAIC-UA/802.11ah-ns3 | ns-3/src/visualizer/visualizer/svgitem.py | 189 | 5073 | import gobject
import rsvg
#import cairo
import goocanvas
import os.path
class SvgItem(goocanvas.ItemSimple):
# setup our custom properties
__gproperties__ = {
'x': (float, # property type
'X', # property nick name
'The x coordinate of a SVG image', # property description
-10e6, # property minimum value
10e6, # property maximum value
0, # property default value
gobject.PARAM_READWRITE), # property flags
'y': (float,
'Y',
'The y coordinate of a SVG image',
-10e6,
10e6,
0,
gobject.PARAM_READWRITE),
'width': (float,
'Width',
'The width of the SVG Image',
0,
10e6,
0,
gobject.PARAM_READWRITE),
'height': (float,
'Height',
'The width of the SVG Image',
0,
10e6,
0,
gobject.PARAM_READWRITE),
}
def __init__(self, x, y, rsvg_handle, **kwargs):
super(SvgItem, self).__init__(**kwargs)
assert isinstance(rsvg_handle, rsvg.Handle)
self.x = x
self.y = y
self.sx = 1.0
self.sy = 1.0
self.handle = rsvg_handle
self.width = self.handle.props.width
self.height = self.handle.props.height
self.custom_width = None
self.custom_height = None
def do_set_property(self, pspec, value):
if pspec.name == 'x':
self.x = value
# make sure we update the display
self.changed(True)
elif pspec.name == 'y':
self.y = value
# make sure we update the display
self.changed(True)
elif pspec.name == 'width':
self.custom_width = value
self._size_changed()
# make sure we update the display
self.changed(True)
elif pspec.name == 'height':
self.custom_height = value
self._size_changed()
# make sure we update the display
self.changed(True)
else:
raise AttributeError, 'unknown property %s' % pspec.name
def _size_changed(self):
if self.custom_width is None and self.custom_height is None:
self.width = self.handle.props.width
self.height = self.handle.props.height
self.sx = 1.0
self.sy = 1.0
elif self.custom_width is not None and self.custom_height is None:
self.width = self.custom_width
self.sx = self.custom_width / self.handle.props.width
self.sy = self.sx
self.height = self.handle.props.height*self.sy
elif self.custom_width is None and self.custom_height is not None:
self.height = self.custom_height
self.sy = self.custom_height / self.handle.props.height
self.sx = self.sy
self.width = self.handle.props.width*self.sx
else:
self.width = self.custom_width
self.height = self.custom_height
self.sx = self.custom_width / self.handle.props.width
self.sy = self.custom_height / self.handle.props.height
def do_get_property(self, pspec):
if pspec.name == 'x':
return self.x
elif pspec.name == 'y':
return self.y
elif pspec.name == 'width':
self.width = self.handle.props.width
self.height = self.handle.props.height
return self.width
elif pspec.name == 'height':
return self.height
else:
raise AttributeError, 'unknown property %s' % pspec.name
def do_simple_paint(self, cr, bounds):
cr.translate(self.x, self.y)
cr.scale(self.sx, self.sy)
self.handle.render_cairo(cr)
def do_simple_update(self, cr):
self.bounds_x1 = float(self.x)
self.bounds_y1 = float(self.y)
self.bounds_x2 = float(self.x + self.width)
self.bounds_y2 = float(self.y + self.height)
def do_simple_is_item_at(self, x, y, cr, is_pointer_event):
if ((x < self.x) or (x > self.x + self.width)) or ((y < self.y) or (y > self.y + self.height)):
return False
else:
return True
_rsvg_cache = dict()
def rsvg_handle_factory(base_file_name):
try:
return _rsvg_cache[base_file_name]
except KeyError:
full_path = os.path.join(os.path.dirname(__file__), 'resource', base_file_name)
rsvg_handle = rsvg.Handle(full_path)
_rsvg_cache[base_file_name] = rsvg_handle
return rsvg_handle
| gpl-2.0 |
importre/kotlin-unwrap | utils/gen.py | 1 | 1264 | #! /usr/bin/env python3
import os
impl = '''
class Unwrap(private var valid: Boolean) {
infix fun <R> nah(f: () -> R) {
if (!valid) f()
}
}
'''
template = '''
inline fun <{0}, R> unwrap(
{1},
block: ({0}) -> R): Unwrap {{
val valid = null !in arrayOf{4}({2})
if (valid) block({3})
return Unwrap(valid = valid)
}}
'''
if __name__ == '__main__':
max = 5
root = os.path.join('src', 'main', 'kotlin', '')
path = [i[0] for i in os.walk(root)
if i[0].endswith(os.sep + 'unwrap')][0].replace(root, '')
codes = ['package {}\n'.format(path.replace(os.sep, '.')), impl]
for iter in range(1, max + 1):
types = ', '.join(['T{}'.format(i + 1) for i in range(iter)])
params = ', '.join(['t{0}: T{0}?'.format(i + 1) for i in range(iter)])
args1 = ', '.join(['t{}'.format(i + 1) for i in range(iter)])
args2 = ', '.join(['t{}!!'.format(i + 1) for i in range(iter)])
arrayType = '<Any?>' if (iter == 1) else ''
code = template.format(types, params, args1, args2, arrayType)
codes.append(code)
filename = os.path.join(root, path, 'Unwrap.kt')
with open(filename, 'w') as fout:
fout.write(''.join(codes).strip() + '\n')
pass
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.