repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
thaim/ansible
refs/heads/fix-broken-link
test/units/modules/net_tools/nios/test_nios_fixed_address.py
52
# This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.module_utils.net_tools.nios import api from ansible.modules.net_tools.nios import nios_fixed_address from units.compat.mock import patch, MagicMock, Mock from .test_nios_module import TestNiosModule, load_fixture class TestNiosFixedAddressModule(TestNiosModule): module = nios_fixed_address def setUp(self): super(TestNiosFixedAddressModule, self).setUp() self.module = MagicMock(name='ansible.modules.net_tools.nios.nios_fixed_address.WapiModule') self.module.check_mode = False self.module.params = {'provider': None} self.mock_wapi = patch('ansible.modules.net_tools.nios.nios_fixed_address.WapiModule') self.exec_command = self.mock_wapi.start() self.mock_wapi_run = patch('ansible.modules.net_tools.nios.nios_fixed_address.WapiModule.run') self.mock_wapi_run.start() self.load_config = self.mock_wapi_run.start() def tearDown(self): super(TestNiosFixedAddressModule, self).tearDown() self.mock_wapi.stop() self.mock_wapi_run.stop() def load_fixtures(self, commands=None): self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None) self.load_config.return_value = dict(diff=None, session='session') def _get_wapi(self, test_object): wapi = api.WapiModule(self.module) wapi.get_object = Mock(name='get_object', return_value=test_object) wapi.create_object = Mock(name='create_object') wapi.update_object = Mock(name='update_object') wapi.delete_object = Mock(name='delete_object') return wapi def test_nios_fixed_address_ipv4_create(self): self.module.params = {'provider': None, 'state': 'present', 'name': 'test_fa', 'ipaddr': '192.168.10.1', 'mac': '08:6d:41:e8:fd:e8', 'network': '192.168.10.0/24', 'network_view': 'default', 'comment': None, 'extattrs': None} test_object = None test_spec = { "name": {}, "ipaddr": {"ib_req": True}, "mac": {"ib_req": True}, "network": {"ib_req": True}, "network_view": {}, "comment": {}, "extattrs": {} } wapi = self._get_wapi(test_object) res = wapi.run('testobject', test_spec) self.assertTrue(res['changed']) wapi.create_object.assert_called_once_with('testobject', {'name': 'test_fa', 'ipaddr': '192.168.10.1', 'mac': '08:6d:41:e8:fd:e8', 'network': '192.168.10.0/24', 'network_view': 'default'}) def test_nios_fixed_address_ipv4_dhcp_update(self): self.module.params = {'provider': None, 'state': 'present', 'name': 'test_fa', 'ipaddr': '192.168.10.1', 'mac': '08:6d:41:e8:fd:e8', 'network': '192.168.10.0/24', 'network_view': 'default', 'comment': 'updated comment', 'extattrs': None} test_object = [ { "comment": "test comment", "name": "test_fa", "_ref": "network/ZG5zLm5ldHdvcmtfdmlldyQw:default/true", "ipaddr": "192.168.10.1", "mac": "08:6d:41:e8:fd:e8", "network": "192.168.10.0/24", "network_view": "default", "extattrs": {'options': {'name': 'test', 'value': 'ansible.com'}} } ] test_spec = { "name": {}, "ipaddr": {"ib_req": True}, "mac": {"ib_req": True}, "network": {"ib_req": True}, "network_view": {}, "comment": {}, "extattrs": {} } wapi = self._get_wapi(test_object) res = wapi.run('testobject', test_spec) self.assertTrue(res['changed']) def test_nios_fixed_address_ipv4_remove(self): self.module.params = {'provider': None, 'state': 'absent', 'name': 'test_fa', 'ipaddr': '192.168.10.1', 'mac': '08:6d:41:e8:fd:e8', 'network': '192.168.10.0/24', 'network_view': 'default', 'comment': None, 'extattrs': None} ref = "fixedaddress/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false" test_object = [{ "comment": "test comment", "name": "test_fa", "_ref": ref, "ipaddr": "192.168.10.1", "mac": "08:6d:41:e8:fd:e8", "network": "192.168.10.0/24", "network_view": "default", "extattrs": {'Site': {'value': 'test'}} }] test_spec = { "name": {}, "ipaddr": {"ib_req": True}, "mac": {"ib_req": True}, "network": {"ib_req": True}, "network_view": {}, "comment": {}, "extattrs": {} } wapi = self._get_wapi(test_object) res = wapi.run('testobject', test_spec) self.assertTrue(res['changed']) wapi.delete_object.assert_called_once_with(ref) def test_nios_fixed_address_ipv6_create(self): self.module.params = {'provider': None, 'state': 'present', 'name': 'test_fa', 'ipaddr': 'fe80::1/10', 'mac': '08:6d:41:e8:fd:e8', 'network': 'fe80::/64', 'network_view': 'default', 'comment': None, 'extattrs': None} test_object = None test_spec = { "name": {}, "ipaddr": {"ib_req": True}, "mac": {"ib_req": True}, "network": {"ib_req": True}, "network_view": {}, "comment": {}, "extattrs": {} } wapi = self._get_wapi(test_object) print("WAPI: ", wapi) res = wapi.run('testobject', test_spec) self.assertTrue(res['changed']) wapi.create_object.assert_called_once_with('testobject', {'name': 'test_fa', 'ipaddr': 'fe80::1/10', 'mac': '08:6d:41:e8:fd:e8', 'network': 'fe80::/64', 'network_view': 'default'}) def test_nios_fixed_address_ipv6_remove(self): self.module.params = {'provider': None, 'state': 'absent', 'name': 'test_fa', 'ipaddr': 'fe80::1/10', 'mac': '08:6d:41:e8:fd:e8', 'network': 'fe80::/64', 'network_view': 'default', 'comment': None, 'extattrs': None} ref = "ipv6fixedaddress/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false" test_object = [{ "comment": "test comment", "name": "test_fa", "_ref": ref, "ipaddr": "fe80::1/10", "mac": "08:6d:41:e8:fd:e8", "network": "fe80::/64", "network_view": "default", "extattrs": {'Site': {'value': 'test'}} }] test_spec = { "name": {}, "ipaddr": {"ib_req": True}, "mac": {"ib_req": True}, "network": {"ib_req": True}, "network_view": {}, "comment": {}, "extattrs": {} } wapi = self._get_wapi(test_object) res = wapi.run('testobject', test_spec) self.assertTrue(res['changed']) wapi.delete_object.assert_called_once_with(ref)
bwbeach/ansible
refs/heads/devel
lib/ansible/cli/pull.py
81
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ######################################################## import datetime import os import platform import random import shutil import socket import sys import time from ansible.errors import AnsibleOptionsError from ansible.cli import CLI from ansible.plugins import module_loader from ansible.utils.cmd_functions import run_cmd ######################################################## class PullCLI(CLI): ''' code behind ansible ad-hoc cli''' DEFAULT_REPO_TYPE = 'git' DEFAULT_PLAYBOOK = 'local.yml' PLAYBOOK_ERRORS = { 1: 'File does not exist', 2: 'File is not readable' } SUPPORTED_REPO_MODULES = ['git'] def parse(self): ''' create an options parser for bin/ansible ''' self.parser = CLI.base_parser( usage='%prog <host-pattern> [options]', connect_opts=True, vault_opts=True, runtask_opts=True, subset_opts=True, inventory_opts=True, module_opts=True, ) # options unique to pull self.parser.add_option('--purge', default=False, action='store_true', help='purge checkout after playbook run') self.parser.add_option('-o', '--only-if-changed', dest='ifchanged', default=False, action='store_true', help='only run the playbook if the repository has been updated') self.parser.add_option('-s', '--sleep', dest='sleep', default=None, help='sleep for random interval (between 0 and n number of seconds) before starting. This is a useful way to disperse git requests') self.parser.add_option('-f', '--force', dest='force', default=False, action='store_true', help='run the playbook even if the repository could not be updated') self.parser.add_option('-d', '--directory', dest='dest', default=None, help='directory to checkout repository to') self.parser.add_option('-U', '--url', dest='url', default=None, help='URL of the playbook repository') self.parser.add_option('-C', '--checkout', dest='checkout', help='branch/tag/commit to checkout. ' 'Defaults to behavior of repository module.') self.parser.add_option('--accept-host-key', default=False, dest='accept_host_key', action='store_true', help='adds the hostkey for the repo url if not already added') self.parser.add_option('-m', '--module-name', dest='module_name', default=self.DEFAULT_REPO_TYPE, help='Repository module name, which ansible will use to check out the repo. Default is %s.' % self.DEFAULT_REPO_TYPE) self.parser.add_option('--verify-commit', dest='verify', default=False, action='store_true', help='verify GPG signature of checked out commit, if it fails abort running the playbook.' ' This needs the corresponding VCS module to support such an operation') self.options, self.args = self.parser.parse_args() if self.options.sleep: try: secs = random.randint(0,int(self.options.sleep)) self.options.sleep = secs except ValueError: raise AnsibleOptionsError("%s is not a number." % self.options.sleep) if not self.options.url: raise AnsibleOptionsError("URL for repository not specified, use -h for help") if len(self.args) != 1: raise AnsibleOptionsError("Missing target hosts") if self.options.module_name not in self.SUPPORTED_REPO_MODULES: raise AnsibleOptionsError("Unsuported repo module %s, choices are %s" % (self.options.module_name, ','.join(self.SUPPORTED_REPO_MODULES))) self.display.verbosity = self.options.verbosity self.validate_conflicts(vault_opts=True) def run(self): ''' use Runner lib to do SSH things ''' super(PullCLI, self).run() # log command line now = datetime.datetime.now() self.display.display(now.strftime("Starting Ansible Pull at %F %T")) self.display.display(' '.join(sys.argv)) # Build Checkout command # Now construct the ansible command node = platform.node() host = socket.getfqdn() limit_opts = 'localhost:%s:127.0.0.1' % ':'.join(set([host, node, host.split('.')[0], node.split('.')[0]])) base_opts = '-c local "%s"' % limit_opts if self.options.verbosity > 0: base_opts += ' -%s' % ''.join([ "v" for x in range(0, self.options.verbosity) ]) # Attempt to use the inventory passed in as an argument # It might not yet have been downloaded so use localhost if note if not self.options.inventory or not os.path.exists(self.options.inventory): inv_opts = 'localhost,' else: inv_opts = self.options.inventory #TODO: enable more repo modules hg/svn? if self.options.module_name == 'git': repo_opts = "name=%s dest=%s" % (self.options.url, self.options.dest) if self.options.checkout: repo_opts += ' version=%s' % self.options.checkout if self.options.accept_host_key: repo_opts += ' accept_hostkey=yes' if self.options.private_key_file: repo_opts += ' key_file=%s' % self.options.private_key_file if self.options.verify: repo_opts += ' verify_commit=yes' path = module_loader.find_plugin(self.options.module_name) if path is None: raise AnsibleOptionsError(("module '%s' not found.\n" % self.options.module_name)) bin_path = os.path.dirname(os.path.abspath(sys.argv[0])) cmd = '%s/ansible -i "%s" %s -m %s -a "%s"' % ( bin_path, inv_opts, base_opts, self.options.module_name, repo_opts ) for ev in self.options.extra_vars: cmd += ' -e "%s"' % ev # Nap? if self.options.sleep: self.display.display("Sleeping for %d seconds..." % self.options.sleep) time.sleep(self.options.sleep); # RUN the Checkout command rc, out, err = run_cmd(cmd, live=True) if rc != 0: if self.options.force: self.display.warning("Unable to update repository. Continuing with (forced) run of playbook.") else: return rc elif self.options.ifchanged and '"changed": true' not in out: self.display.display("Repository has not changed, quitting.") return 0 playbook = self.select_playbook(path) if playbook is None: raise AnsibleOptionsError("Could not find a playbook to run.") # Build playbook command cmd = '%s/ansible-playbook %s %s' % (bin_path, base_opts, playbook) if self.options.vault_password_file: cmd += " --vault-password-file=%s" % self.options.vault_password_file if self.options.inventory: cmd += ' -i "%s"' % self.options.inventory for ev in self.options.extra_vars: cmd += ' -e "%s"' % ev if self.options.ask_sudo_pass: cmd += ' -K' if self.options.tags: cmd += ' -t "%s"' % self.options.tags if self.options.limit: cmd += ' -l "%s"' % self.options.limit os.chdir(self.options.dest) # RUN THE PLAYBOOK COMMAND rc, out, err = run_cmd(cmd, live=True) if self.options.purge: os.chdir('/') try: shutil.rmtree(self.options.dest) except Exception as e: self.display.error("Failed to remove %s: %s" % (self.options.dest, str(e))) return rc def try_playbook(self, path): if not os.path.exists(path): return 1 if not os.access(path, os.R_OK): return 2 return 0 def select_playbook(self, path): playbook = None if len(self.args) > 0 and self.args[0] is not None: playbook = os.path.join(path, self.args[0]) rc = self.try_playbook(playbook) if rc != 0: self.display.warning("%s: %s" % (playbook, self.PLAYBOOK_ERRORS[rc])) return None return playbook else: fqdn = socket.getfqdn() hostpb = os.path.join(path, fqdn + '.yml') shorthostpb = os.path.join(path, fqdn.split('.')[0] + '.yml') localpb = os.path.join(path, self.DEFAULT_PLAYBOOK) errors = [] for pb in [hostpb, shorthostpb, localpb]: rc = self.try_playbook(pb) if rc == 0: playbook = pb break else: errors.append("%s: %s" % (pb, self.PLAYBOOK_ERRORS[rc])) if playbook is None: self.display.warning("\n".join(errors)) return playbook
minhthuanit/selenium
refs/heads/master
py/selenium/webdriver/firefox/firefox_profile.py
60
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC 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 __future__ import with_statement import base64 import copy import json import os import re import shutil import sys import tempfile import zipfile try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO from xml.dom import minidom from selenium.webdriver.common.proxy import ProxyType from selenium.common.exceptions import WebDriverException WEBDRIVER_EXT = "webdriver.xpi" WEBDRIVER_PREFERENCES = "webdriver_prefs.json" EXTENSION_NAME = "fxdriver@googlecode.com" class AddonFormatError(Exception): """Exception for not well-formed add-on manifest files""" class FirefoxProfile(object): ANONYMOUS_PROFILE_NAME = "WEBDRIVER_ANONYMOUS_PROFILE" DEFAULT_PREFERENCES = None def __init__(self, profile_directory=None): """ Initialises a new instance of a Firefox Profile :args: - profile_directory: Directory of profile that you want to use. This defaults to None and will create a new directory when object is created. """ if not FirefoxProfile.DEFAULT_PREFERENCES: with open(os.path.join(os.path.dirname(__file__), WEBDRIVER_PREFERENCES)) as default_prefs: FirefoxProfile.DEFAULT_PREFERENCES = json.load(default_prefs) self.default_preferences = copy.deepcopy( FirefoxProfile.DEFAULT_PREFERENCES['mutable']) self.native_events_enabled = True self.profile_dir = profile_directory self.tempfolder = None if self.profile_dir is None: self.profile_dir = self._create_tempfolder() else: self.tempfolder = tempfile.mkdtemp() newprof = os.path.join(self.tempfolder, "webdriver-py-profilecopy") shutil.copytree(self.profile_dir, newprof, ignore=shutil.ignore_patterns("parent.lock", "lock", ".parentlock")) self.profile_dir = newprof self._read_existing_userjs(os.path.join(self.profile_dir, "user.js")) self.extensionsDir = os.path.join(self.profile_dir, "extensions") self.userPrefs = os.path.join(self.profile_dir, "user.js") #Public Methods def set_preference(self, key, value): """ sets the preference that we want in the profile. """ self.default_preferences[key] = value def add_extension(self, extension=WEBDRIVER_EXT): self._install_extension(extension) def update_preferences(self): for key, value in FirefoxProfile.DEFAULT_PREFERENCES['frozen'].items(): self.default_preferences[key] = value self._write_user_prefs(self.default_preferences) #Properties @property def path(self): """ Gets the profile directory that is currently being used """ return self.profile_dir @property def port(self): """ Gets the port that WebDriver is working on """ return self._port @port.setter def port(self, port): """ Sets the port that WebDriver will be running on """ if not isinstance(port, int): raise WebDriverException("Port needs to be an integer") try: port = int(port) if port < 1 or port > 65535: raise WebDriverException("Port number must be in the range 1..65535") except (ValueError, TypeError) as e: raise WebDriverException("Port needs to be an integer") self._port = port self.set_preference("webdriver_firefox_port", self._port) @property def accept_untrusted_certs(self): return self.default_preferences["webdriver_accept_untrusted_certs"] @accept_untrusted_certs.setter def accept_untrusted_certs(self, value): if value not in [True, False]: raise WebDriverException("Please pass in a Boolean to this call") self.set_preference("webdriver_accept_untrusted_certs", value) @property def assume_untrusted_cert_issuer(self): return self.default_preferences["webdriver_assume_untrusted_issuer"] @assume_untrusted_cert_issuer.setter def assume_untrusted_cert_issuer(self, value): if value not in [True, False]: raise WebDriverException("Please pass in a Boolean to this call") self.set_preference("webdriver_assume_untrusted_issuer", value) @property def native_events_enabled(self): return self.default_preferences['webdriver_enable_native_events'] @native_events_enabled.setter def native_events_enabled(self, value): if value not in [True, False]: raise WebDriverException("Please pass in a Boolean to this call") self.set_preference("webdriver_enable_native_events", value) @property def encoded(self): """ A zipped, base64 encoded string of profile directory for use with remote WebDriver JSON wire protocol """ fp = BytesIO() zipped = zipfile.ZipFile(fp, 'w', zipfile.ZIP_DEFLATED) path_root = len(self.path) + 1 # account for trailing slash for base, dirs, files in os.walk(self.path): for fyle in files: filename = os.path.join(base, fyle) zipped.write(filename, filename[path_root:]) zipped.close() return base64.b64encode(fp.getvalue()).decode('UTF-8') def set_proxy(self, proxy): import warnings warnings.warn( "This method has been deprecated. Please pass in the proxy object to the Driver Object", DeprecationWarning) if proxy is None: raise ValueError("proxy can not be None") if proxy.proxy_type is ProxyType.UNSPECIFIED: return self.set_preference("network.proxy.type", proxy.proxy_type['ff_value']) if proxy.proxy_type is ProxyType.MANUAL: self.set_preference("network.proxy.no_proxies_on", proxy.no_proxy) self._set_manual_proxy_preference("ftp", proxy.ftp_proxy) self._set_manual_proxy_preference("http", proxy.http_proxy) self._set_manual_proxy_preference("ssl", proxy.ssl_proxy) self._set_manual_proxy_preference("socks", proxy.socks_proxy) elif proxy.proxy_type is ProxyType.PAC: self.set_preference("network.proxy.autoconfig_url", proxy.proxy_autoconfig_url) def _set_manual_proxy_preference(self, key, setting): if setting is None or setting is '': return host_details = setting.split(":") self.set_preference("network.proxy.%s" % key, host_details[0]) if len(host_details) > 1: self.set_preference("network.proxy.%s_port" % key, int(host_details[1])) def _create_tempfolder(self): """ Creates a temp folder to store User.js and the extension """ return tempfile.mkdtemp() def _write_user_prefs(self, user_prefs): """ writes the current user prefs dictionary to disk """ with open(self.userPrefs, "w") as f: for key, value in user_prefs.items(): f.write('user_pref("%s", %s);\n' % (key, json.dumps(value))) def _read_existing_userjs(self, userjs): import warnings PREF_RE = re.compile(r'user_pref\("(.*)",\s(.*)\)') try: with open(userjs) as f: for usr in f: matches = re.search(PREF_RE, usr) try: self.default_preferences[matches.group(1)] = json.loads(matches.group(2)) except: warnings.warn("(skipping) failed to json.loads existing preference: " + matches.group(1) + matches.group(2)) except: # The profile given hasn't had any changes made, i.e no users.js pass def _install_extension(self, addon, unpack=True): """ Installs addon from a filepath, url or directory of addons in the profile. - path: url, path to .xpi, or directory of addons - unpack: whether to unpack unless specified otherwise in the install.rdf """ if addon == WEBDRIVER_EXT: addon = os.path.join(os.path.dirname(__file__), WEBDRIVER_EXT) tmpdir = None xpifile = None if addon.endswith('.xpi'): tmpdir = tempfile.mkdtemp(suffix='.' + os.path.split(addon)[-1]) compressed_file = zipfile.ZipFile(addon, 'r') for name in compressed_file.namelist(): if name.endswith('/'): if not os.path.isdir(os.path.join(tmpdir, name)): os.makedirs(os.path.join(tmpdir, name)) else: if not os.path.isdir(os.path.dirname(os.path.join(tmpdir, name))): os.makedirs(os.path.dirname(os.path.join(tmpdir, name))) data = compressed_file.read(name) with open(os.path.join(tmpdir, name), 'wb') as f: f.write(data) xpifile = addon addon = tmpdir # determine the addon id addon_details = self._addon_details(addon) addon_id = addon_details.get('id') assert addon_id, 'The addon id could not be found: %s' % addon # copy the addon to the profile extensions_path = os.path.join(self.profile_dir, 'extensions') addon_path = os.path.join(extensions_path, addon_id) if not unpack and not addon_details['unpack'] and xpifile: if not os.path.exists(extensions_path): os.makedirs(extensions_path) shutil.copy(xpifile, addon_path + '.xpi') else: if not os.path.exists(addon_path): shutil.copytree(addon, addon_path, symlinks=True) # remove the temporary directory, if any if tmpdir: shutil.rmtree(tmpdir) def _addon_details(self, addon_path): """ Returns a dictionary of details about the addon. :param addon_path: path to the add-on directory or XPI Returns:: {'id': u'rainbow@colors.org', # id of the addon 'version': u'1.4', # version of the addon 'name': u'Rainbow', # name of the addon 'unpack': False } # whether to unpack the addon """ details = { 'id': None, 'unpack': False, 'name': None, 'version': None } def get_namespace_id(doc, url): attributes = doc.documentElement.attributes namespace = "" for i in range(attributes.length): if attributes.item(i).value == url: if ":" in attributes.item(i).name: # If the namespace is not the default one remove 'xlmns:' namespace = attributes.item(i).name.split(':')[1] + ":" break return namespace def get_text(element): """Retrieve the text value of a given node""" rc = [] for node in element.childNodes: if node.nodeType == node.TEXT_NODE: rc.append(node.data) return ''.join(rc).strip() if not os.path.exists(addon_path): raise IOError('Add-on path does not exist: %s' % addon_path) try: if zipfile.is_zipfile(addon_path): # Bug 944361 - We cannot use 'with' together with zipFile because # it will cause an exception thrown in Python 2.6. try: compressed_file = zipfile.ZipFile(addon_path, 'r') manifest = compressed_file.read('install.rdf') finally: compressed_file.close() elif os.path.isdir(addon_path): with open(os.path.join(addon_path, 'install.rdf'), 'r') as f: manifest = f.read() else: raise IOError('Add-on path is neither an XPI nor a directory: %s' % addon_path) except (IOError, KeyError) as e: raise AddonFormatError(str(e), sys.exc_info()[2]) try: doc = minidom.parseString(manifest) # Get the namespaces abbreviations em = get_namespace_id(doc, 'http://www.mozilla.org/2004/em-rdf#') rdf = get_namespace_id(doc, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#') description = doc.getElementsByTagName(rdf + 'Description').item(0) if description is None: description = doc.getElementsByTagName('Description').item(0) for node in description.childNodes: # Remove the namespace prefix from the tag for comparison entry = node.nodeName.replace(em, "") if entry in details.keys(): details.update({entry: get_text(node)}) if details.get('id') is None: for i in range(description.attributes.length): attribute = description.attributes.item(i) if attribute.name == em + 'id': details.update({'id': attribute.value}) except Exception as e: raise AddonFormatError(str(e), sys.exc_info()[2]) # turn unpack into a true/false value if isinstance(details['unpack'], str): details['unpack'] = details['unpack'].lower() == 'true' # If no ID is set, the add-on is invalid if details.get('id') is None: raise AddonFormatError('Add-on id could not be found.') return details
gregdek/ansible
refs/heads/devel
test/units/modules/packaging/os/test_rhn_register.py
31
import contextlib import json import os from units.compat.mock import mock_open from ansible.module_utils import basic from ansible.module_utils._text import to_native import ansible.module_utils.six from ansible.module_utils.six.moves import xmlrpc_client from ansible.modules.packaging.os import rhn_register import pytest SYSTEMID = """<?xml version="1.0"?> <params> <param> <value><struct> <member> <name>system_id</name> <value><string>ID-123456789</string></value> </member> </struct></value> </param> </params> """ def skipWhenAllModulesMissing(modules): """Skip the decorated test unless one of modules is available.""" for module in modules: try: __import__(module) return False except ImportError: continue return True orig_import = __import__ @pytest.fixture def import_libxml(mocker): def mock_import(name, *args, **kwargs): if name in ['libxml2', 'libxml']: raise ImportError() else: return orig_import(name, *args, **kwargs) if ansible.module_utils.six.PY3: mocker.patch('builtins.__import__', side_effect=mock_import) else: mocker.patch('__builtin__.__import__', side_effect=mock_import) @pytest.fixture def patch_rhn(mocker): load_config_return = { 'serverURL': 'https://xmlrpc.rhn.redhat.com/XMLRPC', 'systemIdPath': '/etc/sysconfig/rhn/systemid' } mocker.patch.object(rhn_register.Rhn, 'load_config', return_value=load_config_return) mocker.patch.object(rhn_register, 'HAS_UP2DATE_CLIENT', mocker.PropertyMock(return_value=True)) @pytest.mark.skipif(skipWhenAllModulesMissing(['libxml2', 'libxml']), reason='none are available: libxml2, libxml') def test_systemid_with_requirements(capfd, mocker, patch_rhn): """Check 'msg' and 'changed' results""" mocker.patch.object(rhn_register.Rhn, 'enable') mock_isfile = mocker.patch('os.path.isfile', return_value=True) mocker.patch('ansible.modules.packaging.os.rhn_register.open', mock_open(read_data=SYSTEMID), create=True) rhn = rhn_register.Rhn() assert '123456789' == to_native(rhn.systemid) @pytest.mark.parametrize('patch_ansible_module', [{}], indirect=['patch_ansible_module']) @pytest.mark.usefixtures('patch_ansible_module') def test_systemid_requirements_missing(capfd, mocker, patch_rhn, import_libxml): """Check that missing dependencies are detected""" mocker.patch('os.path.isfile', return_value=True) mocker.patch('ansible.modules.packaging.os.rhn_register.open', mock_open(read_data=SYSTEMID), create=True) with pytest.raises(SystemExit): rhn_register.main() out, err = capfd.readouterr() results = json.loads(out) assert results['failed'] assert 'Missing arguments' in results['msg'] @pytest.mark.parametrize('patch_ansible_module', [{}], indirect=['patch_ansible_module']) @pytest.mark.usefixtures('patch_ansible_module') def test_without_required_parameters(capfd, patch_rhn): """Failure must occurs when all parameters are missing""" with pytest.raises(SystemExit): rhn_register.main() out, err = capfd.readouterr() results = json.loads(out) assert results['failed'] assert 'Missing arguments' in results['msg'] TESTED_MODULE = rhn_register.__name__ TEST_CASES = [ [ # Registering an unregistered host with channels { 'channels': 'rhel-x86_64-server-6', 'username': 'user', 'password': 'pass', }, { 'calls': [ ('auth.login', ['X' * 43]), ('channel.software.listSystemChannels', [[{'channel_name': 'Red Hat Enterprise Linux Server (v. 6 for 64-bit x86_64)', 'channel_label': 'rhel-x86_64-server-6'}]]), ('channel.software.setSystemChannels', [1]), ('auth.logout', [1]), ], 'is_registered': False, 'is_registered.call_count': 1, 'enable.call_count': 1, 'systemid.call_count': 2, 'changed': True, 'msg': "System successfully registered to 'rhn.redhat.com'.", 'run_command.call_count': 1, 'run_command.call_args': '/usr/sbin/rhnreg_ks', 'request_called': True, 'unlink.call_count': 0, } ], [ # Registering an unregistered host without channels { 'activationkey': 'key', 'username': 'user', 'password': 'pass', }, { 'calls': [ ], 'is_registered': False, 'is_registered.call_count': 1, 'enable.call_count': 1, 'systemid.call_count': 0, 'changed': True, 'msg': "System successfully registered to 'rhn.redhat.com'.", 'run_command.call_count': 1, 'run_command.call_args': '/usr/sbin/rhnreg_ks', 'request_called': False, 'unlink.call_count': 0, } ], [ # Register an host already registered, check that result is unchanged { 'activationkey': 'key', 'username': 'user', 'password': 'pass', }, { 'calls': [ ], 'is_registered': True, 'is_registered.call_count': 1, 'enable.call_count': 0, 'systemid.call_count': 0, 'changed': False, 'msg': 'System already registered.', 'run_command.call_count': 0, 'request_called': False, 'unlink.call_count': 0, }, ], [ # Unregister an host, check that result is changed { 'activationkey': 'key', 'username': 'user', 'password': 'pass', 'state': 'absent', }, { 'calls': [ ('auth.login', ['X' * 43]), ('system.deleteSystems', [1]), ('auth.logout', [1]), ], 'is_registered': True, 'is_registered.call_count': 1, 'enable.call_count': 0, 'systemid.call_count': 1, 'changed': True, 'msg': 'System successfully unregistered from rhn.redhat.com.', 'run_command.call_count': 0, 'request_called': True, 'unlink.call_count': 1, } ], [ # Unregister a unregistered host (systemid missing) locally, check that result is unchanged { 'activationkey': 'key', 'username': 'user', 'password': 'pass', 'state': 'absent', }, { 'calls': [], 'is_registered': False, 'is_registered.call_count': 1, 'enable.call_count': 0, 'systemid.call_count': 0, 'changed': False, 'msg': 'System already unregistered.', 'run_command.call_count': 0, 'request_called': False, 'unlink.call_count': 0, } ], [ # Unregister an unknown host (an host with a systemid available locally, check that result contains failed { 'activationkey': 'key', 'username': 'user', 'password': 'pass', 'state': 'absent', }, { 'calls': [ ('auth.login', ['X' * 43]), ('system.deleteSystems', xmlrpc_client.Fault(1003, 'The following systems were NOT deleted: 123456789')), ('auth.logout', [1]), ], 'is_registered': True, 'is_registered.call_count': 1, 'enable.call_count': 0, 'systemid.call_count': 1, 'failed': True, 'msg': "Failed to unregister: <Fault 1003: 'The following systems were NOT deleted: 123456789'>", 'run_command.call_count': 0, 'request_called': True, 'unlink.call_count': 0, } ], ] @pytest.mark.parametrize('patch_ansible_module, testcase', TEST_CASES, indirect=['patch_ansible_module']) @pytest.mark.usefixtures('patch_ansible_module') def test_register_parameters(mocker, capfd, mock_request, patch_rhn, testcase): # successful execution, no output mocker.patch.object(basic.AnsibleModule, 'run_command', return_value=(0, '', '')) mock_is_registered = mocker.patch.object(rhn_register.Rhn, 'is_registered', mocker.PropertyMock(return_value=testcase['is_registered'])) mocker.patch.object(rhn_register.Rhn, 'enable') mock_systemid = mocker.patch.object(rhn_register.Rhn, 'systemid', mocker.PropertyMock(return_value=12345)) mocker.patch('os.unlink', return_value=True) with pytest.raises(SystemExit): rhn_register.main() assert basic.AnsibleModule.run_command.call_count == testcase['run_command.call_count'] if basic.AnsibleModule.run_command.call_count: assert basic.AnsibleModule.run_command.call_args[0][0][0] == testcase['run_command.call_args'] assert mock_is_registered.call_count == testcase['is_registered.call_count'] assert rhn_register.Rhn.enable.call_count == testcase['enable.call_count'] assert mock_systemid.call_count == testcase['systemid.call_count'] assert xmlrpc_client.Transport.request.called == testcase['request_called'] assert os.unlink.call_count == testcase['unlink.call_count'] out, err = capfd.readouterr() results = json.loads(out) assert results.get('changed') == testcase.get('changed') assert results.get('failed') == testcase.get('failed') assert results['msg'] == testcase['msg'] assert not testcase['calls'] # all calls should have been consumed
gbirke/scrapy
refs/heads/master
scrapy/contrib/downloadermiddleware/downloadtimeout.py
163
""" Download timeout middleware See documentation in docs/topics/downloader-middleware.rst """ from scrapy import signals class DownloadTimeoutMiddleware(object): def __init__(self, timeout=180): self._timeout = timeout @classmethod def from_crawler(cls, crawler): o = cls(crawler.settings.getfloat('DOWNLOAD_TIMEOUT')) crawler.signals.connect(o.spider_opened, signal=signals.spider_opened) return o def spider_opened(self, spider): self._timeout = getattr(spider, 'download_timeout', self._timeout) def process_request(self, request, spider): if self._timeout: request.meta.setdefault('download_timeout', self._timeout)
amanharitsh123/zulip
refs/heads/master
zerver/templatetags/minified_js.py
3
from typing import Any, Dict from django.template import Node, Library, TemplateSyntaxError from django.conf import settings from django.contrib.staticfiles.storage import staticfiles_storage if False: # no need to add dependency from django.template.base import Parser, Token register = Library() class MinifiedJSNode(Node): def __init__(self, sourcefile): # type: (str) -> None self.sourcefile = sourcefile def render(self, context): # type: (Dict[str, Any]) -> str if settings.DEBUG: source_files = settings.JS_SPECS[self.sourcefile] normal_source = source_files['source_filenames'] minified_source = source_files.get('minifed_source_filenames', []) # Minified source files (most likely libraries) should be loaded # first to prevent any dependency errors. scripts = minified_source + normal_source else: scripts = [settings.JS_SPECS[self.sourcefile]['output_filename']] script_urls = [staticfiles_storage.url(script) for script in scripts] script_tags = ['<script type="text/javascript" src="%s" charset="utf-8"></script>' % url for url in script_urls] return '\n'.join(script_tags) @register.tag def minified_js(parser, token): # type: (Parser, Token) -> MinifiedJSNode try: tag_name, sourcefile = token.split_contents() except ValueError: raise TemplateSyntaxError("%s token requires an argument" % (token,)) if not (sourcefile[0] == sourcefile[-1] and sourcefile[0] in ('"', "'")): raise TemplateSyntaxError("%s tag should be quoted" % (tag_name,)) sourcefile = sourcefile[1:-1] if sourcefile not in settings.JS_SPECS: raise TemplateSyntaxError("%s tag invalid argument: no JS file %s" % (tag_name, sourcefile)) return MinifiedJSNode(sourcefile)
jimberlage/servo
refs/heads/master
tests/wpt/web-platform-tests/websockets/handlers/set-cookie-secure_wsh.py
33
#!/usr/bin/python from six.moves import urllib def web_socket_do_extra_handshake(request): url_parts = urllib.parse.urlsplit(request.uri) request.extra_headers.append(('Set-Cookie', 'ws_test_'+(url_parts.query or '')+'=test; Secure; Path=/')) def web_socket_transfer_data(request): # Expect close() from user agent. request.ws_stream.receive_message()
hynnet/openwrt-mt7620
refs/heads/master
staging_dir/target-mipsel_r2_uClibc-0.9.33.2/root-ralink/usr/lib/libstdc++.so.6.0.16-gdb.py
4
# -*- python -*- # Copyright (C) 2009, 2010 Free Software Foundation, 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 <http://www.gnu.org/licenses/>. import sys import gdb import os import os.path pythondir = '/home/hiwifi/openwrt-mt7620/staging_dir/toolchain-mipsel_r2_gcc-4.6-linaro_uClibc-0.9.33.2/share/gcc-4.6.3/python' libdir = '/home/hiwifi/openwrt-mt7620/staging_dir/toolchain-mipsel_r2_gcc-4.6-linaro_uClibc-0.9.33.2/mipsel-openwrt-linux-uclibc/lib' # This file might be loaded when there is no current objfile. This # can happen if the user loads it manually. In this case we don't # update sys.path; instead we just hope the user managed to do that # beforehand. if gdb.current_objfile () is not None: # Update module path. We want to find the relative path from libdir # to pythondir, and then we want to apply that relative path to the # directory holding the objfile with which this file is associated. # This preserves relocatability of the gcc tree. # Do a simple normalization that removes duplicate separators. pythondir = os.path.normpath (pythondir) libdir = os.path.normpath (libdir) prefix = os.path.commonprefix ([libdir, pythondir]) # In some bizarre configuration we might have found a match in the # middle of a directory name. if prefix[-1] != '/': prefix = os.path.dirname (prefix) + '/' # Strip off the prefix. pythondir = pythondir[len (prefix):] libdir = libdir[len (prefix):] # Compute the ".."s needed to get from libdir to the prefix. dotdots = ('..' + os.sep) * len (libdir.split (os.sep)) objfile = gdb.current_objfile ().filename dir_ = os.path.join (os.path.dirname (objfile), dotdots, pythondir) if not dir_ in sys.path: sys.path.insert(0, dir_) # Load the pretty-printers. from libstdcxx.v6.printers import register_libstdcxx_printers register_libstdcxx_printers (gdb.current_objfile ())
Azure/azure-sdk-for-python
refs/heads/sync-eng/common-js-nightly-docs-2-1768-ForTestPipeline
sdk/sql/azure-mgmt-sql/azure/mgmt/sql/operations/_long_term_retention_managed_instance_backups_operations.py
1
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class LongTermRetentionManagedInstanceBackupsOperations(object): """LongTermRetentionManagedInstanceBackupsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.sql.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def get( self, location_name, # type: str managed_instance_name, # type: str database_name, # type: str backup_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.ManagedInstanceLongTermRetentionBackup" """Gets a long term retention backup for a managed database. :param location_name: The location of the database. :type location_name: str :param managed_instance_name: The name of the managed instance. :type managed_instance_name: str :param database_name: The name of the managed database. :type database_name: str :param backup_name: The backup name. :type backup_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagedInstanceLongTermRetentionBackup, or the result of cls(response) :rtype: ~azure.mgmt.sql.models.ManagedInstanceLongTermRetentionBackup :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceLongTermRetentionBackup"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-11-01-preview" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'locationName': self._serialize.url("location_name", location_name, 'str'), 'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_name, 'str'), 'databaseName': self._serialize.url("database_name", database_name, 'str'), 'backupName': self._serialize.url("backup_name", backup_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ManagedInstanceLongTermRetentionBackup', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstances/{managedInstanceName}/longTermRetentionDatabases/{databaseName}/longTermRetentionManagedInstanceBackups/{backupName}'} # type: ignore def _delete_initial( self, location_name, # type: str managed_instance_name, # type: str database_name, # type: str backup_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-11-01-preview" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'locationName': self._serialize.url("location_name", location_name, 'str'), 'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_name, 'str'), 'databaseName': self._serialize.url("database_name", database_name, 'str'), 'backupName': self._serialize.url("backup_name", backup_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstances/{managedInstanceName}/longTermRetentionDatabases/{databaseName}/longTermRetentionManagedInstanceBackups/{backupName}'} # type: ignore def begin_delete( self, location_name, # type: str managed_instance_name, # type: str database_name, # type: str backup_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes a long term retention backup. :param location_name: The location of the database. :type location_name: str :param managed_instance_name: The name of the managed instance. :type managed_instance_name: str :param database_name: The name of the managed database. :type database_name: str :param backup_name: The backup name. :type backup_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( location_name=location_name, managed_instance_name=managed_instance_name, database_name=database_name, backup_name=backup_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'locationName': self._serialize.url("location_name", location_name, 'str'), 'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_name, 'str'), 'databaseName': self._serialize.url("database_name", database_name, 'str'), 'backupName': self._serialize.url("backup_name", backup_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstances/{managedInstanceName}/longTermRetentionDatabases/{databaseName}/longTermRetentionManagedInstanceBackups/{backupName}'} # type: ignore def list_by_database( self, location_name, # type: str managed_instance_name, # type: str database_name, # type: str only_latest_per_database=None, # type: Optional[bool] database_state=None, # type: Optional[Union[str, "_models.DatabaseState"]] **kwargs # type: Any ): # type: (...) -> Iterable["_models.ManagedInstanceLongTermRetentionBackupListResult"] """Lists all long term retention backups for a managed database. :param location_name: The location of the database. :type location_name: str :param managed_instance_name: The name of the managed instance. :type managed_instance_name: str :param database_name: The name of the managed database. :type database_name: str :param only_latest_per_database: Whether or not to only get the latest backup for each database. :type only_latest_per_database: bool :param database_state: Whether to query against just live databases, just deleted databases, or all databases. :type database_state: str or ~azure.mgmt.sql.models.DatabaseState :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagedInstanceLongTermRetentionBackupListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.sql.models.ManagedInstanceLongTermRetentionBackupListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceLongTermRetentionBackupListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-11-01-preview" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_database.metadata['url'] # type: ignore path_format_arguments = { 'locationName': self._serialize.url("location_name", location_name, 'str'), 'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_name, 'str'), 'databaseName': self._serialize.url("database_name", database_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if only_latest_per_database is not None: query_parameters['onlyLatestPerDatabase'] = self._serialize.query("only_latest_per_database", only_latest_per_database, 'bool') if database_state is not None: query_parameters['databaseState'] = self._serialize.query("database_state", database_state, 'str') query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ManagedInstanceLongTermRetentionBackupListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_database.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstances/{managedInstanceName}/longTermRetentionDatabases/{databaseName}/longTermRetentionManagedInstanceBackups'} # type: ignore def list_by_instance( self, location_name, # type: str managed_instance_name, # type: str only_latest_per_database=None, # type: Optional[bool] database_state=None, # type: Optional[Union[str, "_models.DatabaseState"]] **kwargs # type: Any ): # type: (...) -> Iterable["_models.ManagedInstanceLongTermRetentionBackupListResult"] """Lists the long term retention backups for a given managed instance. :param location_name: The location of the database. :type location_name: str :param managed_instance_name: The name of the managed instance. :type managed_instance_name: str :param only_latest_per_database: Whether or not to only get the latest backup for each database. :type only_latest_per_database: bool :param database_state: Whether to query against just live databases, just deleted databases, or all databases. :type database_state: str or ~azure.mgmt.sql.models.DatabaseState :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagedInstanceLongTermRetentionBackupListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.sql.models.ManagedInstanceLongTermRetentionBackupListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceLongTermRetentionBackupListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-11-01-preview" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_instance.metadata['url'] # type: ignore path_format_arguments = { 'locationName': self._serialize.url("location_name", location_name, 'str'), 'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if only_latest_per_database is not None: query_parameters['onlyLatestPerDatabase'] = self._serialize.query("only_latest_per_database", only_latest_per_database, 'bool') if database_state is not None: query_parameters['databaseState'] = self._serialize.query("database_state", database_state, 'str') query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ManagedInstanceLongTermRetentionBackupListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_instance.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstances/{managedInstanceName}/longTermRetentionManagedInstanceBackups'} # type: ignore def list_by_location( self, location_name, # type: str only_latest_per_database=None, # type: Optional[bool] database_state=None, # type: Optional[Union[str, "_models.DatabaseState"]] **kwargs # type: Any ): # type: (...) -> Iterable["_models.ManagedInstanceLongTermRetentionBackupListResult"] """Lists the long term retention backups for managed databases in a given location. :param location_name: The location of the database. :type location_name: str :param only_latest_per_database: Whether or not to only get the latest backup for each database. :type only_latest_per_database: bool :param database_state: Whether to query against just live databases, just deleted databases, or all databases. :type database_state: str or ~azure.mgmt.sql.models.DatabaseState :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagedInstanceLongTermRetentionBackupListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.sql.models.ManagedInstanceLongTermRetentionBackupListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceLongTermRetentionBackupListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-11-01-preview" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_location.metadata['url'] # type: ignore path_format_arguments = { 'locationName': self._serialize.url("location_name", location_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if only_latest_per_database is not None: query_parameters['onlyLatestPerDatabase'] = self._serialize.query("only_latest_per_database", only_latest_per_database, 'bool') if database_state is not None: query_parameters['databaseState'] = self._serialize.query("database_state", database_state, 'str') query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ManagedInstanceLongTermRetentionBackupListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_location.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstanceBackups'} # type: ignore def get_by_resource_group( self, resource_group_name, # type: str location_name, # type: str managed_instance_name, # type: str database_name, # type: str backup_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.ManagedInstanceLongTermRetentionBackup" """Gets a long term retention backup for a managed database. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. :type resource_group_name: str :param location_name: The location of the database. :type location_name: str :param managed_instance_name: The name of the managed instance. :type managed_instance_name: str :param database_name: The name of the managed database. :type database_name: str :param backup_name: The backup name. :type backup_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagedInstanceLongTermRetentionBackup, or the result of cls(response) :rtype: ~azure.mgmt.sql.models.ManagedInstanceLongTermRetentionBackup :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceLongTermRetentionBackup"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-11-01-preview" accept = "application/json" # Construct URL url = self.get_by_resource_group.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'locationName': self._serialize.url("location_name", location_name, 'str'), 'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_name, 'str'), 'databaseName': self._serialize.url("database_name", database_name, 'str'), 'backupName': self._serialize.url("backup_name", backup_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ManagedInstanceLongTermRetentionBackup', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstances/{managedInstanceName}/longTermRetentionDatabases/{databaseName}/longTermRetentionManagedInstanceBackups/{backupName}'} # type: ignore def _delete_by_resource_group_initial( self, resource_group_name, # type: str location_name, # type: str managed_instance_name, # type: str database_name, # type: str backup_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-11-01-preview" # Construct URL url = self._delete_by_resource_group_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'locationName': self._serialize.url("location_name", location_name, 'str'), 'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_name, 'str'), 'databaseName': self._serialize.url("database_name", database_name, 'str'), 'backupName': self._serialize.url("backup_name", backup_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_by_resource_group_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstances/{managedInstanceName}/longTermRetentionDatabases/{databaseName}/longTermRetentionManagedInstanceBackups/{backupName}'} # type: ignore def begin_delete_by_resource_group( self, resource_group_name, # type: str location_name, # type: str managed_instance_name, # type: str database_name, # type: str backup_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes a long term retention backup. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. :type resource_group_name: str :param location_name: The location of the database. :type location_name: str :param managed_instance_name: The name of the managed instance. :type managed_instance_name: str :param database_name: The name of the managed database. :type database_name: str :param backup_name: The backup name. :type backup_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_by_resource_group_initial( resource_group_name=resource_group_name, location_name=location_name, managed_instance_name=managed_instance_name, database_name=database_name, backup_name=backup_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'locationName': self._serialize.url("location_name", location_name, 'str'), 'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_name, 'str'), 'databaseName': self._serialize.url("database_name", database_name, 'str'), 'backupName': self._serialize.url("backup_name", backup_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstances/{managedInstanceName}/longTermRetentionDatabases/{databaseName}/longTermRetentionManagedInstanceBackups/{backupName}'} # type: ignore def list_by_resource_group_database( self, resource_group_name, # type: str location_name, # type: str managed_instance_name, # type: str database_name, # type: str only_latest_per_database=None, # type: Optional[bool] database_state=None, # type: Optional[Union[str, "_models.DatabaseState"]] **kwargs # type: Any ): # type: (...) -> Iterable["_models.ManagedInstanceLongTermRetentionBackupListResult"] """Lists all long term retention backups for a managed database. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. :type resource_group_name: str :param location_name: The location of the database. :type location_name: str :param managed_instance_name: The name of the managed instance. :type managed_instance_name: str :param database_name: The name of the managed database. :type database_name: str :param only_latest_per_database: Whether or not to only get the latest backup for each database. :type only_latest_per_database: bool :param database_state: Whether to query against just live databases, just deleted databases, or all databases. :type database_state: str or ~azure.mgmt.sql.models.DatabaseState :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagedInstanceLongTermRetentionBackupListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.sql.models.ManagedInstanceLongTermRetentionBackupListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceLongTermRetentionBackupListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-11-01-preview" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_resource_group_database.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'locationName': self._serialize.url("location_name", location_name, 'str'), 'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_name, 'str'), 'databaseName': self._serialize.url("database_name", database_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if only_latest_per_database is not None: query_parameters['onlyLatestPerDatabase'] = self._serialize.query("only_latest_per_database", only_latest_per_database, 'bool') if database_state is not None: query_parameters['databaseState'] = self._serialize.query("database_state", database_state, 'str') query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ManagedInstanceLongTermRetentionBackupListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_resource_group_database.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstances/{managedInstanceName}/longTermRetentionDatabases/{databaseName}/longTermRetentionManagedInstanceBackups'} # type: ignore def list_by_resource_group_instance( self, resource_group_name, # type: str location_name, # type: str managed_instance_name, # type: str only_latest_per_database=None, # type: Optional[bool] database_state=None, # type: Optional[Union[str, "_models.DatabaseState"]] **kwargs # type: Any ): # type: (...) -> Iterable["_models.ManagedInstanceLongTermRetentionBackupListResult"] """Lists the long term retention backups for a given managed instance. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. :type resource_group_name: str :param location_name: The location of the database. :type location_name: str :param managed_instance_name: The name of the managed instance. :type managed_instance_name: str :param only_latest_per_database: Whether or not to only get the latest backup for each database. :type only_latest_per_database: bool :param database_state: Whether to query against just live databases, just deleted databases, or all databases. :type database_state: str or ~azure.mgmt.sql.models.DatabaseState :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagedInstanceLongTermRetentionBackupListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.sql.models.ManagedInstanceLongTermRetentionBackupListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceLongTermRetentionBackupListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-11-01-preview" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_resource_group_instance.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'locationName': self._serialize.url("location_name", location_name, 'str'), 'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if only_latest_per_database is not None: query_parameters['onlyLatestPerDatabase'] = self._serialize.query("only_latest_per_database", only_latest_per_database, 'bool') if database_state is not None: query_parameters['databaseState'] = self._serialize.query("database_state", database_state, 'str') query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ManagedInstanceLongTermRetentionBackupListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_resource_group_instance.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstances/{managedInstanceName}/longTermRetentionManagedInstanceBackups'} # type: ignore def list_by_resource_group_location( self, resource_group_name, # type: str location_name, # type: str only_latest_per_database=None, # type: Optional[bool] database_state=None, # type: Optional[Union[str, "_models.DatabaseState"]] **kwargs # type: Any ): # type: (...) -> Iterable["_models.ManagedInstanceLongTermRetentionBackupListResult"] """Lists the long term retention backups for managed databases in a given location. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. :type resource_group_name: str :param location_name: The location of the database. :type location_name: str :param only_latest_per_database: Whether or not to only get the latest backup for each database. :type only_latest_per_database: bool :param database_state: Whether to query against just live databases, just deleted databases, or all databases. :type database_state: str or ~azure.mgmt.sql.models.DatabaseState :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagedInstanceLongTermRetentionBackupListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.sql.models.ManagedInstanceLongTermRetentionBackupListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceLongTermRetentionBackupListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-11-01-preview" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_resource_group_location.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'locationName': self._serialize.url("location_name", location_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if only_latest_per_database is not None: query_parameters['onlyLatestPerDatabase'] = self._serialize.query("only_latest_per_database", only_latest_per_database, 'bool') if database_state is not None: query_parameters['databaseState'] = self._serialize.query("database_state", database_state, 'str') query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('ManagedInstanceLongTermRetentionBackupListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_resource_group_location.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstanceBackups'} # type: ignore
gangadharkadam/smrterp
refs/heads/develop
erpnext/manufacturing/doctype/bom_replace_tool/__init__.py
12133432
jelugbo/hebs_repo
refs/heads/master
lms/djangoapps/notes/migrations/__init__.py
12133432
yongshengwang/builthue
refs/heads/master
desktop/core/ext-py/Django-1.4.5/django/conf/locale/te/__init__.py
12133432
Vixionar/django
refs/heads/master
tests/select_related/__init__.py
12133432
eeshangarg/oh-mainline
refs/heads/master
vendor/packages/gdata/samples/oauth/oauth_on_appengine/appengine_utilities/__init__.py
12133432
sliz1/servo
refs/heads/master
tests/wpt/web-platform-tests/tools/manifest/tests/__init__.py
12133432
AlexHill/django
refs/heads/master
django/template/loaders/__init__.py
12133432
ioannistsanaktsidis/invenio
refs/heads/prod
modules/bibindex/lib/tokenizers/BibIndexAuthorTokenizer.py
2
# -*- coding:utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2010, 2011, 2012 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. """BibIndexAuthorTokenizer: tokenizer introduced for author index. It tokenizes author name in a fuzzy way. Creates different variants of an author name. For example: John Cleese will be tokenized into: 'C John', 'Cleese John', 'John, C', 'John, Cleese' """ import re from invenio.config import CFG_BIBINDEX_AUTHOR_WORD_INDEX_EXCLUDE_FIRST_NAMES from invenio.bibindex_tokenizers.BibIndexDefaultTokenizer import BibIndexDefaultTokenizer from invenio.textutils import wash_for_utf8, strip_accents from invenio.bibindex_engine_washer import lower_index_term class BibIndexAuthorTokenizer(BibIndexDefaultTokenizer): """Human name tokenizer. Human names are divided into three classes of tokens: 'lastnames', i.e., family, tribal or group identifiers, 'nonlastnames', i.e., personal names distinguishing individuals, 'titles', both incidental and permanent, e.g., 'VIII', '(ed.)', 'Msc' """ def __init__(self, stemming_language = None, remove_stopwords = False, remove_html_markup = False, remove_latex_markup = False): BibIndexDefaultTokenizer.__init__(self, stemming_language, remove_stopwords, remove_html_markup, remove_latex_markup) self.single_initial_re = re.compile('^\w\.$') self.split_on_re = re.compile('[\.\s-]') # lastname_stopwords describes terms which should not be used for indexing, # in multiple-word last names. These are purely conjunctions, serving the # same function as the American hyphen, but using linguistic constructs. self.lastname_stopwords = set(['y', 'of', 'and', 'de']) def scan_string_for_phrases(self, s): """Scan a name string and output an object representing its structure. @param s: the input to be lexically tagged @type s: string @return: dict of lexically tagged input items. Sample output for the name 'Jingleheimer Schmitt, John Jacob, XVI.' is: { 'TOKEN_TAG_LIST' : ['lastnames', 'nonlastnames', 'titles', 'raw'], 'lastnames' : ['Jingleheimer', 'Schmitt'], 'nonlastnames' : ['John', 'Jacob'], 'titles' : ['XVI.'], 'raw' : 'Jingleheimer Schmitt, John Jacob, XVI.' } @rtype: dict """ retval = {'TOKEN_TAG_LIST' : ['lastnames', 'nonlastnames', 'titles', 'raw'], 'lastnames' : [], 'nonlastnames' : [], 'titles' : [], 'raw' : s} l = s.split(',') if len(l) < 2: # No commas means a simple name new = s.strip() new = s.split(' ') if len(new) == 1: retval['lastnames'] = new # rare single-name case else: retval['lastnames'] = new[-1:] retval['nonlastnames'] = new[:-1] for tag in ['lastnames', 'nonlastnames']: retval[tag] = [x.strip() for x in retval[tag]] retval[tag] = [re.split(self.split_on_re, x) for x in retval[tag]] # flatten sublists retval[tag] = [item for sublist in retval[tag] for item in sublist] retval[tag] = [x for x in retval[tag] if x != ''] else: # Handle lastname-first multiple-names case retval['titles'] = l[2:] # no titles? no problem retval['nonlastnames'] = l[1] retval['lastnames'] = l[0] for tag in ['lastnames', 'nonlastnames']: retval[tag] = retval[tag].strip() retval[tag] = re.split(self.split_on_re, retval[tag]) # filter empty strings retval[tag] = [x for x in retval[tag] if x != ''] retval['titles'] = [x.strip() for x in retval['titles'] if x != ''] return retval def parse_scanned_for_phrases(self, scanned): """Return all the indexable variations for a tagged token dictionary. Does this via the combinatoric expansion of the following rules: - Expands first names as name, first initial with period, first initial without period. - Expands compound last names as each of their non-stopword subparts. - Titles are treated literally, but applied serially. Please note that titles will be applied to complete last names only. So for example, if there is a compound last name of the form, "Ibanez y Gracia", with the title, "(ed.)", then only the combination of those two strings will do, not "Ibanez" and not "Gracia". @param scanned: lexically tagged input items in the form of the output from scan() @type scanned: dict @return: combinatorically expanded list of strings for indexing @rtype: list of string """ def _fully_expanded_last_name(first, lastlist, title = None): """Return a list of all of the first / last / title combinations. @param first: one possible non-last name @type first: string @param lastlist: the strings of the tokens in the (possibly compound) last name @type lastlist: list of string @param title: one possible title @type title: string """ retval = [] title_word = '' if title != None: title_word = ', ' + title last = ' '.join(lastlist) retval.append(first + ' ' + last + title_word) retval.append(last + ', ' + first + title_word) for last in lastlist: if last in self.lastname_stopwords: continue retval.append(first + ' ' + last + title_word) retval.append(last + ', ' + first + title_word) return retval last_parts = scanned['lastnames'] first_parts = scanned['nonlastnames'] titles = scanned['titles'] raw = scanned['raw'] if len(first_parts) == 0: # rare single-name case return scanned['lastnames'] expanded = [] for exp in self.__expand_nonlastnames(first_parts): expanded.extend(_fully_expanded_last_name(exp, last_parts, None)) for title in titles: # Drop titles which are parenthesized. This eliminates (ed.) from the index, but # leaves XI, for example. This gets rid of the surprising behavior that searching # for 'author:ed' retrieves people who have been editors, but whose names aren't # Ed. # TODO: Make editorship and other special statuses a MARC field. if title.find('(') != -1: continue # XXX: remember to document that titles can only be applied to complete last names expanded.extend(_fully_expanded_last_name(exp, [' '.join(last_parts)], title)) return sorted(list(set(expanded))) def __expand_nonlastnames(self, namelist): """Generate every expansion of a series of human non-last names. Example: "Michael Edward" -> "Michael Edward", "Michael E.", "Michael E", "M. Edward", "M Edward", "M. E.", "M. E", "M E.", "M E", "M.E." ...but never: "ME" @param namelist: a collection of names @type namelist: list of string @return: a greatly expanded collection of names @rtype: list of string """ def _expand_name(name): """Lists [name, initial, empty]""" if name == None: return [] return [name, name[0]] def _pair_items(head, tail): """Lists every combination of head with each and all of tail""" if len(tail) == 0: return [head] l = [] l.extend([head + ' ' + tail[0]]) #l.extend([head + '-' + tail[0]]) l.extend(_pair_items(head, tail[1:])) return l def _collect(head, tail): """Brings together combinations of things""" def _cons(a, l): l2 = l[:] l2.insert(0, a) return l2 if len(tail) == 0: return [head] l = [] l.extend(_pair_items(head, _expand_name(tail[0]))) l.extend([' '.join(_cons(head, tail)).strip()]) #l.extend(['-'.join(_cons(head, tail)).strip()]) l.extend(_collect(head, tail[1:])) return l def _expand_contract(namelist): """Runs collect with every head in namelist and its tail""" val = [] for i in range(len(namelist)): name = namelist[i] for expansion in _expand_name(name): val.extend(_collect(expansion, namelist[i+1:])) return val def _add_squashed(namelist): """Finds cases like 'M. E.' and adds 'M.E.'""" val = namelist def __check_parts(parts): if len(parts) < 2: return False for part in parts: if not self.single_initial_re.match(part): return False return True for name in namelist: parts = name.split(' ') if not __check_parts(parts): continue val.extend([''.join(parts)]) return val return _add_squashed(_expand_contract(namelist)) def tokenize_for_fuzzy_authors(self, phrase): """Output the list of strings expanding phrase. Does this via the combinatoric expansion of the following rules: - Expands first names as name, first initial with period, first initial without period. - Expands compound last names as each of their non-stopword subparts. - Titles are treated literally, but applied serially. Please note that titles will be applied to complete last names only. So for example, if there is a compound last name of the form, "Ibanez y Gracia", with the title, "(ed.)", then only the combination of those two strings will do, not "Ibanez" and not "Gracia". Old: BibIndexFuzzyAuthorTokenizer @param phrase: the input to be lexically tagged @type phrase: string @return: combinatorically expanded list of strings for indexing @rtype: list of string @note: A simple wrapper around scan and parse_scanned. """ return self.parse_scanned_for_phrases(self.scan_string_for_phrases(phrase)) def tokenize_for_phrases(self, phrase): """ Another name for tokenize_for_fuzzy_authors. It's for the compatibility. See: tokenize_for_fuzzy_authors """ phrase = wash_for_utf8(phrase) phrase = lower_index_term(phrase) return self.tokenize_for_fuzzy_authors(strip_accents(phrase)) def tokenize_for_words_default(self, phrase): """Default tokenize_for_words inherited from default tokenizer""" return super(BibIndexAuthorTokenizer, self).tokenize_for_words(phrase) def get_author_family_name_words_from_phrase(self, phrase): """ Return list of words from author family names, not his/her first names. The phrase is assumed to be the full author name. This is useful for CFG_BIBINDEX_AUTHOR_WORD_INDEX_EXCLUDE_FIRST_NAMES. @param phrase: phrase to get family name from """ d_family_names = {} # first, treat everything before first comma as surname: if ',' in phrase: d_family_names[phrase.split(',', 1)[0]] = 1 # second, try fuzzy author tokenizer to find surname variants: for name in self.tokenize_for_phrases(phrase): if ',' in name: d_family_names[name.split(',', 1)[0]] = 1 # now extract words from these surnames: d_family_names_words = {} for family_name in d_family_names.keys(): for word in self.tokenize_for_words_default(family_name): d_family_names_words[word] = 1 return d_family_names_words.keys() def tokenize_for_words(self, phrase): """ If CFG_BIBINDEX_AUTHOR_WORD_INDEX_EXCLUDE_FIRST_NAMES is 1 we tokenize only for family names. In other case we perform standard tokenization for words. """ phrase = wash_for_utf8(phrase) phrase = lower_index_term(phrase) phrase = strip_accents(phrase) if CFG_BIBINDEX_AUTHOR_WORD_INDEX_EXCLUDE_FIRST_NAMES: return self.get_author_family_name_words_from_phrase(phrase) else: return self.tokenize_for_words_default(phrase)
kawasaki2013/python-for-android-x86
refs/heads/master
python3-alpha/python3-src/Parser/spark.py
85
# Copyright (c) 1998-2002 John Aycock # # 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. __version__ = 'SPARK-0.7 (pre-alpha-5)' import re # Compatibility with older pythons. def output(string='', end='\n'): sys.stdout.write(string + end) try: sorted except NameError: def sorted(seq): seq2 = seq[:] seq2.sort() return seq2 def _namelist(instance): namelist, namedict, classlist = [], {}, [instance.__class__] for c in classlist: for b in c.__bases__: classlist.append(b) for name in c.__dict__.keys(): if name not in namedict: namelist.append(name) namedict[name] = 1 return namelist class GenericScanner: def __init__(self, flags=0): pattern = self.reflect() self.re = re.compile(pattern, re.VERBOSE|flags) self.index2func = {} for name, number in self.re.groupindex.items(): self.index2func[number-1] = getattr(self, 't_' + name) def makeRE(self, name): doc = getattr(self, name).__doc__ rv = '(?P<%s>%s)' % (name[2:], doc) return rv def reflect(self): rv = [] for name in _namelist(self): if name[:2] == 't_' and name != 't_default': rv.append(self.makeRE(name)) rv.append(self.makeRE('t_default')) return '|'.join(rv) def error(self, s, pos): output("Lexical error at position %s" % pos) raise SystemExit def tokenize(self, s): pos = 0 n = len(s) while pos < n: m = self.re.match(s, pos) if m is None: self.error(s, pos) groups = m.groups() for i in range(len(groups)): if groups[i] and i in self.index2func: self.index2func[i](groups[i]) pos = m.end() def t_default(self, s): r'( . | \n )+' output("Specification error: unmatched input") raise SystemExit # # Extracted from GenericParser and made global so that [un]picking works. # class _State: def __init__(self, stateno, items): self.T, self.complete, self.items = [], [], items self.stateno = stateno class GenericParser: # # An Earley parser, as per J. Earley, "An Efficient Context-Free # Parsing Algorithm", CACM 13(2), pp. 94-102. Also J. C. Earley, # "An Efficient Context-Free Parsing Algorithm", Ph.D. thesis, # Carnegie-Mellon University, August 1968. New formulation of # the parser according to J. Aycock, "Practical Earley Parsing # and the SPARK Toolkit", Ph.D. thesis, University of Victoria, # 2001, and J. Aycock and R. N. Horspool, "Practical Earley # Parsing", unpublished paper, 2001. # def __init__(self, start): self.rules = {} self.rule2func = {} self.rule2name = {} self.collectRules() self.augment(start) self.ruleschanged = 1 _NULLABLE = '\e_' _START = 'START' _BOF = '|-' # # When pickling, take the time to generate the full state machine; # some information is then extraneous, too. Unfortunately we # can't save the rule2func map. # def __getstate__(self): if self.ruleschanged: # # XXX - duplicated from parse() # self.computeNull() self.newrules = {} self.new2old = {} self.makeNewRules() self.ruleschanged = 0 self.edges, self.cores = {}, {} self.states = { 0: self.makeState0() } self.makeState(0, self._BOF) # # XXX - should find a better way to do this.. # changes = 1 while changes: changes = 0 for k, v in self.edges.items(): if v is None: state, sym = k if state in self.states: self.goto(state, sym) changes = 1 rv = self.__dict__.copy() for s in self.states.values(): del s.items del rv['rule2func'] del rv['nullable'] del rv['cores'] return rv def __setstate__(self, D): self.rules = {} self.rule2func = {} self.rule2name = {} self.collectRules() start = D['rules'][self._START][0][1][1] # Blech. self.augment(start) D['rule2func'] = self.rule2func D['makeSet'] = self.makeSet_fast self.__dict__ = D # # A hook for GenericASTBuilder and GenericASTMatcher. Mess # thee not with this; nor shall thee toucheth the _preprocess # argument to addRule. # def preprocess(self, rule, func): return rule, func def addRule(self, doc, func, _preprocess=1): fn = func rules = doc.split() index = [] for i in range(len(rules)): if rules[i] == '::=': index.append(i-1) index.append(len(rules)) for i in range(len(index)-1): lhs = rules[index[i]] rhs = rules[index[i]+2:index[i+1]] rule = (lhs, tuple(rhs)) if _preprocess: rule, fn = self.preprocess(rule, func) if lhs in self.rules: self.rules[lhs].append(rule) else: self.rules[lhs] = [ rule ] self.rule2func[rule] = fn self.rule2name[rule] = func.__name__[2:] self.ruleschanged = 1 def collectRules(self): for name in _namelist(self): if name[:2] == 'p_': func = getattr(self, name) doc = func.__doc__ self.addRule(doc, func) def augment(self, start): rule = '%s ::= %s %s' % (self._START, self._BOF, start) self.addRule(rule, lambda args: args[1], 0) def computeNull(self): self.nullable = {} tbd = [] for rulelist in self.rules.values(): lhs = rulelist[0][0] self.nullable[lhs] = 0 for rule in rulelist: rhs = rule[1] if len(rhs) == 0: self.nullable[lhs] = 1 continue # # We only need to consider rules which # consist entirely of nonterminal symbols. # This should be a savings on typical # grammars. # for sym in rhs: if sym not in self.rules: break else: tbd.append(rule) changes = 1 while changes: changes = 0 for lhs, rhs in tbd: if self.nullable[lhs]: continue for sym in rhs: if not self.nullable[sym]: break else: self.nullable[lhs] = 1 changes = 1 def makeState0(self): s0 = _State(0, []) for rule in self.newrules[self._START]: s0.items.append((rule, 0)) return s0 def finalState(self, tokens): # # Yuck. # if len(self.newrules[self._START]) == 2 and len(tokens) == 0: return 1 start = self.rules[self._START][0][1][1] return self.goto(1, start) def makeNewRules(self): worklist = [] for rulelist in self.rules.values(): for rule in rulelist: worklist.append((rule, 0, 1, rule)) for rule, i, candidate, oldrule in worklist: lhs, rhs = rule n = len(rhs) while i < n: sym = rhs[i] if sym not in self.rules or \ not self.nullable[sym]: candidate = 0 i = i + 1 continue newrhs = list(rhs) newrhs[i] = self._NULLABLE+sym newrule = (lhs, tuple(newrhs)) worklist.append((newrule, i+1, candidate, oldrule)) candidate = 0 i = i + 1 else: if candidate: lhs = self._NULLABLE+lhs rule = (lhs, rhs) if lhs in self.newrules: self.newrules[lhs].append(rule) else: self.newrules[lhs] = [ rule ] self.new2old[rule] = oldrule def typestring(self, token): return None def error(self, token): output("Syntax error at or near `%s' token" % token) raise SystemExit def parse(self, tokens): sets = [ [(1,0), (2,0)] ] self.links = {} if self.ruleschanged: self.computeNull() self.newrules = {} self.new2old = {} self.makeNewRules() self.ruleschanged = 0 self.edges, self.cores = {}, {} self.states = { 0: self.makeState0() } self.makeState(0, self._BOF) for i in range(len(tokens)): sets.append([]) if sets[i] == []: break self.makeSet(tokens[i], sets, i) else: sets.append([]) self.makeSet(None, sets, len(tokens)) #_dump(tokens, sets, self.states) finalitem = (self.finalState(tokens), 0) if finalitem not in sets[-2]: if len(tokens) > 0: self.error(tokens[i-1]) else: self.error(None) return self.buildTree(self._START, finalitem, tokens, len(sets)-2) def isnullable(self, sym): # # For symbols in G_e only. If we weren't supporting 1.5, # could just use sym.startswith(). # return self._NULLABLE == sym[0:len(self._NULLABLE)] def skip(self, hs, pos=0): n = len(hs[1]) while pos < n: if not self.isnullable(hs[1][pos]): break pos = pos + 1 return pos def makeState(self, state, sym): assert sym is not None # # Compute \epsilon-kernel state's core and see if # it exists already. # kitems = [] for rule, pos in self.states[state].items: lhs, rhs = rule if rhs[pos:pos+1] == (sym,): kitems.append((rule, self.skip(rule, pos+1))) core = kitems core.sort() tcore = tuple(core) if tcore in self.cores: return self.cores[tcore] # # Nope, doesn't exist. Compute it and the associated # \epsilon-nonkernel state together; we'll need it right away. # k = self.cores[tcore] = len(self.states) K, NK = _State(k, kitems), _State(k+1, []) self.states[k] = K predicted = {} edges = self.edges rules = self.newrules for X in K, NK: worklist = X.items for item in worklist: rule, pos = item lhs, rhs = rule if pos == len(rhs): X.complete.append(rule) continue nextSym = rhs[pos] key = (X.stateno, nextSym) if nextSym not in rules: if key not in edges: edges[key] = None X.T.append(nextSym) else: edges[key] = None if nextSym not in predicted: predicted[nextSym] = 1 for prule in rules[nextSym]: ppos = self.skip(prule) new = (prule, ppos) NK.items.append(new) # # Problem: we know K needs generating, but we # don't yet know about NK. Can't commit anything # regarding NK to self.edges until we're sure. Should # we delay committing on both K and NK to avoid this # hacky code? This creates other problems.. # if X is K: edges = {} if NK.items == []: return k # # Check for \epsilon-nonkernel's core. Unfortunately we # need to know the entire set of predicted nonterminals # to do this without accidentally duplicating states. # core = sorted(predicted.keys()) tcore = tuple(core) if tcore in self.cores: self.edges[(k, None)] = self.cores[tcore] return k nk = self.cores[tcore] = self.edges[(k, None)] = NK.stateno self.edges.update(edges) self.states[nk] = NK return k def goto(self, state, sym): key = (state, sym) if key not in self.edges: # # No transitions from state on sym. # return None rv = self.edges[key] if rv is None: # # Target state isn't generated yet. Remedy this. # rv = self.makeState(state, sym) self.edges[key] = rv return rv def gotoT(self, state, t): return [self.goto(state, t)] def gotoST(self, state, st): rv = [] for t in self.states[state].T: if st == t: rv.append(self.goto(state, t)) return rv def add(self, set, item, i=None, predecessor=None, causal=None): if predecessor is None: if item not in set: set.append(item) else: key = (item, i) if item not in set: self.links[key] = [] set.append(item) self.links[key].append((predecessor, causal)) def makeSet(self, token, sets, i): cur, next = sets[i], sets[i+1] ttype = token is not None and self.typestring(token) or None if ttype is not None: fn, arg = self.gotoT, ttype else: fn, arg = self.gotoST, token for item in cur: ptr = (item, i) state, parent = item add = fn(state, arg) for k in add: if k is not None: self.add(next, (k, parent), i+1, ptr) nk = self.goto(k, None) if nk is not None: self.add(next, (nk, i+1)) if parent == i: continue for rule in self.states[state].complete: lhs, rhs = rule for pitem in sets[parent]: pstate, pparent = pitem k = self.goto(pstate, lhs) if k is not None: why = (item, i, rule) pptr = (pitem, parent) self.add(cur, (k, pparent), i, pptr, why) nk = self.goto(k, None) if nk is not None: self.add(cur, (nk, i)) def makeSet_fast(self, token, sets, i): # # Call *only* when the entire state machine has been built! # It relies on self.edges being filled in completely, and # then duplicates and inlines code to boost speed at the # cost of extreme ugliness. # cur, next = sets[i], sets[i+1] ttype = token is not None and self.typestring(token) or None for item in cur: ptr = (item, i) state, parent = item if ttype is not None: k = self.edges.get((state, ttype), None) if k is not None: #self.add(next, (k, parent), i+1, ptr) #INLINED --v new = (k, parent) key = (new, i+1) if new not in next: self.links[key] = [] next.append(new) self.links[key].append((ptr, None)) #INLINED --^ #nk = self.goto(k, None) nk = self.edges.get((k, None), None) if nk is not None: #self.add(next, (nk, i+1)) #INLINED --v new = (nk, i+1) if new not in next: next.append(new) #INLINED --^ else: add = self.gotoST(state, token) for k in add: if k is not None: self.add(next, (k, parent), i+1, ptr) #nk = self.goto(k, None) nk = self.edges.get((k, None), None) if nk is not None: self.add(next, (nk, i+1)) if parent == i: continue for rule in self.states[state].complete: lhs, rhs = rule for pitem in sets[parent]: pstate, pparent = pitem #k = self.goto(pstate, lhs) k = self.edges.get((pstate, lhs), None) if k is not None: why = (item, i, rule) pptr = (pitem, parent) #self.add(cur, (k, pparent), # i, pptr, why) #INLINED --v new = (k, pparent) key = (new, i) if new not in cur: self.links[key] = [] cur.append(new) self.links[key].append((pptr, why)) #INLINED --^ #nk = self.goto(k, None) nk = self.edges.get((k, None), None) if nk is not None: #self.add(cur, (nk, i)) #INLINED --v new = (nk, i) if new not in cur: cur.append(new) #INLINED --^ def predecessor(self, key, causal): for p, c in self.links[key]: if c == causal: return p assert 0 def causal(self, key): links = self.links[key] if len(links) == 1: return links[0][1] choices = [] rule2cause = {} for p, c in links: rule = c[2] choices.append(rule) rule2cause[rule] = c return rule2cause[self.ambiguity(choices)] def deriveEpsilon(self, nt): if len(self.newrules[nt]) > 1: rule = self.ambiguity(self.newrules[nt]) else: rule = self.newrules[nt][0] #output(rule) rhs = rule[1] attr = [None] * len(rhs) for i in range(len(rhs)-1, -1, -1): attr[i] = self.deriveEpsilon(rhs[i]) return self.rule2func[self.new2old[rule]](attr) def buildTree(self, nt, item, tokens, k): state, parent = item choices = [] for rule in self.states[state].complete: if rule[0] == nt: choices.append(rule) rule = choices[0] if len(choices) > 1: rule = self.ambiguity(choices) #output(rule) rhs = rule[1] attr = [None] * len(rhs) for i in range(len(rhs)-1, -1, -1): sym = rhs[i] if sym not in self.newrules: if sym != self._BOF: attr[i] = tokens[k-1] key = (item, k) item, k = self.predecessor(key, None) #elif self.isnullable(sym): elif self._NULLABLE == sym[0:len(self._NULLABLE)]: attr[i] = self.deriveEpsilon(sym) else: key = (item, k) why = self.causal(key) attr[i] = self.buildTree(sym, why[0], tokens, why[1]) item, k = self.predecessor(key, why) return self.rule2func[self.new2old[rule]](attr) def ambiguity(self, rules): # # XXX - problem here and in collectRules() if the same rule # appears in >1 method. Also undefined results if rules # causing the ambiguity appear in the same method. # sortlist = [] name2index = {} for i in range(len(rules)): lhs, rhs = rule = rules[i] name = self.rule2name[self.new2old[rule]] sortlist.append((len(rhs), name)) name2index[name] = i sortlist.sort() list = [b for a, b in sortlist] return rules[name2index[self.resolve(list)]] def resolve(self, list): # # Resolve ambiguity in favor of the shortest RHS. # Since we walk the tree from the top down, this # should effectively resolve in favor of a "shift". # return list[0] # # GenericASTBuilder automagically constructs a concrete/abstract syntax tree # for a given input. The extra argument is a class (not an instance!) # which supports the "__setslice__" and "__len__" methods. # # XXX - silently overrides any user code in methods. # class GenericASTBuilder(GenericParser): def __init__(self, AST, start): GenericParser.__init__(self, start) self.AST = AST def preprocess(self, rule, func): rebind = lambda lhs, self=self: \ lambda args, lhs=lhs, self=self: \ self.buildASTNode(args, lhs) lhs, rhs = rule return rule, rebind(lhs) def buildASTNode(self, args, lhs): children = [] for arg in args: if isinstance(arg, self.AST): children.append(arg) else: children.append(self.terminal(arg)) return self.nonterminal(lhs, children) def terminal(self, token): return token def nonterminal(self, type, args): rv = self.AST(type) rv[:len(args)] = args return rv # # GenericASTTraversal is a Visitor pattern according to Design Patterns. For # each node it attempts to invoke the method n_<node type>, falling # back onto the default() method if the n_* can't be found. The preorder # traversal also looks for an exit hook named n_<node type>_exit (no default # routine is called if it's not found). To prematurely halt traversal # of a subtree, call the prune() method -- this only makes sense for a # preorder traversal. Node type is determined via the typestring() method. # class GenericASTTraversalPruningException: pass class GenericASTTraversal: def __init__(self, ast): self.ast = ast def typestring(self, node): return node.type def prune(self): raise GenericASTTraversalPruningException def preorder(self, node=None): if node is None: node = self.ast try: name = 'n_' + self.typestring(node) if hasattr(self, name): func = getattr(self, name) func(node) else: self.default(node) except GenericASTTraversalPruningException: return for kid in node: self.preorder(kid) name = name + '_exit' if hasattr(self, name): func = getattr(self, name) func(node) def postorder(self, node=None): if node is None: node = self.ast for kid in node: self.postorder(kid) name = 'n_' + self.typestring(node) if hasattr(self, name): func = getattr(self, name) func(node) else: self.default(node) def default(self, node): pass # # GenericASTMatcher. AST nodes must have "__getitem__" and "__cmp__" # implemented. # # XXX - makes assumptions about how GenericParser walks the parse tree. # class GenericASTMatcher(GenericParser): def __init__(self, start, ast): GenericParser.__init__(self, start) self.ast = ast def preprocess(self, rule, func): rebind = lambda func, self=self: \ lambda args, func=func, self=self: \ self.foundMatch(args, func) lhs, rhs = rule rhslist = list(rhs) rhslist.reverse() return (lhs, tuple(rhslist)), rebind(func) def foundMatch(self, args, func): func(args[-1]) return args[-1] def match_r(self, node): self.input.insert(0, node) children = 0 for child in node: if children == 0: self.input.insert(0, '(') children = children + 1 self.match_r(child) if children > 0: self.input.insert(0, ')') def match(self, ast=None): if ast is None: ast = self.ast self.input = [] self.match_r(ast) self.parse(self.input) def resolve(self, list): # # Resolve ambiguity in favor of the longest RHS. # return list[-1] def _dump(tokens, sets, states): for i in range(len(sets)): output('set %d' % i) for item in sets[i]: output('\t', item) for (lhs, rhs), pos in states[item[0]].items: output('\t\t', lhs, '::=', end='') output(' '.join(rhs[:pos]), end='') output('.', end='') output(' '.join(rhs[pos:])) if i < len(tokens): output() output('token %s' % str(tokens[i])) output()
jaimeMF/youtube-dl
refs/heads/master
youtube_dl/extractor/nick.py
9
# coding: utf-8 from __future__ import unicode_literals from .mtv import MTVServicesInfoExtractor from ..compat import compat_urllib_parse class NickIE(MTVServicesInfoExtractor): IE_NAME = 'nick.com' _VALID_URL = r'https?://(?:www\.)?nick\.com/videos/clip/(?P<id>[^/?#.]+)' _FEED_URL = 'http://udat.mtvnservices.com/service1/dispatch.htm' _TESTS = [{ 'url': 'http://www.nick.com/videos/clip/alvinnn-and-the-chipmunks-112-full-episode.html', 'playlist': [ { 'md5': '6e5adc1e28253bbb1b28ab05403dd4d4', 'info_dict': { 'id': 'be6a17b0-412d-11e5-8ff7-0026b9414f30', 'ext': 'mp4', 'title': 'ALVINNN!!! and The Chipmunks: "Mojo Missing/Who\'s The Animal" S1', 'description': 'Alvin is convinced his mojo was in a cap he gave to a fan, and must find a way to get his hat back before the Chipmunks’ big concert.\nDuring a costume visit to the zoo, Alvin finds himself mistaken for the real Tasmanian devil.', } }, { 'md5': 'd7be441fc53a1d4882fa9508a1e5b3ce', 'info_dict': { 'id': 'be6b8f96-412d-11e5-8ff7-0026b9414f30', 'ext': 'mp4', 'title': 'ALVINNN!!! and The Chipmunks: "Mojo Missing/Who\'s The Animal" S2', 'description': 'Alvin is convinced his mojo was in a cap he gave to a fan, and must find a way to get his hat back before the Chipmunks’ big concert.\nDuring a costume visit to the zoo, Alvin finds himself mistaken for the real Tasmanian devil.', } }, { 'md5': 'efffe1728a234b2b0d2f2b343dd1946f', 'info_dict': { 'id': 'be6cf7e6-412d-11e5-8ff7-0026b9414f30', 'ext': 'mp4', 'title': 'ALVINNN!!! and The Chipmunks: "Mojo Missing/Who\'s The Animal" S3', 'description': 'Alvin is convinced his mojo was in a cap he gave to a fan, and must find a way to get his hat back before the Chipmunks’ big concert.\nDuring a costume visit to the zoo, Alvin finds himself mistaken for the real Tasmanian devil.', } }, { 'md5': '1ec6690733ab9f41709e274a1d5c7556', 'info_dict': { 'id': 'be6e3354-412d-11e5-8ff7-0026b9414f30', 'ext': 'mp4', 'title': 'ALVINNN!!! and The Chipmunks: "Mojo Missing/Who\'s The Animal" S4', 'description': 'Alvin is convinced his mojo was in a cap he gave to a fan, and must find a way to get his hat back before the Chipmunks’ big concert.\nDuring a costume visit to the zoo, Alvin finds himself mistaken for the real Tasmanian devil.', } }, ], }] def _get_feed_query(self, uri): return compat_urllib_parse.urlencode({ 'feed': 'nick_arc_player_prime', 'mgid': uri, }) def _extract_mgid(self, webpage): return self._search_regex(r'data-contenturi="([^"]+)', webpage, 'mgid')
gchild320/kernel_lge_g3
refs/heads/lp5.1
tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/SchedGui.py
12980
# SchedGui.py - Python extension for perf script, basic GUI code for # traces drawing and overview. # # Copyright (C) 2010 by Frederic Weisbecker <fweisbec@gmail.com> # # This software is distributed under the terms of the GNU General # Public License ("GPL") version 2 as published by the Free Software # Foundation. try: import wx except ImportError: raise ImportError, "You need to install the wxpython lib for this script" class RootFrame(wx.Frame): Y_OFFSET = 100 RECT_HEIGHT = 100 RECT_SPACE = 50 EVENT_MARKING_WIDTH = 5 def __init__(self, sched_tracer, title, parent = None, id = -1): wx.Frame.__init__(self, parent, id, title) (self.screen_width, self.screen_height) = wx.GetDisplaySize() self.screen_width -= 10 self.screen_height -= 10 self.zoom = 0.5 self.scroll_scale = 20 self.sched_tracer = sched_tracer self.sched_tracer.set_root_win(self) (self.ts_start, self.ts_end) = sched_tracer.interval() self.update_width_virtual() self.nr_rects = sched_tracer.nr_rectangles() + 1 self.height_virtual = RootFrame.Y_OFFSET + (self.nr_rects * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)) # whole window panel self.panel = wx.Panel(self, size=(self.screen_width, self.screen_height)) # scrollable container self.scroll = wx.ScrolledWindow(self.panel) self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale) self.scroll.EnableScrolling(True, True) self.scroll.SetFocus() # scrollable drawing area self.scroll_panel = wx.Panel(self.scroll, size=(self.screen_width - 15, self.screen_height / 2)) self.scroll_panel.Bind(wx.EVT_PAINT, self.on_paint) self.scroll_panel.Bind(wx.EVT_KEY_DOWN, self.on_key_press) self.scroll_panel.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down) self.scroll.Bind(wx.EVT_PAINT, self.on_paint) self.scroll.Bind(wx.EVT_KEY_DOWN, self.on_key_press) self.scroll.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down) self.scroll.Fit() self.Fit() self.scroll_panel.SetDimensions(-1, -1, self.width_virtual, self.height_virtual, wx.SIZE_USE_EXISTING) self.txt = None self.Show(True) def us_to_px(self, val): return val / (10 ** 3) * self.zoom def px_to_us(self, val): return (val / self.zoom) * (10 ** 3) def scroll_start(self): (x, y) = self.scroll.GetViewStart() return (x * self.scroll_scale, y * self.scroll_scale) def scroll_start_us(self): (x, y) = self.scroll_start() return self.px_to_us(x) def paint_rectangle_zone(self, nr, color, top_color, start, end): offset_px = self.us_to_px(start - self.ts_start) width_px = self.us_to_px(end - self.ts_start) offset_py = RootFrame.Y_OFFSET + (nr * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)) width_py = RootFrame.RECT_HEIGHT dc = self.dc if top_color is not None: (r, g, b) = top_color top_color = wx.Colour(r, g, b) brush = wx.Brush(top_color, wx.SOLID) dc.SetBrush(brush) dc.DrawRectangle(offset_px, offset_py, width_px, RootFrame.EVENT_MARKING_WIDTH) width_py -= RootFrame.EVENT_MARKING_WIDTH offset_py += RootFrame.EVENT_MARKING_WIDTH (r ,g, b) = color color = wx.Colour(r, g, b) brush = wx.Brush(color, wx.SOLID) dc.SetBrush(brush) dc.DrawRectangle(offset_px, offset_py, width_px, width_py) def update_rectangles(self, dc, start, end): start += self.ts_start end += self.ts_start self.sched_tracer.fill_zone(start, end) def on_paint(self, event): dc = wx.PaintDC(self.scroll_panel) self.dc = dc width = min(self.width_virtual, self.screen_width) (x, y) = self.scroll_start() start = self.px_to_us(x) end = self.px_to_us(x + width) self.update_rectangles(dc, start, end) def rect_from_ypixel(self, y): y -= RootFrame.Y_OFFSET rect = y / (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE) height = y % (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE) if rect < 0 or rect > self.nr_rects - 1 or height > RootFrame.RECT_HEIGHT: return -1 return rect def update_summary(self, txt): if self.txt: self.txt.Destroy() self.txt = wx.StaticText(self.panel, -1, txt, (0, (self.screen_height / 2) + 50)) def on_mouse_down(self, event): (x, y) = event.GetPositionTuple() rect = self.rect_from_ypixel(y) if rect == -1: return t = self.px_to_us(x) + self.ts_start self.sched_tracer.mouse_down(rect, t) def update_width_virtual(self): self.width_virtual = self.us_to_px(self.ts_end - self.ts_start) def __zoom(self, x): self.update_width_virtual() (xpos, ypos) = self.scroll.GetViewStart() xpos = self.us_to_px(x) / self.scroll_scale self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale, xpos, ypos) self.Refresh() def zoom_in(self): x = self.scroll_start_us() self.zoom *= 2 self.__zoom(x) def zoom_out(self): x = self.scroll_start_us() self.zoom /= 2 self.__zoom(x) def on_key_press(self, event): key = event.GetRawKeyCode() if key == ord("+"): self.zoom_in() return if key == ord("-"): self.zoom_out() return key = event.GetKeyCode() (x, y) = self.scroll.GetViewStart() if key == wx.WXK_RIGHT: self.scroll.Scroll(x + 1, y) elif key == wx.WXK_LEFT: self.scroll.Scroll(x - 1, y) elif key == wx.WXK_DOWN: self.scroll.Scroll(x, y + 1) elif key == wx.WXK_UP: self.scroll.Scroll(x, y - 1)
mikedlowis-prototypes/albase
refs/heads/master
source/kernel/tools/perf/scripts/python/export-to-postgresql.py
238
# export-to-postgresql.py: export perf data to a postgresql database # Copyright (c) 2014, Intel Corporation. # # This program is free software; you can redistribute it and/or modify it # under the terms and conditions of the GNU General Public License, # version 2, as published by the Free Software Foundation. # # This program is distributed in the hope 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. import os import sys import struct import datetime # To use this script you will need to have installed package python-pyside which # provides LGPL-licensed Python bindings for Qt. You will also need the package # libqt4-sql-psql for Qt postgresql support. # # The script assumes postgresql is running on the local machine and that the # user has postgresql permissions to create databases. Examples of installing # postgresql and adding such a user are: # # fedora: # # $ sudo yum install postgresql postgresql-server python-pyside qt-postgresql # $ sudo su - postgres -c initdb # $ sudo service postgresql start # $ sudo su - postgres # $ createuser <your user id here> # Shall the new role be a superuser? (y/n) y # # ubuntu: # # $ sudo apt-get install postgresql # $ sudo su - postgres # $ createuser <your user id here> # Shall the new role be a superuser? (y/n) y # # An example of using this script with Intel PT: # # $ perf record -e intel_pt//u ls # $ perf script -s ~/libexec/perf-core/scripts/python/export-to-postgresql.py pt_example branches calls # 2015-05-29 12:49:23.464364 Creating database... # 2015-05-29 12:49:26.281717 Writing to intermediate files... # 2015-05-29 12:49:27.190383 Copying to database... # 2015-05-29 12:49:28.140451 Removing intermediate files... # 2015-05-29 12:49:28.147451 Adding primary keys # 2015-05-29 12:49:28.655683 Adding foreign keys # 2015-05-29 12:49:29.365350 Done # # To browse the database, psql can be used e.g. # # $ psql pt_example # pt_example=# select * from samples_view where id < 100; # pt_example=# \d+ # pt_example=# \d+ samples_view # pt_example=# \q # # An example of using the database is provided by the script # call-graph-from-postgresql.py. Refer to that script for details. # # Tables: # # The tables largely correspond to perf tools' data structures. They are largely self-explanatory. # # samples # # 'samples' is the main table. It represents what instruction was executing at a point in time # when something (a selected event) happened. The memory address is the instruction pointer or 'ip'. # # calls # # 'calls' represents function calls and is related to 'samples' by 'call_id' and 'return_id'. # 'calls' is only created when the 'calls' option to this script is specified. # # call_paths # # 'call_paths' represents all the call stacks. Each 'call' has an associated record in 'call_paths'. # 'calls_paths' is only created when the 'calls' option to this script is specified. # # branch_types # # 'branch_types' provides descriptions for each type of branch. # # comm_threads # # 'comm_threads' shows how 'comms' relates to 'threads'. # # comms # # 'comms' contains a record for each 'comm' - the name given to the executable that is running. # # dsos # # 'dsos' contains a record for each executable file or library. # # machines # # 'machines' can be used to distinguish virtual machines if virtualization is supported. # # selected_events # # 'selected_events' contains a record for each kind of event that has been sampled. # # symbols # # 'symbols' contains a record for each symbol. Only symbols that have samples are present. # # threads # # 'threads' contains a record for each thread. # # Views: # # Most of the tables have views for more friendly display. The views are: # # calls_view # call_paths_view # comm_threads_view # dsos_view # machines_view # samples_view # symbols_view # threads_view # # More examples of browsing the database with psql: # Note that some of the examples are not the most optimal SQL query. # Note that call information is only available if the script's 'calls' option has been used. # # Top 10 function calls (not aggregated by symbol): # # SELECT * FROM calls_view ORDER BY elapsed_time DESC LIMIT 10; # # Top 10 function calls (aggregated by symbol): # # SELECT symbol_id,(SELECT name FROM symbols WHERE id = symbol_id) AS symbol, # SUM(elapsed_time) AS tot_elapsed_time,SUM(branch_count) AS tot_branch_count # FROM calls_view GROUP BY symbol_id ORDER BY tot_elapsed_time DESC LIMIT 10; # # Note that the branch count gives a rough estimation of cpu usage, so functions # that took a long time but have a relatively low branch count must have spent time # waiting. # # Find symbols by pattern matching on part of the name (e.g. names containing 'alloc'): # # SELECT * FROM symbols_view WHERE name LIKE '%alloc%'; # # Top 10 function calls for a specific symbol (e.g. whose symbol_id is 187): # # SELECT * FROM calls_view WHERE symbol_id = 187 ORDER BY elapsed_time DESC LIMIT 10; # # Show function calls made by function in the same context (i.e. same call path) (e.g. one with call_path_id 254): # # SELECT * FROM calls_view WHERE parent_call_path_id = 254; # # Show branches made during a function call (e.g. where call_id is 29357 and return_id is 29370 and tid is 29670) # # SELECT * FROM samples_view WHERE id >= 29357 AND id <= 29370 AND tid = 29670 AND event LIKE 'branches%'; # # Show transactions: # # SELECT * FROM samples_view WHERE event = 'transactions'; # # Note transaction start has 'in_tx' true whereas, transaction end has 'in_tx' false. # Transaction aborts have branch_type_name 'transaction abort' # # Show transaction aborts: # # SELECT * FROM samples_view WHERE event = 'transactions' AND branch_type_name = 'transaction abort'; # # To print a call stack requires walking the call_paths table. For example this python script: # #!/usr/bin/python2 # # import sys # from PySide.QtSql import * # # if __name__ == '__main__': # if (len(sys.argv) < 3): # print >> sys.stderr, "Usage is: printcallstack.py <database name> <call_path_id>" # raise Exception("Too few arguments") # dbname = sys.argv[1] # call_path_id = sys.argv[2] # db = QSqlDatabase.addDatabase('QPSQL') # db.setDatabaseName(dbname) # if not db.open(): # raise Exception("Failed to open database " + dbname + " error: " + db.lastError().text()) # query = QSqlQuery(db) # print " id ip symbol_id symbol dso_id dso_short_name" # while call_path_id != 0 and call_path_id != 1: # ret = query.exec_('SELECT * FROM call_paths_view WHERE id = ' + str(call_path_id)) # if not ret: # raise Exception("Query failed: " + query.lastError().text()) # if not query.next(): # raise Exception("Query failed") # print "{0:>6} {1:>10} {2:>9} {3:<30} {4:>6} {5:<30}".format(query.value(0), query.value(1), query.value(2), query.value(3), query.value(4), query.value(5)) # call_path_id = query.value(6) from PySide.QtSql import * # Need to access PostgreSQL C library directly to use COPY FROM STDIN from ctypes import * libpq = CDLL("libpq.so.5") PQconnectdb = libpq.PQconnectdb PQconnectdb.restype = c_void_p PQfinish = libpq.PQfinish PQstatus = libpq.PQstatus PQexec = libpq.PQexec PQexec.restype = c_void_p PQresultStatus = libpq.PQresultStatus PQputCopyData = libpq.PQputCopyData PQputCopyData.argtypes = [ c_void_p, c_void_p, c_int ] PQputCopyEnd = libpq.PQputCopyEnd PQputCopyEnd.argtypes = [ c_void_p, c_void_p ] sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') # These perf imports are not used at present #from perf_trace_context import * #from Core import * perf_db_export_mode = True perf_db_export_calls = False def usage(): print >> sys.stderr, "Usage is: export-to-postgresql.py <database name> [<columns>] [<calls>]" print >> sys.stderr, "where: columns 'all' or 'branches'" print >> sys.stderr, " calls 'calls' => create calls table" raise Exception("Too few arguments") if (len(sys.argv) < 2): usage() dbname = sys.argv[1] if (len(sys.argv) >= 3): columns = sys.argv[2] else: columns = "all" if columns not in ("all", "branches"): usage() branches = (columns == "branches") if (len(sys.argv) >= 4): if (sys.argv[3] == "calls"): perf_db_export_calls = True else: usage() output_dir_name = os.getcwd() + "/" + dbname + "-perf-data" os.mkdir(output_dir_name) def do_query(q, s): if (q.exec_(s)): return raise Exception("Query failed: " + q.lastError().text()) print datetime.datetime.today(), "Creating database..." db = QSqlDatabase.addDatabase('QPSQL') query = QSqlQuery(db) db.setDatabaseName('postgres') db.open() try: do_query(query, 'CREATE DATABASE ' + dbname) except: os.rmdir(output_dir_name) raise query.finish() query.clear() db.close() db.setDatabaseName(dbname) db.open() query = QSqlQuery(db) do_query(query, 'SET client_min_messages TO WARNING') do_query(query, 'CREATE TABLE selected_events (' 'id bigint NOT NULL,' 'name varchar(80))') do_query(query, 'CREATE TABLE machines (' 'id bigint NOT NULL,' 'pid integer,' 'root_dir varchar(4096))') do_query(query, 'CREATE TABLE threads (' 'id bigint NOT NULL,' 'machine_id bigint,' 'process_id bigint,' 'pid integer,' 'tid integer)') do_query(query, 'CREATE TABLE comms (' 'id bigint NOT NULL,' 'comm varchar(16))') do_query(query, 'CREATE TABLE comm_threads (' 'id bigint NOT NULL,' 'comm_id bigint,' 'thread_id bigint)') do_query(query, 'CREATE TABLE dsos (' 'id bigint NOT NULL,' 'machine_id bigint,' 'short_name varchar(256),' 'long_name varchar(4096),' 'build_id varchar(64))') do_query(query, 'CREATE TABLE symbols (' 'id bigint NOT NULL,' 'dso_id bigint,' 'sym_start bigint,' 'sym_end bigint,' 'binding integer,' 'name varchar(2048))') do_query(query, 'CREATE TABLE branch_types (' 'id integer NOT NULL,' 'name varchar(80))') if branches: do_query(query, 'CREATE TABLE samples (' 'id bigint NOT NULL,' 'evsel_id bigint,' 'machine_id bigint,' 'thread_id bigint,' 'comm_id bigint,' 'dso_id bigint,' 'symbol_id bigint,' 'sym_offset bigint,' 'ip bigint,' 'time bigint,' 'cpu integer,' 'to_dso_id bigint,' 'to_symbol_id bigint,' 'to_sym_offset bigint,' 'to_ip bigint,' 'branch_type integer,' 'in_tx boolean)') else: do_query(query, 'CREATE TABLE samples (' 'id bigint NOT NULL,' 'evsel_id bigint,' 'machine_id bigint,' 'thread_id bigint,' 'comm_id bigint,' 'dso_id bigint,' 'symbol_id bigint,' 'sym_offset bigint,' 'ip bigint,' 'time bigint,' 'cpu integer,' 'to_dso_id bigint,' 'to_symbol_id bigint,' 'to_sym_offset bigint,' 'to_ip bigint,' 'period bigint,' 'weight bigint,' 'transaction bigint,' 'data_src bigint,' 'branch_type integer,' 'in_tx boolean)') if perf_db_export_calls: do_query(query, 'CREATE TABLE call_paths (' 'id bigint NOT NULL,' 'parent_id bigint,' 'symbol_id bigint,' 'ip bigint)') do_query(query, 'CREATE TABLE calls (' 'id bigint NOT NULL,' 'thread_id bigint,' 'comm_id bigint,' 'call_path_id bigint,' 'call_time bigint,' 'return_time bigint,' 'branch_count bigint,' 'call_id bigint,' 'return_id bigint,' 'parent_call_path_id bigint,' 'flags integer)') do_query(query, 'CREATE VIEW machines_view AS ' 'SELECT ' 'id,' 'pid,' 'root_dir,' 'CASE WHEN id=0 THEN \'unknown\' WHEN pid=-1 THEN \'host\' ELSE \'guest\' END AS host_or_guest' ' FROM machines') do_query(query, 'CREATE VIEW dsos_view AS ' 'SELECT ' 'id,' 'machine_id,' '(SELECT host_or_guest FROM machines_view WHERE id = machine_id) AS host_or_guest,' 'short_name,' 'long_name,' 'build_id' ' FROM dsos') do_query(query, 'CREATE VIEW symbols_view AS ' 'SELECT ' 'id,' 'name,' '(SELECT short_name FROM dsos WHERE id=dso_id) AS dso,' 'dso_id,' 'sym_start,' 'sym_end,' 'CASE WHEN binding=0 THEN \'local\' WHEN binding=1 THEN \'global\' ELSE \'weak\' END AS binding' ' FROM symbols') do_query(query, 'CREATE VIEW threads_view AS ' 'SELECT ' 'id,' 'machine_id,' '(SELECT host_or_guest FROM machines_view WHERE id = machine_id) AS host_or_guest,' 'process_id,' 'pid,' 'tid' ' FROM threads') do_query(query, 'CREATE VIEW comm_threads_view AS ' 'SELECT ' 'comm_id,' '(SELECT comm FROM comms WHERE id = comm_id) AS command,' 'thread_id,' '(SELECT pid FROM threads WHERE id = thread_id) AS pid,' '(SELECT tid FROM threads WHERE id = thread_id) AS tid' ' FROM comm_threads') if perf_db_export_calls: do_query(query, 'CREATE VIEW call_paths_view AS ' 'SELECT ' 'c.id,' 'to_hex(c.ip) AS ip,' 'c.symbol_id,' '(SELECT name FROM symbols WHERE id = c.symbol_id) AS symbol,' '(SELECT dso_id FROM symbols WHERE id = c.symbol_id) AS dso_id,' '(SELECT dso FROM symbols_view WHERE id = c.symbol_id) AS dso_short_name,' 'c.parent_id,' 'to_hex(p.ip) AS parent_ip,' 'p.symbol_id AS parent_symbol_id,' '(SELECT name FROM symbols WHERE id = p.symbol_id) AS parent_symbol,' '(SELECT dso_id FROM symbols WHERE id = p.symbol_id) AS parent_dso_id,' '(SELECT dso FROM symbols_view WHERE id = p.symbol_id) AS parent_dso_short_name' ' FROM call_paths c INNER JOIN call_paths p ON p.id = c.parent_id') do_query(query, 'CREATE VIEW calls_view AS ' 'SELECT ' 'calls.id,' 'thread_id,' '(SELECT pid FROM threads WHERE id = thread_id) AS pid,' '(SELECT tid FROM threads WHERE id = thread_id) AS tid,' '(SELECT comm FROM comms WHERE id = comm_id) AS command,' 'call_path_id,' 'to_hex(ip) AS ip,' 'symbol_id,' '(SELECT name FROM symbols WHERE id = symbol_id) AS symbol,' 'call_time,' 'return_time,' 'return_time - call_time AS elapsed_time,' 'branch_count,' 'call_id,' 'return_id,' 'CASE WHEN flags=1 THEN \'no call\' WHEN flags=2 THEN \'no return\' WHEN flags=3 THEN \'no call/return\' ELSE \'\' END AS flags,' 'parent_call_path_id' ' FROM calls INNER JOIN call_paths ON call_paths.id = call_path_id') do_query(query, 'CREATE VIEW samples_view AS ' 'SELECT ' 'id,' 'time,' 'cpu,' '(SELECT pid FROM threads WHERE id = thread_id) AS pid,' '(SELECT tid FROM threads WHERE id = thread_id) AS tid,' '(SELECT comm FROM comms WHERE id = comm_id) AS command,' '(SELECT name FROM selected_events WHERE id = evsel_id) AS event,' 'to_hex(ip) AS ip_hex,' '(SELECT name FROM symbols WHERE id = symbol_id) AS symbol,' 'sym_offset,' '(SELECT short_name FROM dsos WHERE id = dso_id) AS dso_short_name,' 'to_hex(to_ip) AS to_ip_hex,' '(SELECT name FROM symbols WHERE id = to_symbol_id) AS to_symbol,' 'to_sym_offset,' '(SELECT short_name FROM dsos WHERE id = to_dso_id) AS to_dso_short_name,' '(SELECT name FROM branch_types WHERE id = branch_type) AS branch_type_name,' 'in_tx' ' FROM samples') file_header = struct.pack("!11sii", "PGCOPY\n\377\r\n\0", 0, 0) file_trailer = "\377\377" def open_output_file(file_name): path_name = output_dir_name + "/" + file_name file = open(path_name, "w+") file.write(file_header) return file def close_output_file(file): file.write(file_trailer) file.close() def copy_output_file_direct(file, table_name): close_output_file(file) sql = "COPY " + table_name + " FROM '" + file.name + "' (FORMAT 'binary')" do_query(query, sql) # Use COPY FROM STDIN because security may prevent postgres from accessing the files directly def copy_output_file(file, table_name): conn = PQconnectdb("dbname = " + dbname) if (PQstatus(conn)): raise Exception("COPY FROM STDIN PQconnectdb failed") file.write(file_trailer) file.seek(0) sql = "COPY " + table_name + " FROM STDIN (FORMAT 'binary')" res = PQexec(conn, sql) if (PQresultStatus(res) != 4): raise Exception("COPY FROM STDIN PQexec failed") data = file.read(65536) while (len(data)): ret = PQputCopyData(conn, data, len(data)) if (ret != 1): raise Exception("COPY FROM STDIN PQputCopyData failed, error " + str(ret)) data = file.read(65536) ret = PQputCopyEnd(conn, None) if (ret != 1): raise Exception("COPY FROM STDIN PQputCopyEnd failed, error " + str(ret)) PQfinish(conn) def remove_output_file(file): name = file.name file.close() os.unlink(name) evsel_file = open_output_file("evsel_table.bin") machine_file = open_output_file("machine_table.bin") thread_file = open_output_file("thread_table.bin") comm_file = open_output_file("comm_table.bin") comm_thread_file = open_output_file("comm_thread_table.bin") dso_file = open_output_file("dso_table.bin") symbol_file = open_output_file("symbol_table.bin") branch_type_file = open_output_file("branch_type_table.bin") sample_file = open_output_file("sample_table.bin") if perf_db_export_calls: call_path_file = open_output_file("call_path_table.bin") call_file = open_output_file("call_table.bin") def trace_begin(): print datetime.datetime.today(), "Writing to intermediate files..." # id == 0 means unknown. It is easier to create records for them than replace the zeroes with NULLs evsel_table(0, "unknown") machine_table(0, 0, "unknown") thread_table(0, 0, 0, -1, -1) comm_table(0, "unknown") dso_table(0, 0, "unknown", "unknown", "") symbol_table(0, 0, 0, 0, 0, "unknown") sample_table(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) if perf_db_export_calls: call_path_table(0, 0, 0, 0) unhandled_count = 0 def trace_end(): print datetime.datetime.today(), "Copying to database..." copy_output_file(evsel_file, "selected_events") copy_output_file(machine_file, "machines") copy_output_file(thread_file, "threads") copy_output_file(comm_file, "comms") copy_output_file(comm_thread_file, "comm_threads") copy_output_file(dso_file, "dsos") copy_output_file(symbol_file, "symbols") copy_output_file(branch_type_file, "branch_types") copy_output_file(sample_file, "samples") if perf_db_export_calls: copy_output_file(call_path_file, "call_paths") copy_output_file(call_file, "calls") print datetime.datetime.today(), "Removing intermediate files..." remove_output_file(evsel_file) remove_output_file(machine_file) remove_output_file(thread_file) remove_output_file(comm_file) remove_output_file(comm_thread_file) remove_output_file(dso_file) remove_output_file(symbol_file) remove_output_file(branch_type_file) remove_output_file(sample_file) if perf_db_export_calls: remove_output_file(call_path_file) remove_output_file(call_file) os.rmdir(output_dir_name) print datetime.datetime.today(), "Adding primary keys" do_query(query, 'ALTER TABLE selected_events ADD PRIMARY KEY (id)') do_query(query, 'ALTER TABLE machines ADD PRIMARY KEY (id)') do_query(query, 'ALTER TABLE threads ADD PRIMARY KEY (id)') do_query(query, 'ALTER TABLE comms ADD PRIMARY KEY (id)') do_query(query, 'ALTER TABLE comm_threads ADD PRIMARY KEY (id)') do_query(query, 'ALTER TABLE dsos ADD PRIMARY KEY (id)') do_query(query, 'ALTER TABLE symbols ADD PRIMARY KEY (id)') do_query(query, 'ALTER TABLE branch_types ADD PRIMARY KEY (id)') do_query(query, 'ALTER TABLE samples ADD PRIMARY KEY (id)') if perf_db_export_calls: do_query(query, 'ALTER TABLE call_paths ADD PRIMARY KEY (id)') do_query(query, 'ALTER TABLE calls ADD PRIMARY KEY (id)') print datetime.datetime.today(), "Adding foreign keys" do_query(query, 'ALTER TABLE threads ' 'ADD CONSTRAINT machinefk FOREIGN KEY (machine_id) REFERENCES machines (id),' 'ADD CONSTRAINT processfk FOREIGN KEY (process_id) REFERENCES threads (id)') do_query(query, 'ALTER TABLE comm_threads ' 'ADD CONSTRAINT commfk FOREIGN KEY (comm_id) REFERENCES comms (id),' 'ADD CONSTRAINT threadfk FOREIGN KEY (thread_id) REFERENCES threads (id)') do_query(query, 'ALTER TABLE dsos ' 'ADD CONSTRAINT machinefk FOREIGN KEY (machine_id) REFERENCES machines (id)') do_query(query, 'ALTER TABLE symbols ' 'ADD CONSTRAINT dsofk FOREIGN KEY (dso_id) REFERENCES dsos (id)') do_query(query, 'ALTER TABLE samples ' 'ADD CONSTRAINT evselfk FOREIGN KEY (evsel_id) REFERENCES selected_events (id),' 'ADD CONSTRAINT machinefk FOREIGN KEY (machine_id) REFERENCES machines (id),' 'ADD CONSTRAINT threadfk FOREIGN KEY (thread_id) REFERENCES threads (id),' 'ADD CONSTRAINT commfk FOREIGN KEY (comm_id) REFERENCES comms (id),' 'ADD CONSTRAINT dsofk FOREIGN KEY (dso_id) REFERENCES dsos (id),' 'ADD CONSTRAINT symbolfk FOREIGN KEY (symbol_id) REFERENCES symbols (id),' 'ADD CONSTRAINT todsofk FOREIGN KEY (to_dso_id) REFERENCES dsos (id),' 'ADD CONSTRAINT tosymbolfk FOREIGN KEY (to_symbol_id) REFERENCES symbols (id)') if perf_db_export_calls: do_query(query, 'ALTER TABLE call_paths ' 'ADD CONSTRAINT parentfk FOREIGN KEY (parent_id) REFERENCES call_paths (id),' 'ADD CONSTRAINT symbolfk FOREIGN KEY (symbol_id) REFERENCES symbols (id)') do_query(query, 'ALTER TABLE calls ' 'ADD CONSTRAINT threadfk FOREIGN KEY (thread_id) REFERENCES threads (id),' 'ADD CONSTRAINT commfk FOREIGN KEY (comm_id) REFERENCES comms (id),' 'ADD CONSTRAINT call_pathfk FOREIGN KEY (call_path_id) REFERENCES call_paths (id),' 'ADD CONSTRAINT callfk FOREIGN KEY (call_id) REFERENCES samples (id),' 'ADD CONSTRAINT returnfk FOREIGN KEY (return_id) REFERENCES samples (id),' 'ADD CONSTRAINT parent_call_pathfk FOREIGN KEY (parent_call_path_id) REFERENCES call_paths (id)') do_query(query, 'CREATE INDEX pcpid_idx ON calls (parent_call_path_id)') if (unhandled_count): print datetime.datetime.today(), "Warning: ", unhandled_count, " unhandled events" print datetime.datetime.today(), "Done" def trace_unhandled(event_name, context, event_fields_dict): global unhandled_count unhandled_count += 1 def sched__sched_switch(*x): pass def evsel_table(evsel_id, evsel_name, *x): n = len(evsel_name) fmt = "!hiqi" + str(n) + "s" value = struct.pack(fmt, 2, 8, evsel_id, n, evsel_name) evsel_file.write(value) def machine_table(machine_id, pid, root_dir, *x): n = len(root_dir) fmt = "!hiqiii" + str(n) + "s" value = struct.pack(fmt, 3, 8, machine_id, 4, pid, n, root_dir) machine_file.write(value) def thread_table(thread_id, machine_id, process_id, pid, tid, *x): value = struct.pack("!hiqiqiqiiii", 5, 8, thread_id, 8, machine_id, 8, process_id, 4, pid, 4, tid) thread_file.write(value) def comm_table(comm_id, comm_str, *x): n = len(comm_str) fmt = "!hiqi" + str(n) + "s" value = struct.pack(fmt, 2, 8, comm_id, n, comm_str) comm_file.write(value) def comm_thread_table(comm_thread_id, comm_id, thread_id, *x): fmt = "!hiqiqiq" value = struct.pack(fmt, 3, 8, comm_thread_id, 8, comm_id, 8, thread_id) comm_thread_file.write(value) def dso_table(dso_id, machine_id, short_name, long_name, build_id, *x): n1 = len(short_name) n2 = len(long_name) n3 = len(build_id) fmt = "!hiqiqi" + str(n1) + "si" + str(n2) + "si" + str(n3) + "s" value = struct.pack(fmt, 5, 8, dso_id, 8, machine_id, n1, short_name, n2, long_name, n3, build_id) dso_file.write(value) def symbol_table(symbol_id, dso_id, sym_start, sym_end, binding, symbol_name, *x): n = len(symbol_name) fmt = "!hiqiqiqiqiii" + str(n) + "s" value = struct.pack(fmt, 6, 8, symbol_id, 8, dso_id, 8, sym_start, 8, sym_end, 4, binding, n, symbol_name) symbol_file.write(value) def branch_type_table(branch_type, name, *x): n = len(name) fmt = "!hiii" + str(n) + "s" value = struct.pack(fmt, 2, 4, branch_type, n, name) branch_type_file.write(value) def sample_table(sample_id, evsel_id, machine_id, thread_id, comm_id, dso_id, symbol_id, sym_offset, ip, time, cpu, to_dso_id, to_symbol_id, to_sym_offset, to_ip, period, weight, transaction, data_src, branch_type, in_tx, *x): if branches: value = struct.pack("!hiqiqiqiqiqiqiqiqiqiqiiiqiqiqiqiiiB", 17, 8, sample_id, 8, evsel_id, 8, machine_id, 8, thread_id, 8, comm_id, 8, dso_id, 8, symbol_id, 8, sym_offset, 8, ip, 8, time, 4, cpu, 8, to_dso_id, 8, to_symbol_id, 8, to_sym_offset, 8, to_ip, 4, branch_type, 1, in_tx) else: value = struct.pack("!hiqiqiqiqiqiqiqiqiqiqiiiqiqiqiqiqiqiqiqiiiB", 21, 8, sample_id, 8, evsel_id, 8, machine_id, 8, thread_id, 8, comm_id, 8, dso_id, 8, symbol_id, 8, sym_offset, 8, ip, 8, time, 4, cpu, 8, to_dso_id, 8, to_symbol_id, 8, to_sym_offset, 8, to_ip, 8, period, 8, weight, 8, transaction, 8, data_src, 4, branch_type, 1, in_tx) sample_file.write(value) def call_path_table(cp_id, parent_id, symbol_id, ip, *x): fmt = "!hiqiqiqiq" value = struct.pack(fmt, 4, 8, cp_id, 8, parent_id, 8, symbol_id, 8, ip) call_path_file.write(value) def call_return_table(cr_id, thread_id, comm_id, call_path_id, call_time, return_time, branch_count, call_id, return_id, parent_call_path_id, flags, *x): fmt = "!hiqiqiqiqiqiqiqiqiqiqii" value = struct.pack(fmt, 11, 8, cr_id, 8, thread_id, 8, comm_id, 8, call_path_id, 8, call_time, 8, return_time, 8, branch_count, 8, call_id, 8, return_id, 8, parent_call_path_id, 4, flags) call_file.write(value)
billgreenwald/pgltools
refs/heads/master
Module/PyGLtools/__init__.py
1
# coding: utf-8 # In[2]: import browser as _brow import closest as _clos2d import closest1D as _clos1d import condense as _cond import conveRt as _conv import coverage as _cov import expand as _expa import findLoops as _fl import intersect as _inter2d import intersect1D as _inter1d import juicebox as _jb import merge as _mer import subtract as _subtr2d import subtract1D as _subtr1d import window as _wind import pgltools_library as _pgltl del pgltools_library # In[1]: def read_PGL(FilePath): """Takes a file path and returns a header and PyGL object of the pgl file. Recommended use is header,pgl=read_PGL(FilePath)""" return _pgltl.processFile(FilePath) # In[ ]: def read_Bed(FilePath): """Takes a file path and returns a header and PyGL-bed object of the pgl file. Recommended use is header,pgl=read_PGL(FilePath)""" return _pgltl.processBedFile(FilePath) # In[ ]: def _cs(pgl): return _pgltl.checkSorted(pgl) # In[56]: def pyglSort(PGL): """Takes a PyGL object and returns a sorted PyGL object""" return sorted(PGL,key=lambda x:(x[0],x[1],x[2],x[3],x[4],x[5])) # In[2]: def browser(PGL,N=0,S=0,P=0,Q=0,tN='pgl_track'): """Takes a PyGL object and returns a string formatted for the UCSC genome browser.""" return _brow.browser(PGL,N,S,P,Q,tN) # In[3]: def closest1D(PGL,BED,ba=False): """Takes a PyGL object and a PyGL-bed object and returns a PyGL object resulting from the closest1D operation""" args={'ba':ba} return _clos1d.closest1D(PGL,BED,args) # In[4]: def closest2D(A,B): """Takes two PyGL objects and returns a PyGL object resulting from the closest operation""" return _clos2d.closest2D(A,B) # In[72]: def condense(PGL,asObject=False): """Takes a PyGL object and returns a string or PyGL-bed object resulting from the condense operation""" t=[] for i in range(len(PGL)): t1=[str(y) for y in PGL[i][:6]] t1.extend([str(y) for y in PGL[i][6]]) t.append(t1) return _cond.condense(t,asObject=asObject) # In[6]: def conveRt(PGL,C=0,P=0,Q=0): """Takes a PyGL object and returns a string formatted by the conveRt operation""" args={'C':C,'P':0,'Q':0} return _conv.conveRt(PGL,args) # In[7]: def coverage(A,B,z=False): """Takes two PyGL objects and returns a PyGL object resulting from the coverage operation""" if _cs(A)!=0: print "A is not sorted. Please use a pyglSort." return if _cs(B)!=0: print "B is not sorted. Please use a pyglSort." return args={'z':z} return _cov.coverage(A,B,"",args) # In[8]: def expand(PGL,d=0,genome={}): """Takes a PyGL object and returns a PyGL object resulting from the expand operation""" args={'d':d} return _expa.expand(PGL,args,genome) # In[9]: def findLoops(PGL): """Takes a PyGL object and returns a PyGL-bed object resulting from the findLoops operation""" return _fl.findLoops(PGL) # In[10]: def intersect2D(A,B,d=0,v=False,bA=False,allA=False,m=False,mc=False,u=False,wa=False,wb=False,wo=False): """Takes two PyGL objects and returns a PyGL object resulting from the intersect operation""" if _cs(A)!=0: print "A is not sorted. Please use a pyglSort." return if _cs(B)!=0: print "B is not sorted. Please use a pyglSort." return args={'d':d,'v':v,'bA':bA,'allA':allA,'m':m,'mc':mc,'u':u,'wa':wa,'wb':wb,'wo':wo} return _inter2d.intersect2D(A,B,args,"") # In[11]: def intersect1D(PGL,BED,bA=False,allA=False,wa=False,wb=False,v=False,u=False,d=0): """Takes a PyGL object and a PyGL-bed object and returns a PyGL object resulting from the intersect1D operation""" if _cs(PGL)!=0: print "The PyGL supplied is not sorted. Please use a pyglSort." return args={'bA':bA,'allA':allA,'wa':wa,'wb':wb,'v':v,'u':u,'d':d,} return _inter1d.intersect1D(PGL,BED,args,"","") # In[12]: def juicebox(PGL,N=0,C=0): """Takes a PyGL object and returns a string formatted by the juicebox operation""" args={'N':N,'C':C} return _jb.juicebox(PGL,args) # In[13]: def merge(PGL,c="%#$",o="%#$",delim=',',d=0): """Takes a PyGL object and returns a PyGL object resulting from the merge operation""" if _cs(PGL)!=0: print "The PyGL supplied is not sorted. Please use a pyglSort." return args={'c':c,'o':o,'delim':delim,'d':d,'noH':True} return _mer.merge(PGL,args,"") # In[35]: def subtract2D(A,B): """Takes two PyGL objects and returns a PyGL object resulting from the subtract operation""" if _cs(A)!=0: print "A is not sorted. Please use a pyglSort." return if _cs(B)!=0: print "B is not sorted. Please use a pyglSort." return return _subtr2d.subtract2D(A,B,{},"") # In[46]: def subtract1D(PGL,BED): """Takes a PyGL object and a PyGL-bed object and returns a PyGL object resulting from the subtract1D operation""" if _cs(PGL)!=0: print "The PyGL supplied is not sorted. Please use a pyglSort." return return _subtr1d.subtract1D(PGL,BED,{},"") # In[50]: def window(PGL,window1="%#$",window2="%#$"): """Takes a PyGL object and returns a PyGL object resulting from the window operation""" args={'window1':window1,'window2':window2} return _wind.window(PGL,args)
axt/angr
refs/heads/master
angr/procedures/glibc/__libc_init.py
3
import angr ###################################### # __libc_init # # Refer to http://androidxref.com/5.1.1_r6/xref/bionic/libc/bionic/libc_init_dynamic.cpp # and http://androidxref.com/5.1.1_r6/xref/bionic/libc/private/KernelArgumentBlock.h # raw_args points to argc, *argv, and *envp located on the stack # unused is always zero # slingshot points to main() # structors points to PRE_INIT_ARRAY, INIT_ARRAY, and FINI_ARRAY ###################################### class __libc_init(angr.SimProcedure): #pylint:disable=arguments-differ,unused-argument,attribute-defined-outside-init ADDS_EXITS = True NO_RET = True IS_FUNCTION = True local_vars = ('main', 'argc', 'argv', 'envp') def run(self, raw_args, unused, slingshot, structors): offset = self.state.arch.bits / 8 readlen = self.state.arch.bits / 8 endness = self.state.arch.memory_endness self.main = slingshot self.argc = self.state.memory.load(raw_args + 0 * offset, readlen, endness=endness) argc_val = self.state.se.eval(self.argc) self.argv = self.state.memory.load(raw_args + 1 * offset, readlen, endness=endness) self.envp= self.state.memory.load(raw_args + (1 + argc_val + 1) * offset, readlen, endness=endness) # TODO: __cxa_atexit calls for various at-exit needs self.call(self.main, (self.argc, self.argv, self.envp), 'after_slingshot') def after_slingshot(self, raw_args, unused, slingshot, structors, exit_addr=0): self.exit(0)
nerzhul/ansible
refs/heads/devel
lib/ansible/modules/network/illumos/flowadm.py
48
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Adam Števko <adam.stevko@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: flowadm short_description: Manage bandwidth resource control and priority for protocols, services and zones. description: - Create/modify/remove networking bandwidth and associated resources for a type of traffic on a particular link. version_added: "2.2" author: Adam Števko (@xen0l) options: name: description: > - A flow is defined as a set of attributes based on Layer 3 and Layer 4 headers, which can be used to identify a protocol, service, or a zone. required: true aliases: [ 'flow' ] link: description: - Specifiies a link to configure flow on. required: false local_ip: description: - Identifies a network flow by the local IP address. required: false remove_ip: description: - Identifies a network flow by the remote IP address. required: false transport: description: > - Specifies a Layer 4 protocol to be used. It is typically used in combination with I(local_port) to identify the service that needs special attention. required: false local_port: description: - Identifies a service specified by the local port. required: false dsfield: description: > - Identifies the 8-bit differentiated services field (as defined in RFC 2474). The optional dsfield_mask is used to state the bits of interest in the differentiated services field when comparing with the dsfield value. Both values must be in hexadecimal. required: false maxbw: description: > - Sets the full duplex bandwidth for the flow. The bandwidth is specified as an integer with one of the scale suffixes(K, M, or G for Kbps, Mbps, and Gbps). If no units are specified, the input value will be read as Mbps. required: false priority: description: - Sets the relative priority for the flow. required: false default: 'medium' choices: [ 'low', 'medium', 'high' ] temporary: description: - Specifies that the configured flow is temporary. Temporary flows do not persist across reboots. required: false default: false choices: [ "true", "false" ] state: description: - Create/delete/enable/disable an IP address on the network interface. required: false default: present choices: [ 'absent', 'present', 'resetted' ] ''' EXAMPLES = ''' # Limit SSH traffic to 100M via vnic0 interface - flowadm: link: vnic0 flow: ssh_out transport: tcp local_port: 22 maxbw: 100M state: present # Reset flow properties - flowadm: name: dns state: resetted # Configure policy for EF PHB (DSCP value of 101110 from RFC 2598) with a bandwidth of 500 Mbps and a high priority. - flowadm: link: bge0 dsfield: '0x2e:0xfc' maxbw: 500M priority: high flow: efphb-flow state: present ''' RETURN = ''' name: description: flow name returned: always type: string sample: "http_drop" link: description: flow's link returned: if link is defined type: string sample: "vnic0" state: description: state of the target returned: always type: string sample: "present" temporary: description: flow's persistence returned: always type: boolean sample: "True" priority: description: flow's priority returned: if priority is defined type: string sample: "low" transport: description: flow's transport returned: if transport is defined type: string sample: "tcp" maxbw: description: flow's maximum bandwidth returned: if maxbw is defined type: string sample: "100M" local_Ip: description: flow's local IP address returned: if local_ip is defined type: string sample: "10.0.0.42" local_port: description: flow's local port returned: if local_port is defined type: int sample: 1337 remote_Ip: description: flow's remote IP address returned: if remote_ip is defined type: string sample: "10.0.0.42" dsfield: description: flow's differentiated services value returned: if dsfield is defined type: string sample: "0x2e:0xfc" ''' import socket SUPPORTED_TRANSPORTS = ['tcp', 'udp', 'sctp', 'icmp', 'icmpv6'] SUPPORTED_PRIORITIES = ['low', 'medium', 'high'] SUPPORTED_ATTRIBUTES = ['local_ip', 'remote_ip', 'transport', 'local_port', 'dsfield'] SUPPORTPED_PROPERTIES = ['maxbw', 'priority'] class Flow(object): def __init__(self, module): self.module = module self.name = module.params['name'] self.link = module.params['link'] self.local_ip = module.params['local_ip'] self.remote_ip = module.params['remote_ip'] self.transport = module.params['transport'] self.local_port = module.params['local_port'] self.dsfield = module.params['dsfield'] self.maxbw = module.params['maxbw'] self.priority = module.params['priority'] self.temporary = module.params['temporary'] self.state = module.params['state'] self._needs_updating = { 'maxbw': False, 'priority': False, } @classmethod def is_valid_port(cls, port): return 1 <= int(port) <= 65535 @classmethod def is_valid_address(cls, ip): if ip.count('/') == 1: ip_address, netmask = ip.split('/') else: ip_address = ip if len(ip_address.split('.')) == 4: try: socket.inet_pton(socket.AF_INET, ip_address) except socket.error: return False if not 0 <= netmask <= 32: return False else: try: socket.inet_pton(socket.AF_INET6, ip_address) except socket.error: return False if not 0 <= netmask <= 128: return False return True @classmethod def is_hex(cls, number): try: int(number, 16) except ValueError: return False return True @classmethod def is_valid_dsfield(cls, dsfield): dsmask = None if dsfield.count(':') == 1: dsval = dsfield.split(':')[0] else: dsval, dsmask = dsfield.split(':') if dsmask and not 0x01 <= int(dsmask, 16) <= 0xff and not 0x01 <= int(dsval, 16) <= 0xff: return False elif not 0x01 <= int(dsval, 16) <= 0xff: return False return True def flow_exists(self): cmd = [self.module.get_bin_path('flowadm')] cmd.append('show-flow') cmd.append(self.name) (rc, _, _) = self.module.run_command(cmd) if rc == 0: return True else: return False def delete_flow(self): cmd = [self.module.get_bin_path('flowadm')] cmd.append('remove-flow') if self.temporary: cmd.append('-t') cmd.append(self.name) return self.module.run_command(cmd) def create_flow(self): cmd = [self.module.get_bin_path('flowadm')] cmd.append('add-flow') cmd.append('-l') cmd.append(self.link) if self.local_ip: cmd.append('-a') cmd.append('local_ip=' + self.local_ip) if self.remote_ip: cmd.append('-a') cmd.append('remote_ip=' + self.remote_ip) if self.transport: cmd.append('-a') cmd.append('transport=' + self.transport) if self.local_port: cmd.append('-a') cmd.append('local_port=' + self.local_port) if self.dsfield: cmd.append('-a') cmd.append('dsfield=' + self.dsfield) if self.maxbw: cmd.append('-p') cmd.append('maxbw=' + self.maxbw) if self.priority: cmd.append('-p') cmd.append('priority=' + self.priority) if self.temporary: cmd.append('-t') cmd.append(self.name) return self.module.run_command(cmd) def _query_flow_props(self): cmd = [self.module.get_bin_path('flowadm')] cmd.append('show-flowprop') cmd.append('-c') cmd.append('-o') cmd.append('property,possible') cmd.append(self.name) return self.module.run_command(cmd) def flow_needs_udpating(self): (rc, out, err) = self._query_flow_props() NEEDS_UPDATING = False if rc == 0: properties = (line.split(':') for line in out.rstrip().split('\n')) for prop, value in properties: if prop == 'maxbw' and self.maxbw != value: self._needs_updating.update({prop: True}) NEEDS_UPDATING = True elif prop == 'priority' and self.priority != value: self._needs_updating.update({prop: True}) NEEDS_UPDATING = True return NEEDS_UPDATING else: self.module.fail_json(msg='Error while checking flow properties: %s' % err, stderr=err, rc=rc) def update_flow(self): cmd = [self.module.get_bin_path('flowadm')] cmd.append('set-flowprop') if self.maxbw and self._needs_updating['maxbw']: cmd.append('-p') cmd.append('maxbw=' + self.maxbw) if self.priority and self._needs_updating['priority']: cmd.append('-p') cmd.append('priority=' + self.priority) if self.temporary: cmd.append('-t') cmd.append(self.name) return self.module.run_command(cmd) def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True, aliases=['flow']), link=dict(required=False), local_ip=dict(required=False), remote_ip=dict(required=False), transport=dict(required=False, choices=SUPPORTED_TRANSPORTS), local_port=dict(required=False), dsfield=dict(required=False), maxbw=dict(required=False), priority=dict(required=False, default='medium', choices=SUPPORTED_PRIORITIES), temporary=dict(default=False, type='bool'), state=dict(required=False, default='present', choices=['absent', 'present', 'resetted']), ), mutually_exclusive=[ ('local_ip', 'remote_ip'), ('local_ip', 'transport'), ('local_ip', 'local_port'), ('local_ip', 'dsfield'), ('remote_ip', 'transport'), ('remote_ip', 'local_port'), ('remote_ip', 'dsfield'), ('transport', 'dsfield'), ('local_port', 'dsfield'), ], supports_check_mode=True ) flow = Flow(module) rc = None out = '' err = '' result = {} result['name'] = flow.name result['state'] = flow.state result['temporary'] = flow.temporary if flow.link: result['link'] = flow.link if flow.maxbw: result['maxbw'] = flow.maxbw if flow.priority: result['priority'] = flow.priority if flow.local_ip: if flow.is_valid_address(flow.local_ip): result['local_ip'] = flow.local_ip if flow.remote_ip: if flow.is_valid_address(flow.remote_ip): result['remote_ip'] = flow.remote_ip if flow.transport: result['transport'] = flow.transport if flow.local_port: if flow.is_valid_port(flow.local_port): result['local_port'] = flow.local_port else: module.fail_json(msg='Invalid port: %s' % flow.local_port, rc=1) if flow.dsfield: if flow.is_valid_dsfield(flow.dsfield): result['dsfield'] = flow.dsfield else: module.fail_json(msg='Invalid dsfield: %s' % flow.dsfield, rc=1) if flow.state == 'absent': if flow.flow_exists(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = flow.delete_flow() if rc != 0: module.fail_json(msg='Error while deleting flow: "%s"' % err, name=flow.name, stderr=err, rc=rc) elif flow.state == 'present': if not flow.flow_exists(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = flow.create_flow() if rc != 0: module.fail_json(msg='Error while creating flow: "%s"' % err, name=flow.name, stderr=err, rc=rc) else: if flow.flow_needs_udpating(): (rc, out, err) = flow.update_flow() if rc != 0: module.fail_json(msg='Error while updating flow: "%s"' % err, name=flow.name, stderr=err, rc=rc) elif flow.state == 'resetted': if flow.flow_exists(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = flow.reset_flow() if rc != 0: module.fail_json(msg='Error while resetting flow: "%s"' % err, name=flow.name, stderr=err, rc=rc) if rc is None: result['changed'] = False else: result['changed'] = True if out: result['stdout'] = out if err: result['stderr'] = err module.exit_json(**result) from ansible.module_utils.basic import * if __name__ == '__main__': main()
mtwharmby/lucky
refs/heads/master
Lucky/src_Mike_GUI_Total/start_lucky.py
1
''' Created on 3 Nov 2015 @author: wnm24546 ''' import sys from PyQt4 import QtGui # import Lucky.LuckyUIView from Lucky.AllViews import MainView if __name__ == '__main__': app = QtGui.QApplication(sys.argv) # lucky0 = Lucky.LuckyUIView.MainWindow() # lucky0.show() lucky = MainView() lucky.show() sys.exit(app.exec_())
Shanec132006/project
refs/heads/master
lib/flask/testsuite/test_apps/moduleapp/apps/frontend/__init__.py
628
from flask import Module, render_template frontend = Module(__name__) @frontend.route('/') def index(): return render_template('frontend/index.html')
marcydoty/geraldo
refs/heads/master
site/newsite/django_1_0/django/forms/formsets.py
11
from forms import Form from django.utils.encoding import StrAndUnicode from django.utils.safestring import mark_safe from fields import IntegerField, BooleanField from widgets import Media, HiddenInput from util import ErrorList, ValidationError __all__ = ('BaseFormSet', 'all_valid') # special field names TOTAL_FORM_COUNT = 'TOTAL_FORMS' INITIAL_FORM_COUNT = 'INITIAL_FORMS' ORDERING_FIELD_NAME = 'ORDER' DELETION_FIELD_NAME = 'DELETE' class ManagementForm(Form): """ ``ManagementForm`` is used to keep track of how many form instances are displayed on the page. If adding new forms via javascript, you should increment the count field of this form as well. """ def __init__(self, *args, **kwargs): self.base_fields[TOTAL_FORM_COUNT] = IntegerField(widget=HiddenInput) self.base_fields[INITIAL_FORM_COUNT] = IntegerField(widget=HiddenInput) super(ManagementForm, self).__init__(*args, **kwargs) class BaseFormSet(StrAndUnicode): """ A collection of instances of the same Form class. """ def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList): self.is_bound = data is not None or files is not None self.prefix = prefix or 'form' self.auto_id = auto_id self.data = data self.files = files self.initial = initial self.error_class = error_class self._errors = None self._non_form_errors = None # initialization is different depending on whether we recieved data, initial, or nothing if data or files: self.management_form = ManagementForm(data, auto_id=self.auto_id, prefix=self.prefix) if self.management_form.is_valid(): self._total_form_count = self.management_form.cleaned_data[TOTAL_FORM_COUNT] self._initial_form_count = self.management_form.cleaned_data[INITIAL_FORM_COUNT] else: raise ValidationError('ManagementForm data is missing or has been tampered with') else: if initial: self._initial_form_count = len(initial) if self._initial_form_count > self.max_num and self.max_num > 0: self._initial_form_count = self.max_num self._total_form_count = self._initial_form_count + self.extra else: self._initial_form_count = 0 self._total_form_count = self.extra if self._total_form_count > self.max_num and self.max_num > 0: self._total_form_count = self.max_num initial = {TOTAL_FORM_COUNT: self._total_form_count, INITIAL_FORM_COUNT: self._initial_form_count} self.management_form = ManagementForm(initial=initial, auto_id=self.auto_id, prefix=self.prefix) # construct the forms in the formset self._construct_forms() def __unicode__(self): return self.as_table() def _construct_forms(self): # instantiate all the forms and put them in self.forms self.forms = [] for i in xrange(self._total_form_count): self.forms.append(self._construct_form(i)) def _construct_form(self, i, **kwargs): """ Instantiates and returns the i-th form instance in a formset. """ defaults = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)} if self.data or self.files: defaults['data'] = self.data defaults['files'] = self.files if self.initial: try: defaults['initial'] = self.initial[i] except IndexError: pass # Allow extra forms to be empty. if i >= self._initial_form_count: defaults['empty_permitted'] = True defaults.update(kwargs) form = self.form(**defaults) self.add_fields(form, i) return form def _get_initial_forms(self): """Return a list of all the intial forms in this formset.""" return self.forms[:self._initial_form_count] initial_forms = property(_get_initial_forms) def _get_extra_forms(self): """Return a list of all the extra forms in this formset.""" return self.forms[self._initial_form_count:] extra_forms = property(_get_extra_forms) # Maybe this should just go away? def _get_cleaned_data(self): """ Returns a list of form.cleaned_data dicts for every form in self.forms. """ if not self.is_valid(): raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__) return [form.cleaned_data for form in self.forms] cleaned_data = property(_get_cleaned_data) def _get_deleted_forms(self): """ Returns a list of forms that have been marked for deletion. Raises an AttributeError is deletion is not allowed. """ if not self.is_valid() or not self.can_delete: raise AttributeError("'%s' object has no attribute 'deleted_forms'" % self.__class__.__name__) # construct _deleted_form_indexes which is just a list of form indexes # that have had their deletion widget set to True if not hasattr(self, '_deleted_form_indexes'): self._deleted_form_indexes = [] for i in range(0, self._total_form_count): form = self.forms[i] # if this is an extra form and hasn't changed, don't consider it if i >= self._initial_form_count and not form.has_changed(): continue if form.cleaned_data[DELETION_FIELD_NAME]: self._deleted_form_indexes.append(i) return [self.forms[i] for i in self._deleted_form_indexes] deleted_forms = property(_get_deleted_forms) def _get_ordered_forms(self): """ Returns a list of form in the order specified by the incoming data. Raises an AttributeError is deletion is not allowed. """ if not self.is_valid() or not self.can_order: raise AttributeError("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__) # Construct _ordering, which is a list of (form_index, order_field_value) # tuples. After constructing this list, we'll sort it by order_field_value # so we have a way to get to the form indexes in the order specified # by the form data. if not hasattr(self, '_ordering'): self._ordering = [] for i in range(0, self._total_form_count): form = self.forms[i] # if this is an extra form and hasn't changed, don't consider it if i >= self._initial_form_count and not form.has_changed(): continue # don't add data marked for deletion to self.ordered_data if self.can_delete and form.cleaned_data[DELETION_FIELD_NAME]: continue # A sort function to order things numerically ascending, but # None should be sorted below anything else. Allowing None as # a comparison value makes it so we can leave ordering fields # blamk. def compare_ordering_values(x, y): if x[1] is None: return 1 if y[1] is None: return -1 return x[1] - y[1] self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME])) # After we're done populating self._ordering, sort it. self._ordering.sort(compare_ordering_values) # Return a list of form.cleaned_data dicts in the order spcified by # the form data. return [self.forms[i[0]] for i in self._ordering] ordered_forms = property(_get_ordered_forms) def non_form_errors(self): """ Returns an ErrorList of errors that aren't associated with a particular form -- i.e., from formset.clean(). Returns an empty ErrorList if there are none. """ if self._non_form_errors is not None: return self._non_form_errors return self.error_class() def _get_errors(self): """ Returns a list of form.errors for every form in self.forms. """ if self._errors is None: self.full_clean() return self._errors errors = property(_get_errors) def is_valid(self): """ Returns True if form.errors is empty for every form in self.forms. """ if not self.is_bound: return False # We loop over every form.errors here rather than short circuiting on the # first failure to make sure validation gets triggered for every form. forms_valid = True for errors in self.errors: if bool(errors): forms_valid = False return forms_valid and not bool(self.non_form_errors()) def full_clean(self): """ Cleans all of self.data and populates self._errors. """ self._errors = [] if not self.is_bound: # Stop further processing. return for i in range(0, self._total_form_count): form = self.forms[i] self._errors.append(form.errors) # Give self.clean() a chance to do cross-form validation. try: self.clean() except ValidationError, e: self._non_form_errors = e.messages def clean(self): """ Hook for doing any extra formset-wide cleaning after Form.clean() has been called on every form. Any ValidationError raised by this method will not be associated with a particular form; it will be accesible via formset.non_form_errors() """ pass def add_fields(self, form, index): """A hook for adding extra fields on to each form instance.""" if self.can_order: # Only pre-fill the ordering field for initial forms. if index < self._initial_form_count: form.fields[ORDERING_FIELD_NAME] = IntegerField(label='Order', initial=index+1, required=False) else: form.fields[ORDERING_FIELD_NAME] = IntegerField(label='Order', required=False) if self.can_delete: form.fields[DELETION_FIELD_NAME] = BooleanField(label='Delete', required=False) def add_prefix(self, index): return '%s-%s' % (self.prefix, index) def is_multipart(self): """ Returns True if the formset needs to be multipart-encrypted, i.e. it has FileInput. Otherwise, False. """ return self.forms[0].is_multipart() def _get_media(self): # All the forms on a FormSet are the same, so you only need to # interrogate the first form for media. if self.forms: return self.forms[0].media else: return Media() media = property(_get_media) def as_table(self): "Returns this formset rendered as HTML <tr>s -- excluding the <table></table>." # XXX: there is no semantic division between forms here, there # probably should be. It might make sense to render each form as a # table row with each field as a td. forms = u' '.join([form.as_table() for form in self.forms]) return mark_safe(u'\n'.join([unicode(self.management_form), forms])) def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False, can_delete=False, max_num=0): """Return a FormSet for the given form class.""" attrs = {'form': form, 'extra': extra, 'can_order': can_order, 'can_delete': can_delete, 'max_num': max_num} return type(form.__name__ + 'FormSet', (formset,), attrs) def all_valid(formsets): """Returns true if every formset in formsets is valid.""" valid = True for formset in formsets: if not formset.is_valid(): valid = False return valid
MarkWh1te/xueqiu_predict
refs/heads/master
python3_env/lib/python3.4/site-packages/pygments/lexers/foxpro.py
47
# -*- coding: utf-8 -*- """ pygments.lexers.foxpro ~~~~~~~~~~~~~~~~~~~~~~ Simple lexer for Microsoft Visual FoxPro source code. :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer from pygments.token import Punctuation, Text, Comment, Operator, Keyword, \ Name, String __all__ = ['FoxProLexer'] class FoxProLexer(RegexLexer): """Lexer for Microsoft Visual FoxPro language. FoxPro syntax allows to shorten all keywords and function names to 4 characters. Shortened forms are not recognized by this lexer. .. versionadded:: 1.6 """ name = 'FoxPro' aliases = ['foxpro', 'vfp', 'clipper', 'xbase'] filenames = ['*.PRG', '*.prg'] mimetype = [] flags = re.IGNORECASE | re.MULTILINE tokens = { 'root': [ (r';\s*\n', Punctuation), # consume newline (r'(^|\n)\s*', Text, 'newline'), # Square brackets may be used for array indices # and for string literal. Look for arrays # before matching string literals. (r'(?<=\w)\[[0-9, ]+\]', Text), (r'\'[^\'\n]*\'|"[^"\n]*"|\[[^]*]\]', String), (r'(^\s*\*|&&|&amp;&amp;).*?\n', Comment.Single), (r'(ABS|ACLASS|ACOPY|ACOS|ADATABASES|ADBOBJECTS|ADDBS|' r'ADDPROPERTY|ADEL|ADIR|ADLLS|ADOCKSTATE|AELEMENT|AERROR|' r'AEVENTS|AFIELDS|AFONT|AGETCLASS|AGETFILEVERSION|AINS|' r'AINSTANCE|ALANGUAGE|ALEN|ALIAS|ALINES|ALLTRIM|' r'AMEMBERS|AMOUSEOBJ|ANETRESOURCES|APRINTERS|APROCINFO|' r'ASC|ASCAN|ASELOBJ|ASESSIONS|ASIN|ASORT|ASQLHANDLES|' r'ASTACKINFO|ASUBSCRIPT|AT|AT_C|ATAGINFO|ATAN|ATC|ATCC|' r'ATCLINE|ATLINE|ATN2|AUSED|AVCXCLASSES|BAR|BARCOUNT|' r'BARPROMPT|BETWEEN|BINDEVENT|BINTOC|BITAND|BITCLEAR|' r'BITLSHIFT|BITNOT|BITOR|BITRSHIFT|BITSET|BITTEST|BITXOR|' r'BOF|CANDIDATE|CAPSLOCK|CAST|CDOW|CDX|CEILING|CHR|CHRSAW|' r'CHRTRAN|CHRTRANC|CLEARRESULTSET|CMONTH|CNTBAR|CNTPAD|COL|' r'COM|Functions|COMARRAY|COMCLASSINFO|COMPOBJ|COMPROP|' r'COMRETURNERROR|COS|CPCONVERT|CPCURRENT|CPDBF|CREATEBINARY|' r'CREATEOBJECT|CREATEOBJECTEX|CREATEOFFLINE|CTOBIN|CTOD|' r'CTOT|CURDIR|CURSORGETPROP|CURSORSETPROP|CURSORTOXML|' r'CURVAL|DATE|DATETIME|DAY|DBC|DBF|DBGETPROP|DBSETPROP|' r'DBUSED|DDEAbortTrans|DDEAdvise|DDEEnabled|DDEExecute|' r'DDEInitiate|DDELastError|DDEPoke|DDERequest|DDESetOption|' r'DDESetService|DDESetTopic|DDETerminate|DEFAULTEXT|' r'DELETED|DESCENDING|DIFFERENCE|DIRECTORY|DISKSPACE|' r'DisplayPath|DMY|DODEFAULT|DOW|DRIVETYPE|DROPOFFLINE|' r'DTOC|DTOR|DTOS|DTOT|EDITSOURCE|EMPTY|EOF|ERROR|EVAL(UATE)?|' r'EVENTHANDLER|EVL|EXECSCRIPT|EXP|FCHSIZE|FCLOSE|FCOUNT|' r'FCREATE|FDATE|FEOF|FERROR|FFLUSH|FGETS|FIELD|FILE|' r'FILETOSTR|FILTER|FKLABEL|FKMAX|FLDLIST|FLOCK|FLOOR|' r'FONTMETRIC|FOPEN|FOR|FORCEEXT|FORCEPATH|FOUND|FPUTS|' r'FREAD|FSEEK|FSIZE|FTIME|FULLPATH|FV|FWRITE|' r'GETAUTOINCVALUE|GETBAR|GETCOLOR|GETCP|GETDIR|GETENV|' r'GETFILE|GETFLDSTATE|GETFONT|GETINTERFACE|' r'GETNEXTMODIFIED|GETOBJECT|GETPAD|GETPEM|GETPICT|' r'GETPRINTER|GETRESULTSET|GETWORDCOUNT|GETWORDNUM|' r'GETCURSORADAPTER|GOMONTH|HEADER|HOME|HOUR|ICASE|' r'IDXCOLLATE|IIF|IMESTATUS|INDBC|INDEXSEEK|INKEY|INLIST|' r'INPUTBOX|INSMODE|INT|ISALPHA|ISBLANK|ISCOLOR|ISDIGIT|' r'ISEXCLUSIVE|ISFLOCKED|ISLEADBYTE|ISLOWER|ISMEMOFETCHED|' r'ISMOUSE|ISNULL|ISPEN|ISREADONLY|ISRLOCKED|' r'ISTRANSACTABLE|ISUPPER|JUSTDRIVE|JUSTEXT|JUSTFNAME|' r'JUSTPATH|JUSTSTEM|KEY|KEYMATCH|LASTKEY|LEFT|LEFTC|LEN|' r'LENC|LIKE|LIKEC|LINENO|LOADPICTURE|LOCFILE|LOCK|LOG|' r'LOG10|LOOKUP|LOWER|LTRIM|LUPDATE|MAKETRANSACTABLE|MAX|' r'MCOL|MDOWN|MDX|MDY|MEMLINES|MEMORY|MENU|MESSAGE|' r'MESSAGEBOX|MIN|MINUTE|MLINE|MOD|MONTH|MRKBAR|MRKPAD|' r'MROW|MTON|MWINDOW|NDX|NEWOBJECT|NORMALIZE|NTOM|NUMLOCK|' r'NVL|OBJNUM|OBJTOCLIENT|OBJVAR|OCCURS|OEMTOANSI|OLDVAL|' r'ON|ORDER|OS|PAD|PADL|PARAMETERS|PAYMENT|PCOL|PCOUNT|' r'PEMSTATUS|PI|POPUP|PRIMARY|PRINTSTATUS|PRMBAR|PRMPAD|' r'PROGRAM|PROMPT|PROPER|PROW|PRTINFO|PUTFILE|PV|QUARTER|' r'RAISEEVENT|RAND|RAT|RATC|RATLINE|RDLEVEL|READKEY|RECCOUNT|' r'RECNO|RECSIZE|REFRESH|RELATION|REPLICATE|REQUERY|RGB|' r'RGBSCHEME|RIGHT|RIGHTC|RLOCK|ROUND|ROW|RTOD|RTRIM|' r'SAVEPICTURE|SCHEME|SCOLS|SEC|SECONDS|SEEK|SELECT|SET|' r'SETFLDSTATE|SETRESULTSET|SIGN|SIN|SKPBAR|SKPPAD|SOUNDEX|' r'SPACE|SQLCANCEL|SQLCOLUMNS|SQLCOMMIT|SQLCONNECT|' r'SQLDISCONNECT|SQLEXEC|SQLGETPROP|SQLIDLEDISCONNECT|' r'SQLMORERESULTS|SQLPREPARE|SQLROLLBACK|SQLSETPROP|' r'SQLSTRINGCONNECT|SQLTABLES|SQRT|SROWS|STR|STRCONV|' r'STREXTRACT|STRTOFILE|STRTRAN|STUFF|STUFFC|SUBSTR|' r'SUBSTRC|SYS|SYSMETRIC|TABLEREVERT|TABLEUPDATE|TAG|' r'TAGCOUNT|TAGNO|TAN|TARGET|TEXTMERGE|TIME|TRANSFORM|' r'TRIM|TTOC|TTOD|TXNLEVEL|TXTWIDTH|TYPE|UNBINDEVENTS|' r'UNIQUE|UPDATED|UPPER|USED|VAL|VARREAD|VARTYPE|VERSION|' r'WBORDER|WCHILD|WCOLS|WDOCKABLE|WEEK|WEXIST|WFONT|WLAST|' r'WLCOL|WLROW|WMAXIMUM|WMINIMUM|WONTOP|WOUTPUT|WPARENT|' r'WREAD|WROWS|WTITLE|WVISIBLE|XMLTOCURSOR|XMLUPDATEGRAM|' r'YEAR)(?=\s*\()', Name.Function), (r'_ALIGNMENT|_ASCIICOLS|_ASCIIROWS|_ASSIST|_BEAUTIFY|_BOX|' r'_BROWSER|_BUILDER|_CALCMEM|_CALCVALUE|_CLIPTEXT|_CONVERTER|' r'_COVERAGE|_CUROBJ|_DBLCLICK|_DIARYDATE|_DOS|_FOXDOC|_FOXREF|' r'_GALLERY|_GENGRAPH|_GENHTML|_GENMENU|_GENPD|_GENSCRN|' r'_GENXTAB|_GETEXPR|_INCLUDE|_INCSEEK|_INDENT|_LMARGIN|_MAC|' r'_MENUDESIGNER|_MLINE|_PADVANCE|_PAGENO|_PAGETOTAL|_PBPAGE|' r'_PCOLNO|_PCOPIES|_PDRIVER|_PDSETUP|_PECODE|_PEJECT|_PEPAGE|' r'_PLENGTH|_PLINENO|_PLOFFSET|_PPITCH|_PQUALITY|_PRETEXT|' r'_PSCODE|_PSPACING|_PWAIT|_RMARGIN|_REPORTBUILDER|' r'_REPORTOUTPUT|_REPORTPREVIEW|_SAMPLES|_SCCTEXT|_SCREEN|' r'_SHELL|_SPELLCHK|_STARTUP|_TABS|_TALLY|_TASKPANE|_TEXT|' r'_THROTTLE|_TOOLBOX|_TOOLTIPTIMEOUT|_TRANSPORT|_TRIGGERLEVEL|' r'_UNIX|_VFP|_WINDOWS|_WIZARD|_WRAP', Keyword.Pseudo), (r'THISFORMSET|THISFORM|THIS', Name.Builtin), (r'Application|CheckBox|Collection|Column|ComboBox|' r'CommandButton|CommandGroup|Container|Control|CursorAdapter|' r'Cursor|Custom|DataEnvironment|DataObject|EditBox|' r'Empty|Exception|Fields|Files|File|FormSet|Form|FoxCode|' r'Grid|Header|Hyperlink|Image|Label|Line|ListBox|Objects|' r'OptionButton|OptionGroup|PageFrame|Page|ProjectHook|Projects|' r'Project|Relation|ReportListener|Separator|Servers|Server|' r'Session|Shape|Spinner|Tables|TextBox|Timer|ToolBar|' r'XMLAdapter|XMLField|XMLTable', Name.Class), (r'm\.[a-z_]\w*', Name.Variable), (r'\.(F|T|AND|OR|NOT|NULL)\.|\b(AND|OR|NOT|NULL)\b', Operator.Word), (r'\.(ActiveColumn|ActiveControl|ActiveForm|ActivePage|' r'ActiveProject|ActiveRow|AddLineFeeds|ADOCodePage|Alias|' r'Alignment|Align|AllowAddNew|AllowAutoColumnFit|' r'AllowCellSelection|AllowDelete|AllowHeaderSizing|' r'AllowInsert|AllowModalMessages|AllowOutput|AllowRowSizing|' r'AllowSimultaneousFetch|AllowTabs|AllowUpdate|' r'AlwaysOnBottom|AlwaysOnTop|Anchor|Application|' r'AutoActivate|AutoCenter|AutoCloseTables|AutoComplete|' r'AutoCompSource|AutoCompTable|AutoHideScrollBar|' r'AutoIncrement|AutoOpenTables|AutoRelease|AutoSize|' r'AutoVerbMenu|AutoYield|BackColor|ForeColor|BackStyle|' r'BaseClass|BatchUpdateCount|BindControls|BorderColor|' r'BorderStyle|BorderWidth|BoundColumn|BoundTo|Bound|' r'BreakOnError|BufferModeOverride|BufferMode|' r'BuildDateTime|ButtonCount|Buttons|Cancel|Caption|' r'Centered|Century|ChildAlias|ChildOrder|ChildTable|' r'ClassLibrary|Class|ClipControls|Closable|CLSID|CodePage|' r'ColorScheme|ColorSource|ColumnCount|ColumnLines|' r'ColumnOrder|Columns|ColumnWidths|CommandClauses|' r'Comment|CompareMemo|ConflictCheckCmd|ConflictCheckType|' r'ContinuousScroll|ControlBox|ControlCount|Controls|' r'ControlSource|ConversionFunc|Count|CurrentControl|' r'CurrentDataSession|CurrentPass|CurrentX|CurrentY|' r'CursorSchema|CursorSource|CursorStatus|Curvature|' r'Database|DataSessionID|DataSession|DataSourceType|' r'DataSource|DataType|DateFormat|DateMark|Debug|' r'DeclareXMLPrefix|DEClassLibrary|DEClass|DefaultFilePath|' r'Default|DefOLELCID|DeleteCmdDataSourceType|DeleteCmdDataSource|' r'DeleteCmd|DeleteMark|Description|Desktop|' r'Details|DisabledBackColor|DisabledForeColor|' r'DisabledItemBackColor|DisabledItemForeColor|' r'DisabledPicture|DisableEncode|DisplayCount|' r'DisplayValue|Dockable|Docked|DockPosition|' r'DocumentFile|DownPicture|DragIcon|DragMode|DrawMode|' r'DrawStyle|DrawWidth|DynamicAlignment|DynamicBackColor|' r'DynamicForeColor|DynamicCurrentControl|DynamicFontBold|' r'DynamicFontItalic|DynamicFontStrikethru|' r'DynamicFontUnderline|DynamicFontName|DynamicFontOutline|' r'DynamicFontShadow|DynamicFontSize|DynamicInputMask|' r'DynamicLineHeight|EditorOptions|Enabled|' r'EnableHyperlinks|Encrypted|ErrorNo|Exclude|Exclusive|' r'FetchAsNeeded|FetchMemoCmdList|FetchMemoDataSourceType|' r'FetchMemoDataSource|FetchMemo|FetchSize|' r'FileClassLibrary|FileClass|FillColor|FillStyle|Filter|' r'FirstElement|FirstNestedTable|Flags|FontBold|FontItalic|' r'FontStrikethru|FontUnderline|FontCharSet|FontCondense|' r'FontExtend|FontName|FontOutline|FontShadow|FontSize|' r'ForceCloseTag|Format|FormCount|FormattedOutput|Forms|' r'FractionDigits|FRXDataSession|FullName|GDIPlusGraphics|' r'GridLineColor|GridLines|GridLineWidth|HalfHeightCaption|' r'HeaderClassLibrary|HeaderClass|HeaderHeight|Height|' r'HelpContextID|HideSelection|HighlightBackColor|' r'HighlightForeColor|HighlightStyle|HighlightRowLineWidth|' r'HighlightRow|Highlight|HomeDir|Hours|HostName|' r'HScrollSmallChange|hWnd|Icon|IncrementalSearch|Increment|' r'InitialSelectedAlias|InputMask|InsertCmdDataSourceType|' r'InsertCmdDataSource|InsertCmdRefreshCmd|' r'InsertCmdRefreshFieldList|InsertCmdRefreshKeyFieldList|' r'InsertCmd|Instancing|IntegralHeight|' r'Interval|IMEMode|IsAttribute|IsBase64|IsBinary|IsNull|' r'IsDiffGram|IsLoaded|ItemBackColor,|ItemData|ItemIDData|' r'ItemTips|IXMLDOMElement|KeyboardHighValue|KeyboardLowValue|' r'Keyfield|KeyFieldList|KeyPreview|KeySort|LanguageOptions|' r'LeftColumn|Left|LineContents|LineNo|LineSlant|LinkMaster|' r'ListCount|ListenerType|ListIndex|ListItemID|ListItem|' r'List|LockColumnsLeft|LockColumns|LockScreen|MacDesktop|' r'MainFile|MapN19_4ToCurrency|MapBinary|MapVarchar|Margin|' r'MaxButton|MaxHeight|MaxLeft|MaxLength|MaxRecords|MaxTop|' r'MaxWidth|MDIForm|MemberClassLibrary|MemberClass|' r'MemoWindow|Message|MinButton|MinHeight|MinWidth|' r'MouseIcon|MousePointer|Movable|MoverBars|MultiSelect|' r'Name|NestedInto|NewIndex|NewItemID|NextSiblingTable|' r'NoCpTrans|NoDataOnLoad|NoData|NullDisplay|' r'NumberOfElements|Object|OLEClass|OLEDragMode|' r'OLEDragPicture|OLEDropEffects|OLEDropHasData|' r'OLEDropMode|OLEDropTextInsertion|OLELCID|' r'OLERequestPendingTimeout|OLEServerBusyRaiseError|' r'OLEServerBusyTimeout|OLETypeAllowed|OneToMany|' r'OpenViews|OpenWindow|Optimize|OrderDirection|Order|' r'OutputPageCount|OutputType|PageCount|PageHeight|' r'PageNo|PageOrder|Pages|PageTotal|PageWidth|' r'PanelLink|Panel|ParentAlias|ParentClass|ParentTable|' r'Parent|Partition|PasswordChar|PictureMargin|' r'PicturePosition|PictureSpacing|PictureSelectionDisplay|' r'PictureVal|Picture|Prepared|' r'PolyPoints|PreserveWhiteSpace|PreviewContainer|' r'PrintJobName|Procedure|PROCESSID|ProgID|ProjectHookClass|' r'ProjectHookLibrary|ProjectHook|QuietMode|' r'ReadCycle|ReadLock|ReadMouse|ReadObject|ReadOnly|' r'ReadSave|ReadTimeout|RecordMark|RecordSourceType|' r'RecordSource|RefreshAlias|' r'RefreshCmdDataSourceType|RefreshCmdDataSource|RefreshCmd|' r'RefreshIgnoreFieldList|RefreshTimeStamp|RelationalExpr|' r'RelativeColumn|RelativeRow|ReleaseType|Resizable|' r'RespectCursorCP|RespectNesting|RightToLeft|RotateFlip|' r'Rotation|RowColChange|RowHeight|RowSourceType|' r'RowSource|ScaleMode|SCCProvider|SCCStatus|ScrollBars|' r'Seconds|SelectCmd|SelectedID|' r'SelectedItemBackColor|SelectedItemForeColor|Selected|' r'SelectionNamespaces|SelectOnEntry|SelLength|SelStart|' r'SelText|SendGDIPlusImage|SendUpdates|ServerClassLibrary|' r'ServerClass|ServerHelpFile|ServerName|' r'ServerProject|ShowTips|ShowInTaskbar|ShowWindow|' r'Sizable|SizeBox|SOM|Sorted|Sparse|SpecialEffect|' r'SpinnerHighValue|SpinnerLowValue|SplitBar|StackLevel|' r'StartMode|StatusBarText|StatusBar|Stretch|StrictDateEntry|' r'Style|TabIndex|Tables|TabOrientation|Tabs|TabStop|' r'TabStretch|TabStyle|Tag|TerminateRead|Text|Themes|' r'ThreadID|TimestampFieldList|TitleBar|ToolTipText|' r'TopIndex|TopItemID|Top|TwoPassProcess|TypeLibCLSID|' r'TypeLibDesc|TypeLibName|Type|Unicode|UpdatableFieldList|' r'UpdateCmdDataSourceType|UpdateCmdDataSource|' r'UpdateCmdRefreshCmd|UpdateCmdRefreshFieldList|' r'UpdateCmdRefreshKeyFieldList|UpdateCmd|' r'UpdateGramSchemaLocation|UpdateGram|UpdateNameList|UpdateType|' r'UseCodePage|UseCursorSchema|UseDeDataSource|UseMemoSize|' r'UserValue|UseTransactions|UTF8Encoded|Value|VersionComments|' r'VersionCompany|VersionCopyright|VersionDescription|' r'VersionNumber|VersionProduct|VersionTrademarks|Version|' r'VFPXMLProgID|ViewPortHeight|ViewPortLeft|' r'ViewPortTop|ViewPortWidth|VScrollSmallChange|View|Visible|' r'VisualEffect|WhatsThisButton|WhatsThisHelpID|WhatsThisHelp|' r'WhereType|Width|WindowList|WindowState|WindowType|WordWrap|' r'WrapCharInCDATA|WrapInCDATA|WrapMemoInCDATA|XMLAdapter|' r'XMLConstraints|XMLNameIsXPath|XMLNamespace|XMLName|' r'XMLPrefix|XMLSchemaLocation|XMLTable|XMLType|' r'XSDfractionDigits|XSDmaxLength|XSDtotalDigits|' r'XSDtype|ZoomBox)', Name.Attribute), (r'\.(ActivateCell|AddColumn|AddItem|AddListItem|AddObject|' r'AddProperty|AddTableSchema|AddToSCC|Add|' r'ApplyDiffgram|Attach|AutoFit|AutoOpen|Box|Build|' r'CancelReport|ChangesToCursor|CheckIn|CheckOut|Circle|' r'CleanUp|ClearData|ClearStatus|Clear|CloneObject|CloseTables|' r'Close|Cls|CursorAttach|CursorDetach|CursorFill|' r'CursorRefresh|DataToClip|DelayedMemoFetch|DeleteColumn|' r'Dock|DoMessage|DoScroll|DoStatus|DoVerb|Drag|Draw|Eval|' r'GetData|GetDockState|GetFormat|GetKey|GetLatestVersion|' r'GetPageHeight|GetPageWidth|Help|Hide|IncludePageInOutput|' r'IndexToItemID|ItemIDToIndex|Item|LoadXML|Line|Modify|' r'MoveItem|Move|Nest|OLEDrag|OnPreviewClose|OutputPage|' r'Point|Print|PSet|Quit|ReadExpression|ReadMethod|' r'RecordRefresh|Refresh|ReleaseXML|Release|RemoveFromSCC|' r'RemoveItem|RemoveListItem|RemoveObject|Remove|' r'Render|Requery|RequestData|ResetToDefault|Reset|Run|' r'SaveAsClass|SaveAs|SetAll|SetData|SetFocus|SetFormat|' r'SetMain|SetVar|SetViewPort|ShowWhatsThis|Show|' r'SupportsListenerType|TextHeight|TextWidth|ToCursor|' r'ToXML|UndoCheckOut|Unnest|UpdateStatus|WhatsThisMode|' r'WriteExpression|WriteMethod|ZOrder)', Name.Function), (r'\.(Activate|AdjustObjectSize|AfterBand|AfterBuild|' r'AfterCloseTables|AfterCursorAttach|AfterCursorClose|' r'AfterCursorDetach|AfterCursorFill|AfterCursorRefresh|' r'AfterCursorUpdate|AfterDelete|AfterInsert|' r'AfterRecordRefresh|AfterUpdate|AfterDock|AfterReport|' r'AfterRowColChange|BeforeBand|BeforeCursorAttach|' r'BeforeCursorClose|BeforeCursorDetach|BeforeCursorFill|' r'BeforeCursorRefresh|BeforeCursorUpdate|BeforeDelete|' r'BeforeInsert|BeforeDock|BeforeOpenTables|' r'BeforeRecordRefresh|BeforeReport|BeforeRowColChange|' r'BeforeUpdate|Click|dbc_Activate|dbc_AfterAddTable|' r'dbc_AfterAppendProc|dbc_AfterCloseTable|dbc_AfterCopyProc|' r'dbc_AfterCreateConnection|dbc_AfterCreateOffline|' r'dbc_AfterCreateTable|dbc_AfterCreateView|dbc_AfterDBGetProp|' r'dbc_AfterDBSetProp|dbc_AfterDeleteConnection|' r'dbc_AfterDropOffline|dbc_AfterDropTable|' r'dbc_AfterModifyConnection|dbc_AfterModifyProc|' r'dbc_AfterModifyTable|dbc_AfterModifyView|dbc_AfterOpenTable|' r'dbc_AfterRemoveTable|dbc_AfterRenameConnection|' r'dbc_AfterRenameTable|dbc_AfterRenameView|' r'dbc_AfterValidateData|dbc_BeforeAddTable|' r'dbc_BeforeAppendProc|dbc_BeforeCloseTable|' r'dbc_BeforeCopyProc|dbc_BeforeCreateConnection|' r'dbc_BeforeCreateOffline|dbc_BeforeCreateTable|' r'dbc_BeforeCreateView|dbc_BeforeDBGetProp|' r'dbc_BeforeDBSetProp|dbc_BeforeDeleteConnection|' r'dbc_BeforeDropOffline|dbc_BeforeDropTable|' r'dbc_BeforeModifyConnection|dbc_BeforeModifyProc|' r'dbc_BeforeModifyTable|dbc_BeforeModifyView|' r'dbc_BeforeOpenTable|dbc_BeforeRemoveTable|' r'dbc_BeforeRenameConnection|dbc_BeforeRenameTable|' r'dbc_BeforeRenameView|dbc_BeforeValidateData|' r'dbc_CloseData|dbc_Deactivate|dbc_ModifyData|dbc_OpenData|' r'dbc_PackData|DblClick|Deactivate|Deleted|Destroy|DoCmd|' r'DownClick|DragDrop|DragOver|DropDown|ErrorMessage|Error|' r'EvaluateContents|GotFocus|Init|InteractiveChange|KeyPress|' r'LoadReport|Load|LostFocus|Message|MiddleClick|MouseDown|' r'MouseEnter|MouseLeave|MouseMove|MouseUp|MouseWheel|Moved|' r'OLECompleteDrag|OLEDragOver|OLEGiveFeedback|OLESetData|' r'OLEStartDrag|OnMoveItem|Paint|ProgrammaticChange|' r'QueryAddFile|QueryModifyFile|QueryNewFile|QueryRemoveFile|' r'QueryRunFile|QueryUnload|RangeHigh|RangeLow|ReadActivate|' r'ReadDeactivate|ReadShow|ReadValid|ReadWhen|Resize|' r'RightClick|SCCInit|SCCDestroy|Scrolled|Timer|UIEnable|' r'UnDock|UnloadReport|Unload|UpClick|Valid|When)', Name.Function), (r'\s+', Text), # everything else is not colored (r'.', Text), ], 'newline': [ (r'\*.*?$', Comment.Single, '#pop'), (r'(ACCEPT|ACTIVATE\s*MENU|ACTIVATE\s*POPUP|ACTIVATE\s*SCREEN|' r'ACTIVATE\s*WINDOW|APPEND|APPEND\s*FROM|APPEND\s*FROM\s*ARRAY|' r'APPEND\s*GENERAL|APPEND\s*MEMO|ASSIST|AVERAGE|BLANK|BROWSE|' r'BUILD\s*APP|BUILD\s*EXE|BUILD\s*PROJECT|CALCULATE|CALL|' r'CANCEL|CHANGE|CLEAR|CLOSE|CLOSE\s*MEMO|COMPILE|CONTINUE|' r'COPY\s*FILE|COPY\s*INDEXES|COPY\s*MEMO|COPY\s*STRUCTURE|' r'COPY\s*STRUCTURE\s*EXTENDED|COPY\s*TAG|COPY\s*TO|' r'COPY\s*TO\s*ARRAY|COUNT|CREATE|CREATE\s*COLOR\s*SET|' r'CREATE\s*CURSOR|CREATE\s*FROM|CREATE\s*LABEL|CREATE\s*MENU|' r'CREATE\s*PROJECT|CREATE\s*QUERY|CREATE\s*REPORT|' r'CREATE\s*SCREEN|CREATE\s*TABLE|CREATE\s*VIEW|DDE|' r'DEACTIVATE\s*MENU|DEACTIVATE\s*POPUP|DEACTIVATE\s*WINDOW|' r'DECLARE|DEFINE\s*BAR|DEFINE\s*BOX|DEFINE\s*MENU|' r'DEFINE\s*PAD|DEFINE\s*POPUP|DEFINE\s*WINDOW|DELETE|' r'DELETE\s*FILE|DELETE\s*TAG|DIMENSION|DIRECTORY|DISPLAY|' r'DISPLAY\s*FILES|DISPLAY\s*MEMORY|DISPLAY\s*STATUS|' r'DISPLAY\s*STRUCTURE|DO|EDIT|EJECT|EJECT\s*PAGE|ERASE|' r'EXIT|EXPORT|EXTERNAL|FILER|FIND|FLUSH|FUNCTION|GATHER|' r'GETEXPR|GO|GOTO|HELP|HIDE\s*MENU|HIDE\s*POPUP|' r'HIDE\s*WINDOW|IMPORT|INDEX|INPUT|INSERT|JOIN|KEYBOARD|' r'LABEL|LIST|LOAD|LOCATE|LOOP|MENU|MENU\s*TO|MODIFY\s*COMMAND|' r'MODIFY\s*FILE|MODIFY\s*GENERAL|MODIFY\s*LABEL|MODIFY\s*MEMO|' r'MODIFY\s*MENU|MODIFY\s*PROJECT|MODIFY\s*QUERY|' r'MODIFY\s*REPORT|MODIFY\s*SCREEN|MODIFY\s*STRUCTURE|' r'MODIFY\s*WINDOW|MOVE\s*POPUP|MOVE\s*WINDOW|NOTE|' r'ON\s*APLABOUT|ON\s*BAR|ON\s*ERROR|ON\s*ESCAPE|' r'ON\s*EXIT\s*BAR|ON\s*EXIT\s*MENU|ON\s*EXIT\s*PAD|' r'ON\s*EXIT\s*POPUP|ON\s*KEY|ON\s*KEY\s*=|ON\s*KEY\s*LABEL|' r'ON\s*MACHELP|ON\s*PAD|ON\s*PAGE|ON\s*READERROR|' r'ON\s*SELECTION\s*BAR|ON\s*SELECTION\s*MENU|' r'ON\s*SELECTION\s*PAD|ON\s*SELECTION\s*POPUP|ON\s*SHUTDOWN|' r'PACK|PARAMETERS|PLAY\s*MACRO|POP\s*KEY|POP\s*MENU|' r'POP\s*POPUP|PRIVATE|PROCEDURE|PUBLIC|PUSH\s*KEY|' r'PUSH\s*MENU|PUSH\s*POPUP|QUIT|READ|READ\s*MENU|RECALL|' r'REINDEX|RELEASE|RELEASE\s*MODULE|RENAME|REPLACE|' r'REPLACE\s*FROM\s*ARRAY|REPORT|RESTORE\s*FROM|' r'RESTORE\s*MACROS|RESTORE\s*SCREEN|RESTORE\s*WINDOW|' r'RESUME|RETRY|RETURN|RUN|RUN\s*\/N"|RUNSCRIPT|' r'SAVE\s*MACROS|SAVE\s*SCREEN|SAVE\s*TO|SAVE\s*WINDOWS|' r'SCATTER|SCROLL|SEEK|SELECT|SET|SET\s*ALTERNATE|' r'SET\s*ANSI|SET\s*APLABOUT|SET\s*AUTOSAVE|SET\s*BELL|' r'SET\s*BLINK|SET\s*BLOCKSIZE|SET\s*BORDER|SET\s*BRSTATUS|' r'SET\s*CARRY|SET\s*CENTURY|SET\s*CLEAR|SET\s*CLOCK|' r'SET\s*COLLATE|SET\s*COLOR\s*OF|SET\s*COLOR\s*OF\s*SCHEME|' r'SET\s*COLOR\s*SET|SET\s*COLOR\s*TO|SET\s*COMPATIBLE|' r'SET\s*CONFIRM|SET\s*CONSOLE|SET\s*CURRENCY|SET\s*CURSOR|' r'SET\s*DATE|SET\s*DEBUG|SET\s*DECIMALS|SET\s*DEFAULT|' r'SET\s*DELETED|SET\s*DELIMITERS|SET\s*DEVELOPMENT|' r'SET\s*DEVICE|SET\s*DISPLAY|SET\s*DOHISTORY|SET\s*ECHO|' r'SET\s*ESCAPE|SET\s*EXACT|SET\s*EXCLUSIVE|SET\s*FIELDS|' r'SET\s*FILTER|SET\s*FIXED|SET\s*FORMAT|SET\s*FULLPATH|' r'SET\s*FUNCTION|SET\s*HEADINGS|SET\s*HELP|SET\s*HELPFILTER|' r'SET\s*HOURS|SET\s*INDEX|SET\s*INTENSITY|SET\s*KEY|' r'SET\s*KEYCOMP|SET\s*LIBRARY|SET\s*LOCK|SET\s*LOGERRORS|' r'SET\s*MACDESKTOP|SET\s*MACHELP|SET\s*MACKEY|SET\s*MARGIN|' r'SET\s*MARK\s*OF|SET\s*MARK\s*TO|SET\s*MEMOWIDTH|' r'SET\s*MESSAGE|SET\s*MOUSE|SET\s*MULTILOCKS|SET\s*NEAR|' r'SET\s*NOCPTRANS|SET\s*NOTIFY|SET\s*ODOMETER|SET\s*OPTIMIZE|' r'SET\s*ORDER|SET\s*PALETTE|SET\s*PATH|SET\s*PDSETUP|' r'SET\s*POINT|SET\s*PRINTER|SET\s*PROCEDURE|SET\s*READBORDER|' r'SET\s*REFRESH|SET\s*RELATION|SET\s*RELATION\s*OFF|' r'SET\s*REPROCESS|SET\s*RESOURCE|SET\s*SAFETY|SET\s*SCOREBOARD|' r'SET\s*SEPARATOR|SET\s*SHADOWS|SET\s*SKIP|SET\s*SKIP\s*OF|' r'SET\s*SPACE|SET\s*STATUS|SET\s*STATUS\s*BAR|SET\s*STEP|' r'SET\s*STICKY|SET\s*SYSMENU|SET\s*TALK|SET\s*TEXTMERGE|' r'SET\s*TEXTMERGE\s*DELIMITERS|SET\s*TOPIC|SET\s*TRBETWEEN|' r'SET\s*TYPEAHEAD|SET\s*UDFPARMS|SET\s*UNIQUE|SET\s*VIEW|' r'SET\s*VOLUME|SET\s*WINDOW\s*OF\s*MEMO|SET\s*XCMDFILE|' r'SHOW\s*GET|SHOW\s*GETS|SHOW\s*MENU|SHOW\s*OBJECT|' r'SHOW\s*POPUP|SHOW\s*WINDOW|SIZE\s*POPUP|SKIP|SORT|' r'STORE|SUM|SUSPEND|TOTAL|TYPE|UNLOCK|UPDATE|USE|WAIT|' r'ZAP|ZOOM\s*WINDOW|DO\s*CASE|CASE|OTHERWISE|ENDCASE|' r'DO\s*WHILE|ENDDO|FOR|ENDFOR|NEXT|IF|ELSE|ENDIF|PRINTJOB|' r'ENDPRINTJOB|SCAN|ENDSCAN|TEXT|ENDTEXT|=)', Keyword.Reserved, '#pop'), (r'#\s*(IF|ELIF|ELSE|ENDIF|DEFINE|IFDEF|IFNDEF|INCLUDE)', Comment.Preproc, '#pop'), (r'(m\.)?[a-z_]\w*', Name.Variable, '#pop'), (r'.', Text, '#pop'), ], }
samfoo/servo
refs/heads/master
tests/wpt/web-platform-tests/webdriver/navigation/forward.py
58
import unittest import sys import os sys.path.insert(1, os.path.abspath(os.path.join(__file__, "../.."))) import base_test class ForwardTest(base_test.WebDriverBaseTest): # Get a static page that must be the same upon refresh def test_forward(self): self.driver.get(self.webserver.where_is('navigation/res/forwardStart.html')) self.driver.get(self.webserver.where_is('navigation/res/forwardNext.html')) nextbody = self.driver.find_element_by_css("body").text self.driver.go_back() currbody = self.driver.find_element_by_css("body").text self.assertNotEqual(nextbody, currbody) self.driver.go_forward() currbody = self.driver.find_element_by_css("body").text self.assertEqual(nextbody, currbody) if __name__ == '__main__': unittest.main()
Salat-Cx65/python-for-android
refs/heads/master
python3-alpha/python3-src/Lib/encodings/cp1256.py
272
""" Python Character Mapping Codec cp1256 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1256.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp1256', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( '\x00' # 0x00 -> NULL '\x01' # 0x01 -> START OF HEADING '\x02' # 0x02 -> START OF TEXT '\x03' # 0x03 -> END OF TEXT '\x04' # 0x04 -> END OF TRANSMISSION '\x05' # 0x05 -> ENQUIRY '\x06' # 0x06 -> ACKNOWLEDGE '\x07' # 0x07 -> BELL '\x08' # 0x08 -> BACKSPACE '\t' # 0x09 -> HORIZONTAL TABULATION '\n' # 0x0A -> LINE FEED '\x0b' # 0x0B -> VERTICAL TABULATION '\x0c' # 0x0C -> FORM FEED '\r' # 0x0D -> CARRIAGE RETURN '\x0e' # 0x0E -> SHIFT OUT '\x0f' # 0x0F -> SHIFT IN '\x10' # 0x10 -> DATA LINK ESCAPE '\x11' # 0x11 -> DEVICE CONTROL ONE '\x12' # 0x12 -> DEVICE CONTROL TWO '\x13' # 0x13 -> DEVICE CONTROL THREE '\x14' # 0x14 -> DEVICE CONTROL FOUR '\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE '\x16' # 0x16 -> SYNCHRONOUS IDLE '\x17' # 0x17 -> END OF TRANSMISSION BLOCK '\x18' # 0x18 -> CANCEL '\x19' # 0x19 -> END OF MEDIUM '\x1a' # 0x1A -> SUBSTITUTE '\x1b' # 0x1B -> ESCAPE '\x1c' # 0x1C -> FILE SEPARATOR '\x1d' # 0x1D -> GROUP SEPARATOR '\x1e' # 0x1E -> RECORD SEPARATOR '\x1f' # 0x1F -> UNIT SEPARATOR ' ' # 0x20 -> SPACE '!' # 0x21 -> EXCLAMATION MARK '"' # 0x22 -> QUOTATION MARK '#' # 0x23 -> NUMBER SIGN '$' # 0x24 -> DOLLAR SIGN '%' # 0x25 -> PERCENT SIGN '&' # 0x26 -> AMPERSAND "'" # 0x27 -> APOSTROPHE '(' # 0x28 -> LEFT PARENTHESIS ')' # 0x29 -> RIGHT PARENTHESIS '*' # 0x2A -> ASTERISK '+' # 0x2B -> PLUS SIGN ',' # 0x2C -> COMMA '-' # 0x2D -> HYPHEN-MINUS '.' # 0x2E -> FULL STOP '/' # 0x2F -> SOLIDUS '0' # 0x30 -> DIGIT ZERO '1' # 0x31 -> DIGIT ONE '2' # 0x32 -> DIGIT TWO '3' # 0x33 -> DIGIT THREE '4' # 0x34 -> DIGIT FOUR '5' # 0x35 -> DIGIT FIVE '6' # 0x36 -> DIGIT SIX '7' # 0x37 -> DIGIT SEVEN '8' # 0x38 -> DIGIT EIGHT '9' # 0x39 -> DIGIT NINE ':' # 0x3A -> COLON ';' # 0x3B -> SEMICOLON '<' # 0x3C -> LESS-THAN SIGN '=' # 0x3D -> EQUALS SIGN '>' # 0x3E -> GREATER-THAN SIGN '?' # 0x3F -> QUESTION MARK '@' # 0x40 -> COMMERCIAL AT 'A' # 0x41 -> LATIN CAPITAL LETTER A 'B' # 0x42 -> LATIN CAPITAL LETTER B 'C' # 0x43 -> LATIN CAPITAL LETTER C 'D' # 0x44 -> LATIN CAPITAL LETTER D 'E' # 0x45 -> LATIN CAPITAL LETTER E 'F' # 0x46 -> LATIN CAPITAL LETTER F 'G' # 0x47 -> LATIN CAPITAL LETTER G 'H' # 0x48 -> LATIN CAPITAL LETTER H 'I' # 0x49 -> LATIN CAPITAL LETTER I 'J' # 0x4A -> LATIN CAPITAL LETTER J 'K' # 0x4B -> LATIN CAPITAL LETTER K 'L' # 0x4C -> LATIN CAPITAL LETTER L 'M' # 0x4D -> LATIN CAPITAL LETTER M 'N' # 0x4E -> LATIN CAPITAL LETTER N 'O' # 0x4F -> LATIN CAPITAL LETTER O 'P' # 0x50 -> LATIN CAPITAL LETTER P 'Q' # 0x51 -> LATIN CAPITAL LETTER Q 'R' # 0x52 -> LATIN CAPITAL LETTER R 'S' # 0x53 -> LATIN CAPITAL LETTER S 'T' # 0x54 -> LATIN CAPITAL LETTER T 'U' # 0x55 -> LATIN CAPITAL LETTER U 'V' # 0x56 -> LATIN CAPITAL LETTER V 'W' # 0x57 -> LATIN CAPITAL LETTER W 'X' # 0x58 -> LATIN CAPITAL LETTER X 'Y' # 0x59 -> LATIN CAPITAL LETTER Y 'Z' # 0x5A -> LATIN CAPITAL LETTER Z '[' # 0x5B -> LEFT SQUARE BRACKET '\\' # 0x5C -> REVERSE SOLIDUS ']' # 0x5D -> RIGHT SQUARE BRACKET '^' # 0x5E -> CIRCUMFLEX ACCENT '_' # 0x5F -> LOW LINE '`' # 0x60 -> GRAVE ACCENT 'a' # 0x61 -> LATIN SMALL LETTER A 'b' # 0x62 -> LATIN SMALL LETTER B 'c' # 0x63 -> LATIN SMALL LETTER C 'd' # 0x64 -> LATIN SMALL LETTER D 'e' # 0x65 -> LATIN SMALL LETTER E 'f' # 0x66 -> LATIN SMALL LETTER F 'g' # 0x67 -> LATIN SMALL LETTER G 'h' # 0x68 -> LATIN SMALL LETTER H 'i' # 0x69 -> LATIN SMALL LETTER I 'j' # 0x6A -> LATIN SMALL LETTER J 'k' # 0x6B -> LATIN SMALL LETTER K 'l' # 0x6C -> LATIN SMALL LETTER L 'm' # 0x6D -> LATIN SMALL LETTER M 'n' # 0x6E -> LATIN SMALL LETTER N 'o' # 0x6F -> LATIN SMALL LETTER O 'p' # 0x70 -> LATIN SMALL LETTER P 'q' # 0x71 -> LATIN SMALL LETTER Q 'r' # 0x72 -> LATIN SMALL LETTER R 's' # 0x73 -> LATIN SMALL LETTER S 't' # 0x74 -> LATIN SMALL LETTER T 'u' # 0x75 -> LATIN SMALL LETTER U 'v' # 0x76 -> LATIN SMALL LETTER V 'w' # 0x77 -> LATIN SMALL LETTER W 'x' # 0x78 -> LATIN SMALL LETTER X 'y' # 0x79 -> LATIN SMALL LETTER Y 'z' # 0x7A -> LATIN SMALL LETTER Z '{' # 0x7B -> LEFT CURLY BRACKET '|' # 0x7C -> VERTICAL LINE '}' # 0x7D -> RIGHT CURLY BRACKET '~' # 0x7E -> TILDE '\x7f' # 0x7F -> DELETE '\u20ac' # 0x80 -> EURO SIGN '\u067e' # 0x81 -> ARABIC LETTER PEH '\u201a' # 0x82 -> SINGLE LOW-9 QUOTATION MARK '\u0192' # 0x83 -> LATIN SMALL LETTER F WITH HOOK '\u201e' # 0x84 -> DOUBLE LOW-9 QUOTATION MARK '\u2026' # 0x85 -> HORIZONTAL ELLIPSIS '\u2020' # 0x86 -> DAGGER '\u2021' # 0x87 -> DOUBLE DAGGER '\u02c6' # 0x88 -> MODIFIER LETTER CIRCUMFLEX ACCENT '\u2030' # 0x89 -> PER MILLE SIGN '\u0679' # 0x8A -> ARABIC LETTER TTEH '\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK '\u0152' # 0x8C -> LATIN CAPITAL LIGATURE OE '\u0686' # 0x8D -> ARABIC LETTER TCHEH '\u0698' # 0x8E -> ARABIC LETTER JEH '\u0688' # 0x8F -> ARABIC LETTER DDAL '\u06af' # 0x90 -> ARABIC LETTER GAF '\u2018' # 0x91 -> LEFT SINGLE QUOTATION MARK '\u2019' # 0x92 -> RIGHT SINGLE QUOTATION MARK '\u201c' # 0x93 -> LEFT DOUBLE QUOTATION MARK '\u201d' # 0x94 -> RIGHT DOUBLE QUOTATION MARK '\u2022' # 0x95 -> BULLET '\u2013' # 0x96 -> EN DASH '\u2014' # 0x97 -> EM DASH '\u06a9' # 0x98 -> ARABIC LETTER KEHEH '\u2122' # 0x99 -> TRADE MARK SIGN '\u0691' # 0x9A -> ARABIC LETTER RREH '\u203a' # 0x9B -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK '\u0153' # 0x9C -> LATIN SMALL LIGATURE OE '\u200c' # 0x9D -> ZERO WIDTH NON-JOINER '\u200d' # 0x9E -> ZERO WIDTH JOINER '\u06ba' # 0x9F -> ARABIC LETTER NOON GHUNNA '\xa0' # 0xA0 -> NO-BREAK SPACE '\u060c' # 0xA1 -> ARABIC COMMA '\xa2' # 0xA2 -> CENT SIGN '\xa3' # 0xA3 -> POUND SIGN '\xa4' # 0xA4 -> CURRENCY SIGN '\xa5' # 0xA5 -> YEN SIGN '\xa6' # 0xA6 -> BROKEN BAR '\xa7' # 0xA7 -> SECTION SIGN '\xa8' # 0xA8 -> DIAERESIS '\xa9' # 0xA9 -> COPYRIGHT SIGN '\u06be' # 0xAA -> ARABIC LETTER HEH DOACHASHMEE '\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK '\xac' # 0xAC -> NOT SIGN '\xad' # 0xAD -> SOFT HYPHEN '\xae' # 0xAE -> REGISTERED SIGN '\xaf' # 0xAF -> MACRON '\xb0' # 0xB0 -> DEGREE SIGN '\xb1' # 0xB1 -> PLUS-MINUS SIGN '\xb2' # 0xB2 -> SUPERSCRIPT TWO '\xb3' # 0xB3 -> SUPERSCRIPT THREE '\xb4' # 0xB4 -> ACUTE ACCENT '\xb5' # 0xB5 -> MICRO SIGN '\xb6' # 0xB6 -> PILCROW SIGN '\xb7' # 0xB7 -> MIDDLE DOT '\xb8' # 0xB8 -> CEDILLA '\xb9' # 0xB9 -> SUPERSCRIPT ONE '\u061b' # 0xBA -> ARABIC SEMICOLON '\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK '\xbc' # 0xBC -> VULGAR FRACTION ONE QUARTER '\xbd' # 0xBD -> VULGAR FRACTION ONE HALF '\xbe' # 0xBE -> VULGAR FRACTION THREE QUARTERS '\u061f' # 0xBF -> ARABIC QUESTION MARK '\u06c1' # 0xC0 -> ARABIC LETTER HEH GOAL '\u0621' # 0xC1 -> ARABIC LETTER HAMZA '\u0622' # 0xC2 -> ARABIC LETTER ALEF WITH MADDA ABOVE '\u0623' # 0xC3 -> ARABIC LETTER ALEF WITH HAMZA ABOVE '\u0624' # 0xC4 -> ARABIC LETTER WAW WITH HAMZA ABOVE '\u0625' # 0xC5 -> ARABIC LETTER ALEF WITH HAMZA BELOW '\u0626' # 0xC6 -> ARABIC LETTER YEH WITH HAMZA ABOVE '\u0627' # 0xC7 -> ARABIC LETTER ALEF '\u0628' # 0xC8 -> ARABIC LETTER BEH '\u0629' # 0xC9 -> ARABIC LETTER TEH MARBUTA '\u062a' # 0xCA -> ARABIC LETTER TEH '\u062b' # 0xCB -> ARABIC LETTER THEH '\u062c' # 0xCC -> ARABIC LETTER JEEM '\u062d' # 0xCD -> ARABIC LETTER HAH '\u062e' # 0xCE -> ARABIC LETTER KHAH '\u062f' # 0xCF -> ARABIC LETTER DAL '\u0630' # 0xD0 -> ARABIC LETTER THAL '\u0631' # 0xD1 -> ARABIC LETTER REH '\u0632' # 0xD2 -> ARABIC LETTER ZAIN '\u0633' # 0xD3 -> ARABIC LETTER SEEN '\u0634' # 0xD4 -> ARABIC LETTER SHEEN '\u0635' # 0xD5 -> ARABIC LETTER SAD '\u0636' # 0xD6 -> ARABIC LETTER DAD '\xd7' # 0xD7 -> MULTIPLICATION SIGN '\u0637' # 0xD8 -> ARABIC LETTER TAH '\u0638' # 0xD9 -> ARABIC LETTER ZAH '\u0639' # 0xDA -> ARABIC LETTER AIN '\u063a' # 0xDB -> ARABIC LETTER GHAIN '\u0640' # 0xDC -> ARABIC TATWEEL '\u0641' # 0xDD -> ARABIC LETTER FEH '\u0642' # 0xDE -> ARABIC LETTER QAF '\u0643' # 0xDF -> ARABIC LETTER KAF '\xe0' # 0xE0 -> LATIN SMALL LETTER A WITH GRAVE '\u0644' # 0xE1 -> ARABIC LETTER LAM '\xe2' # 0xE2 -> LATIN SMALL LETTER A WITH CIRCUMFLEX '\u0645' # 0xE3 -> ARABIC LETTER MEEM '\u0646' # 0xE4 -> ARABIC LETTER NOON '\u0647' # 0xE5 -> ARABIC LETTER HEH '\u0648' # 0xE6 -> ARABIC LETTER WAW '\xe7' # 0xE7 -> LATIN SMALL LETTER C WITH CEDILLA '\xe8' # 0xE8 -> LATIN SMALL LETTER E WITH GRAVE '\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE '\xea' # 0xEA -> LATIN SMALL LETTER E WITH CIRCUMFLEX '\xeb' # 0xEB -> LATIN SMALL LETTER E WITH DIAERESIS '\u0649' # 0xEC -> ARABIC LETTER ALEF MAKSURA '\u064a' # 0xED -> ARABIC LETTER YEH '\xee' # 0xEE -> LATIN SMALL LETTER I WITH CIRCUMFLEX '\xef' # 0xEF -> LATIN SMALL LETTER I WITH DIAERESIS '\u064b' # 0xF0 -> ARABIC FATHATAN '\u064c' # 0xF1 -> ARABIC DAMMATAN '\u064d' # 0xF2 -> ARABIC KASRATAN '\u064e' # 0xF3 -> ARABIC FATHA '\xf4' # 0xF4 -> LATIN SMALL LETTER O WITH CIRCUMFLEX '\u064f' # 0xF5 -> ARABIC DAMMA '\u0650' # 0xF6 -> ARABIC KASRA '\xf7' # 0xF7 -> DIVISION SIGN '\u0651' # 0xF8 -> ARABIC SHADDA '\xf9' # 0xF9 -> LATIN SMALL LETTER U WITH GRAVE '\u0652' # 0xFA -> ARABIC SUKUN '\xfb' # 0xFB -> LATIN SMALL LETTER U WITH CIRCUMFLEX '\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS '\u200e' # 0xFD -> LEFT-TO-RIGHT MARK '\u200f' # 0xFE -> RIGHT-TO-LEFT MARK '\u06d2' # 0xFF -> ARABIC LETTER YEH BARREE ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
rgerkin/neuroConstruct
refs/heads/master
lib/jython/Lib/test/autotest.py
420
# This should be equivalent to running regrtest.py from the cmdline. # It can be especially handy if you're in an interactive shell, e.g., # from test import autotest. from test import regrtest regrtest.main()
wd5/jangr
refs/heads/master
_django/contrib/gis/geos/polygon.py
321
from ctypes import c_uint, byref from django.contrib.gis.geos.error import GEOSIndexError from django.contrib.gis.geos.geometry import GEOSGeometry from django.contrib.gis.geos.libgeos import get_pointer_arr, GEOM_PTR from django.contrib.gis.geos.linestring import LinearRing from django.contrib.gis.geos import prototypes as capi class Polygon(GEOSGeometry): _minlength = 1 def __init__(self, *args, **kwargs): """ Initializes on an exterior ring and a sequence of holes (both instances may be either LinearRing instances, or a tuple/list that may be constructed into a LinearRing). Examples of initialization, where shell, hole1, and hole2 are valid LinearRing geometries: >>> poly = Polygon(shell, hole1, hole2) >>> poly = Polygon(shell, (hole1, hole2)) Example where a tuple parameters are used: >>> poly = Polygon(((0, 0), (0, 10), (10, 10), (0, 10), (0, 0)), ((4, 4), (4, 6), (6, 6), (6, 4), (4, 4))) """ if not args: raise TypeError('Must provide at least one LinearRing, or a tuple, to initialize a Polygon.') # Getting the ext_ring and init_holes parameters from the argument list ext_ring = args[0] init_holes = args[1:] n_holes = len(init_holes) # If initialized as Polygon(shell, (LinearRing, LinearRing)) [for backward-compatibility] if n_holes == 1 and isinstance(init_holes[0], (tuple, list)): if len(init_holes[0]) == 0: init_holes = () n_holes = 0 elif isinstance(init_holes[0][0], LinearRing): init_holes = init_holes[0] n_holes = len(init_holes) polygon = self._create_polygon(n_holes + 1, (ext_ring,) + init_holes) super(Polygon, self).__init__(polygon, **kwargs) def __iter__(self): "Iterates over each ring in the polygon." for i in xrange(len(self)): yield self[i] def __len__(self): "Returns the number of rings in this Polygon." return self.num_interior_rings + 1 @classmethod def from_bbox(cls, bbox): "Constructs a Polygon from a bounding box (4-tuple)." x0, y0, x1, y1 = bbox return GEOSGeometry( 'POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' % ( x0, y0, x0, y1, x1, y1, x1, y0, x0, y0) ) ### These routines are needed for list-like operation w/ListMixin ### def _create_polygon(self, length, items): # Instantiate LinearRing objects if necessary, but don't clone them yet # _construct_ring will throw a TypeError if a parameter isn't a valid ring # If we cloned the pointers here, we wouldn't be able to clean up # in case of error. rings = [] for r in items: if isinstance(r, GEOM_PTR): rings.append(r) else: rings.append(self._construct_ring(r)) shell = self._clone(rings.pop(0)) n_holes = length - 1 if n_holes: holes = get_pointer_arr(n_holes) for i, r in enumerate(rings): holes[i] = self._clone(r) holes_param = byref(holes) else: holes_param = None return capi.create_polygon(shell, holes_param, c_uint(n_holes)) def _clone(self, g): if isinstance(g, GEOM_PTR): return capi.geom_clone(g) else: return capi.geom_clone(g.ptr) def _construct_ring(self, param, msg='Parameter must be a sequence of LinearRings or objects that can initialize to LinearRings'): "Helper routine for trying to construct a ring from the given parameter." if isinstance(param, LinearRing): return param try: ring = LinearRing(param) return ring except TypeError: raise TypeError(msg) def _set_list(self, length, items): # Getting the current pointer, replacing with the newly constructed # geometry, and destroying the old geometry. prev_ptr = self.ptr srid = self.srid self.ptr = self._create_polygon(length, items) if srid: self.srid = srid capi.destroy_geom(prev_ptr) def _get_single_internal(self, index): """ Returns the ring at the specified index. The first index, 0, will always return the exterior ring. Indices > 0 will return the interior ring at the given index (e.g., poly[1] and poly[2] would return the first and second interior ring, respectively). CAREFUL: Internal/External are not the same as Interior/Exterior! _get_single_internal returns a pointer from the existing geometries for use internally by the object's methods. _get_single_external returns a clone of the same geometry for use by external code. """ if index == 0: return capi.get_extring(self.ptr) else: # Getting the interior ring, have to subtract 1 from the index. return capi.get_intring(self.ptr, index-1) def _get_single_external(self, index): return GEOSGeometry(capi.geom_clone(self._get_single_internal(index)), srid=self.srid) _set_single = GEOSGeometry._set_single_rebuild _assign_extended_slice = GEOSGeometry._assign_extended_slice_rebuild #### Polygon Properties #### @property def num_interior_rings(self): "Returns the number of interior rings." # Getting the number of rings return capi.get_nrings(self.ptr) def _get_ext_ring(self): "Gets the exterior ring of the Polygon." return self[0] def _set_ext_ring(self, ring): "Sets the exterior ring of the Polygon." self[0] = ring # Properties for the exterior ring/shell. exterior_ring = property(_get_ext_ring, _set_ext_ring) shell = exterior_ring @property def tuple(self): "Gets the tuple for each ring in this Polygon." return tuple([self[i].tuple for i in xrange(len(self))]) coords = tuple @property def kml(self): "Returns the KML representation of this Polygon." inner_kml = ''.join(["<innerBoundaryIs>%s</innerBoundaryIs>" % self[i+1].kml for i in xrange(self.num_interior_rings)]) return "<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>" % (self[0].kml, inner_kml)
camilonova/sentry
refs/heads/master
tests/sentry/utils/http/tests.py
1
# -*- coding: utf-8 -*- from __future__ import absolute_import import mock from django.conf import settings from exam import fixture from sentry.models import Project from sentry.testutils import TestCase from sentry.utils.http import ( is_same_domain, is_valid_origin, get_origins, absolute_uri) class AbsoluteUriTest(TestCase): def test_without_path(self): assert absolute_uri() == settings.SENTRY_URL_PREFIX def test_with_path(self): assert absolute_uri('/foo/bar') == '%s/foo/bar' % (settings.SENTRY_URL_PREFIX,) class SameDomainTestCase(TestCase): def test_is_same_domain(self): url1 = 'http://example.com/foo/bar' url2 = 'http://example.com/biz/baz' self.assertTrue(is_same_domain(url1, url2)) def test_is_same_domain_diff_scheme(self): url1 = 'https://example.com/foo/bar' url2 = 'http://example.com/biz/baz' self.assertTrue(is_same_domain(url1, url2)) def test_is_same_domain_diff_port(self): url1 = 'http://example.com:80/foo/bar' url2 = 'http://example.com:13/biz/baz' self.assertFalse(is_same_domain(url1, url2)) class GetOriginsTestCase(TestCase): def test_project(self): project = Project.objects.get() project.update_option('sentry:origins', ['http://foo.example']) with self.settings(SENTRY_ALLOW_ORIGIN=None): result = get_origins(project) self.assertEquals(result, frozenset(['http://foo.example'])) def test_project_and_setting(self): project = Project.objects.get() project.update_option('sentry:origins', ['http://foo.example']) with self.settings(SENTRY_ALLOW_ORIGIN='http://example.com'): result = get_origins(project) self.assertEquals(result, frozenset(['http://foo.example', 'http://example.com'])) def test_setting_empty(self): with self.settings(SENTRY_ALLOW_ORIGIN=None): result = get_origins(None) self.assertEquals(result, frozenset([])) def test_setting_all(self): with self.settings(SENTRY_ALLOW_ORIGIN='*'): result = get_origins(None) self.assertEquals(result, frozenset(['*'])) def test_setting_uri(self): with self.settings(SENTRY_ALLOW_ORIGIN='http://example.com'): result = get_origins(None) self.assertEquals(result, frozenset(['http://example.com'])) class IsValidOriginTestCase(TestCase): @fixture def project(self): return mock.Mock() def isValidOrigin(self, origin, inputs): with mock.patch('sentry.utils.http.get_origins') as get_origins: get_origins.return_value = inputs result = is_valid_origin(origin, self.project) get_origins.assert_called_once_with(self.project) return result def test_global_wildcard_matches_domain(self): result = self.isValidOrigin('http://example.com', ['*']) self.assertEquals(result, True) def test_domain_wildcard_matches_domain(self): result = self.isValidOrigin('http://example.com', ['*.example.com']) self.assertEquals(result, True) def test_domain_wildcard_matches_domain_with_port(self): result = self.isValidOrigin('http://example.com:80', ['*.example.com']) self.assertEquals(result, True) def test_domain_wildcard_matches_subdomain(self): result = self.isValidOrigin('http://foo.example.com', ['*.example.com']) self.assertEquals(result, True) def test_domain_wildcard_matches_subdomain_with_port(self): result = self.isValidOrigin('http://foo.example.com:80', ['*.example.com']) self.assertEquals(result, True) def test_domain_wildcard_does_not_match_others(self): result = self.isValidOrigin('http://foo.com', ['*.example.com']) self.assertEquals(result, False) def test_domain_wildcard_matches_domain_with_path(self): result = self.isValidOrigin('http://foo.example.com/foo/bar', ['*.example.com']) self.assertEquals(result, True) def test_base_domain_matches_domain(self): result = self.isValidOrigin('http://example.com', ['example.com']) self.assertEquals(result, True) def test_base_domain_matches_domain_with_path(self): result = self.isValidOrigin('http://example.com/foo/bar', ['example.com']) self.assertEquals(result, True) def test_base_domain_matches_domain_with_port(self): result = self.isValidOrigin('http://example.com:80', ['example.com']) self.assertEquals(result, True) def test_base_domain_does_not_match_subdomain(self): result = self.isValidOrigin('http://example.com', ['foo.example.com']) self.assertEquals(result, False) def test_full_uri_match(self): result = self.isValidOrigin('http://example.com', ['http://example.com']) self.assertEquals(result, True) def test_full_uri_match_requires_scheme(self): result = self.isValidOrigin('https://example.com', ['http://example.com']) self.assertEquals(result, False) def test_full_uri_match_does_not_require_port(self): result = self.isValidOrigin('http://example.com:80', ['http://example.com']) self.assertEquals(result, True) def test_partial_uri_match(self): result = self.isValidOrigin('http://example.com/foo/bar', ['http://example.com']) self.assertEquals(result, True) def test_null_valid_with_global(self): result = self.isValidOrigin('null', ['*']) self.assertEquals(result, True) def test_null_invalid_graceful_with_domains(self): result = self.isValidOrigin('null', ['http://example.com']) self.assertEquals(result, False)
ericgriffin/metasort
refs/heads/master
lib/boost/tools/build/v2/test/dependency_test.py
44
#!/usr/bin/python # Copyright 2003 Dave Abrahams # Copyright 2002, 2003, 2005, 2006 Vladimir Prus # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import BoostBuild def test_basic(): t = BoostBuild.Tester(["-d3", "-d+12"], pass_d0=False, use_test_config=False) t.write("a.cpp", """ #include <a.h> # include "a.h" #include <x.h> int main() {} """) t.write("a.h", "\n") t.write("a_c.c", """\ #include <a.h> # include "a.h" #include <x.h> """) t.write("b.cpp", """\ #include "a.h" int main() {} """) t.write("b.h", "\n") t.write("c.cpp", """\ #include "x.h" int main() {} """) t.write("e.cpp", """\ #include "x.h" int main() {} """) t.write("x.foo", "") t.write("y.foo", "") t.write("src1/a.h", '#include "b.h"\n') t.write("src1/b.h", '#include "c.h"\n') t.write("src1/c.h", "\n") t.write("src1/z.h", """\ extern int dummy_variable_suppressing_empty_file_warning_on_hp_cxx_compiler; """) t.write("src2/b.h", "\n") t.write("jamroot.jam", """\ import foo ; import types/cpp ; import types/exe ; project test : requirements <include>src1 ; exe a : x.foo a.cpp a_c.c ; exe b : b.cpp ; # Because of <define>FOO, c.cpp will be compiled to a different directory than # everything for main target "a". Therefore, without <implicit-dependency>, C # preprocessor processing that module will not find "x.h", which is part of # "a"'s dependency graph. # # -------------------------- # More detailed explanation: # -------------------------- # c.cpp includes x.h which does not exist on the current include path so Boost # Jam will try to match it to existing Jam targets to cover cases as this one # where the file is generated by the same build. # # However, as x.h is not part of "c" metatarget's dependency graph, Boost # Build will not actualize its target by default, i.e. create its Jam target. # # To get the Jam target created in time, we use the <implicit-dependency> # feature. This tells Boost Build that it needs to actualize the dependency # graph for metatarget "a", even though that metatarget has not been directly # mentioned and is not a dependency for any of the metatargets mentioned in the # current build request. # # Note that Boost Build does not automatically add a dependency between the # Jam targets in question so, if Boost Jam does not add a dependency on a target # from that other dependency graph (x.h in our case), i.e. if c.cpp does not # actually include x.h, us actualizing it will have no effect in the end as # Boost Jam will not have a reason to actually build those targets in spite of # knowing about them. exe c : c.cpp : <define>FOO <implicit-dependency>a ; """) t.write("foo.jam", """\ import generators ; import modules ; import os ; import print ; import type ; import types/cpp ; type.register FOO : foo ; generators.register-standard foo.foo : FOO : CPP H ; nl = " " ; rule foo ( targets * : sources * : properties * ) { # On NT, you need an exported symbol in order to have an import library # generated. We will not really use the symbol defined here, just force the # import library creation. if ( [ os.name ] = NT || [ modules.peek : OS ] in CYGWIN ) && <main-target-type>LIB in $(properties) { .decl = "void __declspec(dllexport) foo() {}" ; } print.output $(<[1]) ; print.text $(.decl:E="//")$(nl) ; print.output $(<[2]) ; print.text "#include <z.h>"$(nl) ; } """) t.write("foo.py", r"""import bjam import b2.build.type as type import b2.build.generators as generators from b2.manager import get_manager type.register("FOO", ["foo"]) generators.register_standard("foo.foo", ["FOO"], ["CPP", "H"]) def prepare_foo(targets, sources, properties): if properties.get('os') in ['windows', 'cygwin']: bjam.call('set-target-variable', targets, "DECL", "void __declspec(dllexport) foo() {}") get_manager().engine().register_action("foo.foo", "echo -e $(DECL:E=//)\\n > $(<[1])\n" "echo -e "#include <z.h>\\n" > $(<[2])\n", function=prepare_foo) """) # Check that main target 'c' was able to find 'x.h' from 'a's dependency # graph. t.run_build_system() t.expect_addition("bin/$toolset/debug/c.exe") # Check handling of first level includes. # Both 'a' and 'b' include "a.h" and should be updated. t.touch("a.h") t.run_build_system() t.expect_touch("bin/$toolset/debug/a.exe") t.expect_touch("bin/$toolset/debug/a.obj") t.expect_touch("bin/$toolset/debug/a_c.obj") t.expect_touch("bin/$toolset/debug/b.exe") t.expect_touch("bin/$toolset/debug/b.obj") t.expect_nothing_more() # Only source files using include <a.h> should be compiled. t.touch("src1/a.h") t.run_build_system() t.expect_touch("bin/$toolset/debug/a.exe") t.expect_touch("bin/$toolset/debug/a.obj") t.expect_touch("bin/$toolset/debug/a_c.obj") t.expect_nothing_more() # "src/a.h" includes "b.h" (in the same dir). t.touch("src1/b.h") t.run_build_system() t.expect_touch("bin/$toolset/debug/a.exe") t.expect_touch("bin/$toolset/debug/a.obj") t.expect_touch("bin/$toolset/debug/a_c.obj") t.expect_nothing_more() # Included by "src/b.h". We had a bug: file included using double quotes # (e.g. "b.h") was not scanned at all in this case. t.touch("src1/c.h") t.run_build_system() t.expect_touch("bin/$toolset/debug/a.exe") t.touch("b.h") t.run_build_system() t.expect_nothing_more() # Test dependency on a generated header. # # TODO: we have also to check that generated header is found correctly if # it is different for different subvariants. Lacking any toolset support, # this check will be implemented later. t.touch("x.foo") t.run_build_system() t.expect_touch("bin/$toolset/debug/a.obj") t.expect_touch("bin/$toolset/debug/a_c.obj") # Check that generated headers are scanned for dependencies as well. t.touch("src1/z.h") t.run_build_system() t.expect_touch("bin/$toolset/debug/a.obj") t.expect_touch("bin/$toolset/debug/a_c.obj") t.cleanup() def test_scanned_includes_with_absolute_paths(): """ Regression test: on Windows, <includes> with absolute paths were not considered when scanning dependencies. """ t = BoostBuild.Tester(["-d3", "-d+12"], pass_d0=False) t.write("jamroot.jam", """\ path-constant TOP : . ; exe app : main.cpp : <include>$(TOP)/include ; """); t.write("main.cpp", """\ #include <dir/header.h> int main() {} """) t.write("include/dir/header.h", "\n") t.run_build_system() t.expect_addition("bin/$toolset/debug/main.obj") t.touch("include/dir/header.h") t.run_build_system() t.expect_touch("bin/$toolset/debug/main.obj") t.cleanup() test_basic() test_scanned_includes_with_absolute_paths()
quru/qis
refs/heads/master
src/imageserver/conf/base_settings.py
1
# # Quru Image Server # # Base server settings (production settings) # # Do not edit this file - it will be overwritten when you upgrade the package. # # These settings can instead be overridden by creating the file # <base>/conf/local_settings.py and adding entries there instead. # # The server's public/external host name (and optionally port). # E.g. "images.example.com" or "images.example.com:8080" # or "" for automatic host name and port detection. PUBLIC_HOST_NAME = "" # The deployment path of the application on the server. # This also defaults the session cookie path. APPLICATION_ROOT = "/" # Whether to default image URLs to http or https PREFERRED_URL_SCHEME = "http" # Benchmark mode (do not enable this in production) BENCHMARKING = False # Session encryption key. Set your own in local_settings.py and KEEP IT SECRET! SECRET_KEY = "\xc7\x9b\xed9Q\x89\xb0\x19\xad\x80\x85+r\xaat:U#\x9bi\xc9\x99zY" # Which imaging back-end to load (new in v4.0). # Use 'pillow' for basic imaging, 'imagemagick' for premium imaging # (requires qismagick.so), or 'auto' for automatic detection/selection. IMAGE_BACKEND = 'auto' # Allowed image types, in the format {file extension: (name, mime type), ...}. # Only the image types in this list will be allowed to be uploaded and displayed # in the admin area. Note it is the imaging back-end that determines which formats # are actually supported. In the case of ImageMagick, the build flags and installed # delegate libraries also affect this (e.g. how well SVG is supported). IMAGE_FORMATS = { # Common image files - Pillow or ImageMagick "gif": ("GIF image", "image/gif"), "jpg": ("JPEG image", "image/jpeg"), "jpe": ("JPEG image", "image/jpeg"), "jfif": ("JPEG image", "image/jpeg"), "jif": ("JPEG image", "image/jpeg"), "jpeg": ("JPEG image", "image/jpeg"), "pjpg": ("Progressive JPEG image", "image/jpeg"), # virtual format "pjpeg": ("Progressive JPEG image", "image/jpeg"), # virtual format "png": ("PNG image", "image/png"), "tif": ("TIFF image", "image/tiff"), "tiff": ("TIFF image", "image/tiff"), # Extra image files - requires qismagick.so "bmp": ("Bitmap image", "image/bmp"), "dcm": ("DICOM image", "application/dicom"), "eps": ("Encapsulated PostScript", "application/postscript"), "ico": ("Microsoft icon", "image/x-icon"), "pdf": ("PDF file", "application/pdf"), "ppm": ("Portable PixMap image", "image/x-portable-pixmap"), "psd": ("Photoshop image", "image/psd"), "svg": ("SVG image", "image/svg+xml"), "tga": ("Truevision TARGA image", "image/tga"), "xcf": ("GIMP image", "image/xcf"), # RAW image files - requires qismagick.so "arw": ("Sony Alpha RAW image", "image/arw"), "cr2": ("Canon RAW image", "image/cr2"), "mrw": ("Minolta RAW image", "image/mrw"), "nef": ("Nikon RAW image", "image/nef"), "nrw": ("Nikon RAW image", "image/nrw"), "orf": ("Olympus RAW image", "image/orf"), "rw2": ("Panasonic RAW image", "image/rw2"), "raw": ("Panasonic RAW image", "image/raw"), "raf": ("Fuji RAW image", "image/raf"), "x3f": ("Sigma RAW image", "image/x3f"), } # Resize algorithm (1 fastest/good, 2 better, 3 slowest/best) IMAGE_RESIZE_QUALITY = 3 # Whether to gamma correct sRGB images when resizing. Should be True for the # best image quality. Adds a small overhead with the ImageMagick back-end but # incurs a heavy performance penalty with the Pillow back-end. IMAGE_RESIZE_GAMMA_CORRECT = True # Maximum image width/height parameter value to accept # E.g. 15k x 15k x 32bpp = 900MB memory required for processing MAX_IMAGE_DIMENSION = 15000 # Maximum grid size when producing tiles (must be a power of 2) MAX_GRID_TILES = 256 # Optional width and/or height limits to enforce for public-facing images, # e.g. to prevent people requesting large versions of thumbnail images. # Use a value of 0 to allow images to be requested at any size. # When non-zero, do not set these lower than 1000 if using the HTML5 zoom # viewer or gallery viewer. Also note: image templates that define a larger # width or height will take precedence over these values. PUBLIC_MAX_IMAGE_WIDTH = 0 PUBLIC_MAX_IMAGE_HEIGHT = 0 # The image pixel area beyond which the server may choose to automatically create # resized smaller versions of the image, to speed up future imaging operations. # Values below 1000000 (1 megapixel) will be ignored and disable this feature. AUTO_PYRAMID_THRESHOLD = 10000000 # The maximum time in seconds to wait for another client to finish generating # the requested image before either returning a "server too busy" error or # going on to generate a duplicate image. Allowed range 10 to 120 seconds. # Note that this value must be less than the timeouts that are also defined # at the mod_wsgi (v4.1+) and Apache/Nginx software layers. IMAGE_GENERATION_WAIT_TIMEOUT = 30 # Whether to return a "server too busy" error when IMAGE_GENERATION_WAIT_TIMEOUT # is reached. If False, the client should eventually receive the requested image, # but the server may be subjected to a significant load spike. IMAGE_GENERATION_RAISE_TOO_BUSY = True # Whether to automatically background-convert PDF files into images, # by creating a sub-folder and a PNG image file for each page. PDF_BURST_TO_PNG = True # The target DPI value to use when converting PDF pages to images. # Larger values result in larger images. PDF_BURST_DPI = 150 # Files types to treat as PDF PDF_FILE_TYPES = ['pdf', 'ps', 'eps', 'epsi', 'epsf'] # An image path (relative to IMAGES_BASE_DIR) for the image to use as the # application logo, or an empty string to use the default logo. LOGO_IMAGE_PATH = "" # An image path or folder path (relative to IMAGES_BASE_DIR) that contains the # image (or folder of images) to use for the public demo page at URL /demo/ # The image(s) must be publicly viewable. An empty string disables the demo page. DEMO_IMAGE_PATH = "" # An image path (relative to IMAGES_BASE_DIR) of an image to use for the demo # overlay on the public demo page. The image must be publicly viewable. # An empty string disables the overlay demo. DEMO_OVERLAY_IMAGE_PATH = "" # Image upload directories available for selection from the upload page. # These should be relative to IMAGES_BASE_DIR and will be created at file upload # time if they do not exist. You may optionally include date and time placeholders # as described for Python's 'strftime' function (current UTC time will be applied). # Use format (display name, relative image path). # E.g. ("Today's snaps", "%Y-%m-%d snaps") will at the time of writing create # image folder /images/2011-06-14 snaps/ for an IMAGES_BASE_DIR of /images IMAGE_UPLOAD_DIRS = [ ("Today's images", "%Y-%m-%d"), ("Sample images", "samples") ] # A template to suggest in the example HTML snippet for the uploaded image # (or an empty string for none) IMAGE_UPLOADED_TEMPLATE = "" # Maximum upload size in bytes # For multi-file uploads, this is the maximum size of all files combined MAX_CONTENT_LENGTH = 1024 * 1024 * 1024 # Full paths to the application files. # All images must lie within the path given by IMAGES_BASE_DIR. This can # point to any path that has read+write access for the application user. INSTALL_DIR = "/opt/qis/" DOCS_BASE_DIR = INSTALL_DIR + "doc/" ICC_BASE_DIR = INSTALL_DIR + "icc/" IMAGES_BASE_DIR = INSTALL_DIR + "images/" LOGGING_BASE_DIR = INSTALL_DIR + "logs/" # The directory to store published portfolios in, inside IMAGES_BASE_DIR. # Prefix the name with a single dot/period to hide it in the admin interface. FOLIO_EXPORTS_DIR = ".folio_exports" # A path where temporary imaging files can be created, or an empty string to # use the operating system's default directory (e.g. "/tmp"). TEMP_DIR = "" # Whether to allow alphanumeric unicode characters in filenames. # If False, all file names are coerced to the nearest ASCII equivalents. ALLOW_UNICODE_FILENAMES = True # Permissions to apply when creating images and directories. # Applicable to *nix platforms only. The system umask is ignored. # File default is 0o644 (rw-r--r--). IMAGES_FILE_MODE = 0o644 # Directory default is 0o755 (rwxr-xr-x). IMAGES_DIR_MODE = 0o755 # The logging server's name or IP address, or an empty string "" to disable logging LOGGING_SERVER = "localhost" # The logging server port LOGGING_SERVER_PORT = 9002 # The stats server's name or IP address, or an empty string "" to disable statistics STATS_SERVER = "localhost" # The logging server port STATS_SERVER_PORT = 9003 # The granularity of recorded image statistics, in minutes (approximate, minimum 5) STATS_FREQUENCY = 60 # The number of days to keep statistics for before deleting them. # Set to 0 to disable the automatic deletion of old statistics. STATS_KEEP_DAYS = 365 # The task server's name or IP address TASK_SERVER = "localhost" # The task server port TASK_SERVER_PORT = 9004 # The number of task processing threads to create (note CPython's GIL) TASK_SERVER_THREADS = 5 # The memcached server(s) to use, as a list MEMCACHED_SERVERS = ["127.0.0.1:11211"] # The cache management database CACHE_DATABASE_CONNECTION = "postgresql+psycopg2:///qis-cache" CACHE_DATABASE_POOL_SIZE = 5 # (per Apache process) # The image management database # Local: postgresql+psycopg2:///qis-mgmt # Remote: postgresql+psycopg2://dbuser:password@db.example.com:5432/qis-mgmt MGMT_DATABASE_CONNECTION = "postgresql+psycopg2:///qis-mgmt" MGMT_DATABASE_POOL_SIZE = 5 # (per Apache process) # If the application is hosted behind a load balancer or a reverse proxy server, # set this value to the number of servers that sit in front (usually just 1). # This is required to log the IP address of clients instead of the proxy server's # IP address, and to prevent redirection loops when the proxy server handles # HTTPS externally but uses plain HTTP internally. PROXY_SERVERS = 0 # The HTTP port to restrict the API, login, file browsing and administration # web pages to, or 0 to use the standard web browsing ports. Requires Apache/ # Nginx to also be servicing the application on this port when non-zero. INTERNAL_BROWSING_PORT = 0 # Whether to require HTTPS for the API, login, and administration web pages # to prevent eavesdropping and session hijacking (requires an installed SSL certificate) INTERNAL_BROWSING_SSL = True # Session cookie settings SESSION_COOKIE_NAME = 'session' SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = INTERNAL_BROWSING_SSL # The type of authentication used by the REST API. # Currently "TimedTokenBasicAuthentication" is the only value allowed. API_AUTHENTICATION_CLASS = "TimedTokenBasicAuthentication" # The API token expiry time in seconds. API_TOKEN_EXPIRY_TIME = 60 * 60 # The path to the Ghostscript command to use for PDF file processing. # This can be simply "gs" to use the server's default installation. GHOSTSCRIPT_PATH = "gs" # Whether to integrate with an LDAP or Active Directory server # for the provision of user accounts and login authentication. # All other LDAP settings are ignored when LDAP_INTEGRATION is False. LDAP_INTEGRATION = False # The directory service type, one from: # "OpenLDAPPosix", "OpenLDAPOrganizational", "Apple", "ActiveDirectory". LDAP_SERVER_TYPE = "" # The LDAP/AD server's name or IP address LDAP_SERVER = "" # Whether to use a secure connection with TLS / LDAPS. # Requires OpenSSL, GnuTLS or MozNSS (and possibly further configuration there). LDAP_SECURE = False # The base tree level to use when querying the directory. # E.g. LDAP "cn=users,dc=ldap,dc=mycompany,dc=com" # E.g. ActiveDirectory "dc=mycompany,dc=com" LDAP_QUERY_BASE = "" # The distinguished name and password of an LDAP user account to use for # querying the directory (only required for Active Directory). # E.g. LDAP "uid=myuser,cn=users,dc=ldap,dc=mycompany,dc=com" # E.g. ActiveDirectory "myuser@mycompany.com" LDAP_BIND_USER_DN = "" LDAP_BIND_PASSWORD = "" # Destination for sending anonymous usage data, once per 24 hours USAGE_DATA_URL = 'https://qis.quru.com/collectstats' # For use with the "xref" image parameter, a 3rd party URL that will be called # (every time the image is requested) with the xref value appended to it. # E.g. "http://www.example.com/trackid?id=", or "" to disable this feature. # Note: Do not use a URL that refers back to this same server, otherwise # a deadlock-type condition could occur when the server is very busy. XREF_TRACKING_URL = ""
ahamilton55/ansible
refs/heads/devel
lib/ansible/modules/net_tools/exoscale/__init__.py
12133432
mitdbg/modeldb
refs/heads/master
client/verta/verta/_swagger/_public/common/__init__.py
12133432
vismartltd/edx-platform
refs/heads/master
lms/djangoapps/django_comment_client/management/commands/__init__.py
12133432
matteoredaelli/scrapy_web
refs/heads/master
scrapy_web/spiders/nomi_maschili_femminili_nomix_it.py
1
# -*- coding: utf-8 -*- # scrapy_web # Copyright (C) 2016-2017 Matteo.Redaelli@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # scrapy crawl dizionario_italiano_corriere -t jsonlines -o diz.json import scrapy class NomiMaschiliFemminiliNomixItSpider(scrapy.Spider): name = "nomi-nomix.it" allowed_domains = ["nomix.it"] start_urls = ( 'http://www.nomix.it/nomi-italiani-maschili-e-femminili.php', ) def parse(self, response): for nome in response.xpath('//div[@class="pure-g"]/div[1]/table//td/text()').extract(): yield {"word": nome, "class": "nome proprio", "sex": "male", "source": "nomix.com"} for nome in response.xpath('//div[@class="pure-g"]/div[2]/table//td/text()').extract(): yield {"word": nome, "class": "nome proprio", "sex": "female", "source": "nomix.com"} # extracting next pages for next_page in response.xpath('//h2/a/@href').extract(): if next_page is not None and next_page != "#": next_page = response.urljoin(next_page) yield scrapy.Request(next_page, callback=self.parse)
tntnatbry/tensorflow
refs/heads/master
tensorflow/contrib/learn/python/learn/estimators/prediction_key.py
28
# 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. # ============================================================================== """Enum for model prediction keys.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function class PredictionKey(object): CLASSES = "classes" PROBABILITIES = "probabilities" LOGITS = "logits" LOGISTIC = "logistic" SCORES = "scores" TOP_K = "top_k" GENERIC = "output"
rubbenrc/uip-prog3
refs/heads/master
parcial/presupuesto_parcial.py
1
#------------------------------------------------------------------------------- # Name: presupuesto parcial#1 # Author: programar # # Creado: 12/11/2015 # Copyright: (c) programar 2015 # Licence: <your licence 1.1> #------------------------------------------------------------------------------- import msvcrt titulo="Empresa Rubben Rc Corporation\n".capitalize() print titulo.center(50," ") print("Telefono: 6948209") class modelo_presupuesto: titulo="presupuesto" inicio_nombre="Empresa Rubben Rc Corporation" inicio_web= "www.rubbenrc.com" inicio_email= "rubbenrc@hotmail.com" cuota_iva= 7 div= "="*80 def set_cliente(self): self.empresa= raw_input("Empresa: ") self.cliente= raw_input("Nombre del cliente: ") def set_datos_basicos(self): self.fecha= raw_input(" Fecha: ") self.servicio= raw_input("Descripcion del servicio: ") importe= raw_input("importe bruto: $") self.importe= float(importe) self.vencimiento= raw_input("fecha de expiracion: ") def iva(self): self.monto_iva= self.importe*self.cuota_iva/100 def monto_neto(self): self.neto= self.importe+self.monto_iva def armar_presupuesto(self): """ Esta funcion se encarga de armar todo el presupuesto """ txt = '\n'+self.div+'\n' txt += '\t'+self.inicio_nombre+'\n' txt += '\tWeb Site: '+self.inicio_web+' | ' txt += 'E-mail: '+self.inicio_email+'\n' txt += self.div+'\n' txt += '\t'+self.titulo+'\n' txt += self.div+'\n\n' txt += '\tFecha: '+self.fecha+'\n' txt += '\tEmpresa: '+self.empresa+'\n' txt += '\tCliente: '+self.cliente+'\n' txt += self.div+'\n\n' txt += '\tDetalle del servicio:' txt += '\t'+self.servicio+'\n\n' txt += '\tImporte: $%0.2f | IVA: $%0.2f\n' % ( self.importe, self.monto_iva) txt += '-'*80 txt += '\n\tMONTO TOTAL: $%0.2f\n' % (self.neto) txt += self.div+'\n' print txt # Metodo constructor def __init__(self): print self.div print "\tPRESUPUESTO A OFRECER" print self.div self.set_cliente() self.set_datos_basicos() self.iva() self.monto_neto() self.armar_presupuesto() # Instanciar clase presupuesto = modelo_presupuesto() msvcrt.getch()
tumbl3w33d/ansible
refs/heads/devel
test/units/plugins/loader_fixtures/import_fixture.py
129
# Nothing to see here, this file is just empty to support a imp.load_source # without doing anything __metaclass__ = type class test: def __init__(self, *args, **kwargs): pass
runfalk/stormspans
refs/heads/master
stormspans/__init__.py
1
""" StormSpans brings support for PostgreSQL's range types to Canonical's Storm using PsycoSpans paired with Spans. from spans import intrange from storm.locals import * from stormspans import IntRange class Model(Storm): id = Int(primary=True) span = IntRange(default=intrange(1, 10)) To connect to the database "postgres+spans://..." must be specified instead of "postgres://..." """ __version__ = "0.1.0" from storm.database import register_scheme from .database import PostgresStormSpans, install_range from .properties import * __all__ = [ "IntRange", "FloatRange", "DateRange", "DateTimeRange", "install_range" ] register_scheme("postgres+spans", PostgresStormSpans)
avirajsaha/rts_scheduler
refs/heads/master
rts_util.py
1
T_INSTANCE_OFF = 0 T_TIME_FROM_OFF = 1 T_TIME_TO_OFF = 2 T_REL_TIME_OFF = 3 T_DEADLINE_OFF = 4 T_EXEC_LEFT_OFF = 5 T_PERIOD_OFF = 6 T_ACTIVE_OFF = 7 T_PROMOTION_OFF = 8 def gcd(*numbers): """Return the greatest common divisor of the given integers""" from fractions import gcd return reduce(gcd, numbers) def lcm(*numbers): """Return lowest common multiple.""" def lcm(a, b): return (a * b) // gcd(a, b) return reduce(lcm, numbers, 1) schedule_chart = [] def rts_rm_schedule_dump(curr_task, sched_info): global schedule_chart schedule_chart.append([curr_task+1, sched_info[T_INSTANCE_OFF], sched_info[T_TIME_FROM_OFF], sched_info[T_TIME_TO_OFF], sched_info[T_REL_TIME_OFF], sched_info[T_DEADLINE_OFF], sched_info[T_EXEC_LEFT_OFF], sched_info[T_PROMOTION_OFF]]) def rts_rm_schedule_show(show=True): global schedule_chart if show: print "\"Promotion\"\t\"Time(from)\"\t\"Time(to)\"\t\"Task Id\"\t\"Instance\"\t\"Rel Time\"\t\"Deadline\"\t\"Execution Left\"" for sched_entry in schedule_chart: if (sched_entry[7] == True): promotion = "yes" else: promotion = "no" print "%s\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t\t" %(promotion, sched_entry[2], sched_entry[3], sched_entry[0], sched_entry[1], sched_entry[4], sched_entry[5], sched_entry[6]) #Flush after the display schedule_chart = []
j0gurt/ggrc-core
refs/heads/develop
src/ggrc/models/section.py
4
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.directive import Directive from ggrc.models.mixins import CustomAttributable from ggrc.models.mixins import Described from ggrc.models.mixins import Hierarchical from ggrc.models.mixins import Hyperlinked from ggrc.models.mixins import Noted from ggrc.models.mixins import Slugged from ggrc.models.mixins import Stateful from ggrc.models.mixins import Titled from ggrc.models.mixins import WithContact from ggrc.models.deferred import deferred from ggrc.models.object_owner import Ownable from ggrc.models.object_person import Personable from ggrc.models.reflection import AttributeInfo from ggrc.models.relationship import Relatable from ggrc.models.relationship import Relationship from ggrc.models.track_object_state import HasObjectState from ggrc.models.track_object_state import track_state_for_class class Section(HasObjectState, Hierarchical, Noted, Described, Hyperlinked, WithContact, Titled, Stateful, db.Model, CustomAttributable, Personable, Ownable, Relatable, Slugged): VALID_STATES = [ 'Draft', 'Final', 'Effective', 'Ineffective', 'Launched', 'Not Launched', 'In Scope', 'Not in Scope', 'Deprecated', ] __tablename__ = 'sections' _table_plural = 'sections' _title_uniqueness = True _aliases = { "url": "Section URL", "description": "Text of Section", "directive": { "display_name": "Policy / Regulation / Standard / Contract", "type": AttributeInfo.Type.MAPPING, "filter_by": "_filter_by_directive", } } na = deferred(db.Column(db.Boolean, default=False, nullable=False), 'Section') notes = deferred(db.Column(db.Text), 'Section') _publish_attrs = [ 'na', 'notes', ] _sanitize_html = ['notes'] _include_links = [] @classmethod def _filter_by_directive(cls, predicate): types = ["Policy", "Regulation", "Standard", "Contract"] dst = Relationship.query \ .filter( (Relationship.source_id == cls.id) & (Relationship.source_type == cls.__name__) & (Relationship.destination_type.in_(types))) \ .join(Directive, Directive.id == Relationship.destination_id) \ .filter(predicate(Directive.slug) | predicate(Directive.title)) \ .exists() src = Relationship.query \ .filter( (Relationship.destination_id == cls.id) & (Relationship.destination_type == cls.__name__) & (Relationship.source_type.in_(types))) \ .join(Directive, Directive.id == Relationship.source_id) \ .filter(predicate(Directive.slug) | predicate(Directive.title)) \ .exists() return dst | src track_state_for_class(Section)
zhangzhishan/thefuck
refs/heads/master
thefuck/rules/quotation_marks.py
9
# Fixes careless " and ' usage # # Example: # > git commit -m 'My Message" def match(command, settings): return '\'' in command.script and '\"' in command.script def get_new_command(command, settings): return command.script.replace('\'', '\"')
havt/odoo
refs/heads/8.0
addons/website_event_track/__openerp__.py
323
# -*- coding: utf-8 -*- { 'name': 'Advanced Events', 'category': 'Website', 'summary': 'Sponsors, Tracks, Agenda, Event News', 'website': 'https://www.odoo.com/page/events', 'version': '1.0', 'description': """ Online Advanced Events ====================== Adds support for: - sponsors - dedicated menu per event - news per event - tracks - agenda - call for proposals """, 'author': 'OpenERP SA', 'depends': ['website_event', 'website_blog'], 'data': [ 'data/event_data.xml', 'views/website_event.xml', 'views/event_backend.xml', 'security/ir.model.access.csv', 'security/event.xml', ], 'qweb': ['static/src/xml/*.xml'], 'demo': [ 'data/event_demo.xml', 'data/website_event_track_demo.xml' ], 'installable': True, }
130265/Galaxy-S4-Value-Edition-I9515L-Kernel
refs/heads/cm-12.1-oc
scripts/rt-tester/rt-tester.py
11005
#!/usr/bin/python # # rt-mutex tester # # (C) 2006 Thomas Gleixner <tglx@linutronix.de> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # import os import sys import getopt import shutil import string # Globals quiet = 0 test = 0 comments = 0 sysfsprefix = "/sys/devices/system/rttest/rttest" statusfile = "/status" commandfile = "/command" # Command opcodes cmd_opcodes = { "schedother" : "1", "schedfifo" : "2", "lock" : "3", "locknowait" : "4", "lockint" : "5", "lockintnowait" : "6", "lockcont" : "7", "unlock" : "8", "signal" : "11", "resetevent" : "98", "reset" : "99", } test_opcodes = { "prioeq" : ["P" , "eq" , None], "priolt" : ["P" , "lt" , None], "priogt" : ["P" , "gt" , None], "nprioeq" : ["N" , "eq" , None], "npriolt" : ["N" , "lt" , None], "npriogt" : ["N" , "gt" , None], "unlocked" : ["M" , "eq" , 0], "trylock" : ["M" , "eq" , 1], "blocked" : ["M" , "eq" , 2], "blockedwake" : ["M" , "eq" , 3], "locked" : ["M" , "eq" , 4], "opcodeeq" : ["O" , "eq" , None], "opcodelt" : ["O" , "lt" , None], "opcodegt" : ["O" , "gt" , None], "eventeq" : ["E" , "eq" , None], "eventlt" : ["E" , "lt" , None], "eventgt" : ["E" , "gt" , None], } # Print usage information def usage(): print "rt-tester.py <-c -h -q -t> <testfile>" print " -c display comments after first command" print " -h help" print " -q quiet mode" print " -t test mode (syntax check)" print " testfile: read test specification from testfile" print " otherwise from stdin" return # Print progress when not in quiet mode def progress(str): if not quiet: print str # Analyse a status value def analyse(val, top, arg): intval = int(val) if top[0] == "M": intval = intval / (10 ** int(arg)) intval = intval % 10 argval = top[2] elif top[0] == "O": argval = int(cmd_opcodes.get(arg, arg)) else: argval = int(arg) # progress("%d %s %d" %(intval, top[1], argval)) if top[1] == "eq" and intval == argval: return 1 if top[1] == "lt" and intval < argval: return 1 if top[1] == "gt" and intval > argval: return 1 return 0 # Parse the commandline try: (options, arguments) = getopt.getopt(sys.argv[1:],'chqt') except getopt.GetoptError, ex: usage() sys.exit(1) # Parse commandline options for option, value in options: if option == "-c": comments = 1 elif option == "-q": quiet = 1 elif option == "-t": test = 1 elif option == '-h': usage() sys.exit(0) # Select the input source if arguments: try: fd = open(arguments[0]) except Exception,ex: sys.stderr.write("File not found %s\n" %(arguments[0])) sys.exit(1) else: fd = sys.stdin linenr = 0 # Read the test patterns while 1: linenr = linenr + 1 line = fd.readline() if not len(line): break line = line.strip() parts = line.split(":") if not parts or len(parts) < 1: continue if len(parts[0]) == 0: continue if parts[0].startswith("#"): if comments > 1: progress(line) continue if comments == 1: comments = 2 progress(line) cmd = parts[0].strip().lower() opc = parts[1].strip().lower() tid = parts[2].strip() dat = parts[3].strip() try: # Test or wait for a status value if cmd == "t" or cmd == "w": testop = test_opcodes[opc] fname = "%s%s%s" %(sysfsprefix, tid, statusfile) if test: print fname continue while 1: query = 1 fsta = open(fname, 'r') status = fsta.readline().strip() fsta.close() stat = status.split(",") for s in stat: s = s.strip() if s.startswith(testop[0]): # Separate status value val = s[2:].strip() query = analyse(val, testop, dat) break if query or cmd == "t": break progress(" " + status) if not query: sys.stderr.write("Test failed in line %d\n" %(linenr)) sys.exit(1) # Issue a command to the tester elif cmd == "c": cmdnr = cmd_opcodes[opc] # Build command string and sys filename cmdstr = "%s:%s" %(cmdnr, dat) fname = "%s%s%s" %(sysfsprefix, tid, commandfile) if test: print fname continue fcmd = open(fname, 'w') fcmd.write(cmdstr) fcmd.close() except Exception,ex: sys.stderr.write(str(ex)) sys.stderr.write("\nSyntax error in line %d\n" %(linenr)) if not test: fd.close() sys.exit(1) # Normal exit pass print "Pass" sys.exit(0)
bollu/sandhi
refs/heads/master
modules/gr36/gr-input/python/gr_ramp_source.py
7
#!/usr/bin/python import gras import numpy # Serial is imported in __init__ class ramp(gras.Block): def __init__(self): gras.Block.__init__(self, name="ser", in_sig=[numpy.float32], out_sig=[numpy.float32]) self.i = 0 self.flag=True def set_parameters(self, ramp_slope, height_Offset, width_Offset): self.slope = ramp_slope self.width = width_Offset self.offset = height_Offset def work(self, input_items, output_items): out = output_items[0][0:1] input_stream = input_items[0][0] if self.flag: for j in range(self.width): out = self.offset print "OUT", out self.produce(0,1) # Produce from port 0 output_items self.consume(0,1) # Consume from port 0 input_items self.flag = False else: self.i = self.i + 1 out[:1] =self.offset + self.i*input_stream*self.slope print "OUT", out self.produce(0,1) # Produce from port 0 output_items self.consume(0,1) # Consume from port 0 input_items
akhilari7/pa-dude
refs/heads/master
lib/python2.7/site-packages/pip/_vendor/six.py
2715
"""Utilities for writing code that runs on Python 2 and 3""" # Copyright (c) 2010-2015 Benjamin Peterson # # 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. from __future__ import absolute_import import functools import itertools import operator import sys import types __author__ = "Benjamin Peterson <benjamin@python.org>" __version__ = "1.10.0" # Useful for very coarse version differentiation. PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 PY34 = sys.version_info[0:2] >= (3, 4) if PY3: string_types = str, integer_types = int, class_types = type, text_type = str binary_type = bytes MAXSIZE = sys.maxsize else: string_types = basestring, integer_types = (int, long) class_types = (type, types.ClassType) text_type = unicode binary_type = str if sys.platform.startswith("java"): # Jython always uses 32 bits. MAXSIZE = int((1 << 31) - 1) else: # It's possible to have sizeof(long) != sizeof(Py_ssize_t). class X(object): def __len__(self): return 1 << 31 try: len(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name] class _LazyDescr(object): def __init__(self, name): self.name = name def __get__(self, obj, tp): result = self._resolve() setattr(obj, self.name, result) # Invokes __set__. try: # This is a bit ugly, but it avoids running this again by # removing this descriptor. delattr(obj.__class__, self.name) except AttributeError: pass return result class MovedModule(_LazyDescr): def __init__(self, name, old, new=None): super(MovedModule, self).__init__(name) if PY3: if new is None: new = name self.mod = new else: self.mod = old def _resolve(self): return _import_module(self.mod) def __getattr__(self, attr): _module = self._resolve() value = getattr(_module, attr) setattr(self, attr, value) return value class _LazyModule(types.ModuleType): def __init__(self, name): super(_LazyModule, self).__init__(name) self.__doc__ = self.__class__.__doc__ def __dir__(self): attrs = ["__doc__", "__name__"] attrs += [attr.name for attr in self._moved_attributes] return attrs # Subclasses should override this _moved_attributes = [] class MovedAttribute(_LazyDescr): def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): super(MovedAttribute, self).__init__(name) if PY3: if new_mod is None: new_mod = name self.mod = new_mod if new_attr is None: if old_attr is None: new_attr = name else: new_attr = old_attr self.attr = new_attr else: self.mod = old_mod if old_attr is None: old_attr = name self.attr = old_attr def _resolve(self): module = _import_module(self.mod) return getattr(module, self.attr) class _SixMetaPathImporter(object): """ A meta path importer to import six.moves and its submodules. This class implements a PEP302 finder and loader. It should be compatible with Python 2.5 and all existing versions of Python3 """ def __init__(self, six_module_name): self.name = six_module_name self.known_modules = {} def _add_module(self, mod, *fullnames): for fullname in fullnames: self.known_modules[self.name + "." + fullname] = mod def _get_module(self, fullname): return self.known_modules[self.name + "." + fullname] def find_module(self, fullname, path=None): if fullname in self.known_modules: return self return None def __get_module(self, fullname): try: return self.known_modules[fullname] except KeyError: raise ImportError("This loader does not know module " + fullname) def load_module(self, fullname): try: # in case of a reload return sys.modules[fullname] except KeyError: pass mod = self.__get_module(fullname) if isinstance(mod, MovedModule): mod = mod._resolve() else: mod.__loader__ = self sys.modules[fullname] = mod return mod def is_package(self, fullname): """ Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451) """ return hasattr(self.__get_module(fullname), "__path__") def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None get_source = get_code # same as get_code _importer = _SixMetaPathImporter(__name__) class _MovedItems(_LazyModule): """Lazy loading of moved objects""" __path__ = [] # mark as package _moved_attributes = [ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), MovedAttribute("intern", "__builtin__", "sys"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), MovedAttribute("reduce", "__builtin__", "functools"), MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), MovedAttribute("StringIO", "StringIO", "io"), MovedAttribute("UserDict", "UserDict", "collections"), MovedAttribute("UserList", "UserList", "collections"), MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), MovedModule("cPickle", "cPickle", "pickle"), MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), MovedModule("_thread", "thread", "_thread"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"), MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"), MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), MovedModule("tkinter_font", "tkFont", "tkinter.font"), MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"), MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), ] # Add windows specific modules. if sys.platform == "win32": _moved_attributes += [ MovedModule("winreg", "_winreg"), ] for attr in _moved_attributes: setattr(_MovedItems, attr.name, attr) if isinstance(attr, MovedModule): _importer._add_module(attr, "moves." + attr.name) del attr _MovedItems._moved_attributes = _moved_attributes moves = _MovedItems(__name__ + ".moves") _importer._add_module(moves, "moves") class Module_six_moves_urllib_parse(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_parse""" _urllib_parse_moved_attributes = [ MovedAttribute("ParseResult", "urlparse", "urllib.parse"), MovedAttribute("SplitResult", "urlparse", "urllib.parse"), MovedAttribute("parse_qs", "urlparse", "urllib.parse"), MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), MovedAttribute("urldefrag", "urlparse", "urllib.parse"), MovedAttribute("urljoin", "urlparse", "urllib.parse"), MovedAttribute("urlparse", "urlparse", "urllib.parse"), MovedAttribute("urlsplit", "urlparse", "urllib.parse"), MovedAttribute("urlunparse", "urlparse", "urllib.parse"), MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), MovedAttribute("quote", "urllib", "urllib.parse"), MovedAttribute("quote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote", "urllib", "urllib.parse"), MovedAttribute("unquote_plus", "urllib", "urllib.parse"), MovedAttribute("urlencode", "urllib", "urllib.parse"), MovedAttribute("splitquery", "urllib", "urllib.parse"), MovedAttribute("splittag", "urllib", "urllib.parse"), MovedAttribute("splituser", "urllib", "urllib.parse"), MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), MovedAttribute("uses_params", "urlparse", "urllib.parse"), MovedAttribute("uses_query", "urlparse", "urllib.parse"), MovedAttribute("uses_relative", "urlparse", "urllib.parse"), ] for attr in _urllib_parse_moved_attributes: setattr(Module_six_moves_urllib_parse, attr.name, attr) del attr Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), "moves.urllib_parse", "moves.urllib.parse") class Module_six_moves_urllib_error(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_error""" _urllib_error_moved_attributes = [ MovedAttribute("URLError", "urllib2", "urllib.error"), MovedAttribute("HTTPError", "urllib2", "urllib.error"), MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), ] for attr in _urllib_error_moved_attributes: setattr(Module_six_moves_urllib_error, attr.name, attr) del attr Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), "moves.urllib_error", "moves.urllib.error") class Module_six_moves_urllib_request(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_request""" _urllib_request_moved_attributes = [ MovedAttribute("urlopen", "urllib2", "urllib.request"), MovedAttribute("install_opener", "urllib2", "urllib.request"), MovedAttribute("build_opener", "urllib2", "urllib.request"), MovedAttribute("pathname2url", "urllib", "urllib.request"), MovedAttribute("url2pathname", "urllib", "urllib.request"), MovedAttribute("getproxies", "urllib", "urllib.request"), MovedAttribute("Request", "urllib2", "urllib.request"), MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), MovedAttribute("BaseHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), MovedAttribute("FileHandler", "urllib2", "urllib.request"), MovedAttribute("FTPHandler", "urllib2", "urllib.request"), MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), MovedAttribute("urlretrieve", "urllib", "urllib.request"), MovedAttribute("urlcleanup", "urllib", "urllib.request"), MovedAttribute("URLopener", "urllib", "urllib.request"), MovedAttribute("FancyURLopener", "urllib", "urllib.request"), MovedAttribute("proxy_bypass", "urllib", "urllib.request"), ] for attr in _urllib_request_moved_attributes: setattr(Module_six_moves_urllib_request, attr.name, attr) del attr Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), "moves.urllib_request", "moves.urllib.request") class Module_six_moves_urllib_response(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_response""" _urllib_response_moved_attributes = [ MovedAttribute("addbase", "urllib", "urllib.response"), MovedAttribute("addclosehook", "urllib", "urllib.response"), MovedAttribute("addinfo", "urllib", "urllib.response"), MovedAttribute("addinfourl", "urllib", "urllib.response"), ] for attr in _urllib_response_moved_attributes: setattr(Module_six_moves_urllib_response, attr.name, attr) del attr Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), "moves.urllib_response", "moves.urllib.response") class Module_six_moves_urllib_robotparser(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_robotparser""" _urllib_robotparser_moved_attributes = [ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), ] for attr in _urllib_robotparser_moved_attributes: setattr(Module_six_moves_urllib_robotparser, attr.name, attr) del attr Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), "moves.urllib_robotparser", "moves.urllib.robotparser") class Module_six_moves_urllib(types.ModuleType): """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" __path__ = [] # mark as package parse = _importer._get_module("moves.urllib_parse") error = _importer._get_module("moves.urllib_error") request = _importer._get_module("moves.urllib_request") response = _importer._get_module("moves.urllib_response") robotparser = _importer._get_module("moves.urllib_robotparser") def __dir__(self): return ['parse', 'error', 'request', 'response', 'robotparser'] _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib") def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,)) if PY3: _meth_func = "__func__" _meth_self = "__self__" _func_closure = "__closure__" _func_code = "__code__" _func_defaults = "__defaults__" _func_globals = "__globals__" else: _meth_func = "im_func" _meth_self = "im_self" _func_closure = "func_closure" _func_code = "func_code" _func_defaults = "func_defaults" _func_globals = "func_globals" try: advance_iterator = next except NameError: def advance_iterator(it): return it.next() next = advance_iterator try: callable = callable except NameError: def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) if PY3: def get_unbound_function(unbound): return unbound create_bound_method = types.MethodType def create_unbound_method(func, cls): return func Iterator = object else: def get_unbound_function(unbound): return unbound.im_func def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__) def create_unbound_method(func, cls): return types.MethodType(func, None, cls) class Iterator(object): def next(self): return type(self).__next__(self) callable = callable _add_doc(get_unbound_function, """Get the function out of a possibly unbound function""") get_method_function = operator.attrgetter(_meth_func) get_method_self = operator.attrgetter(_meth_self) get_function_closure = operator.attrgetter(_func_closure) get_function_code = operator.attrgetter(_func_code) get_function_defaults = operator.attrgetter(_func_defaults) get_function_globals = operator.attrgetter(_func_globals) if PY3: def iterkeys(d, **kw): return iter(d.keys(**kw)) def itervalues(d, **kw): return iter(d.values(**kw)) def iteritems(d, **kw): return iter(d.items(**kw)) def iterlists(d, **kw): return iter(d.lists(**kw)) viewkeys = operator.methodcaller("keys") viewvalues = operator.methodcaller("values") viewitems = operator.methodcaller("items") else: def iterkeys(d, **kw): return d.iterkeys(**kw) def itervalues(d, **kw): return d.itervalues(**kw) def iteritems(d, **kw): return d.iteritems(**kw) def iterlists(d, **kw): return d.iterlists(**kw) viewkeys = operator.methodcaller("viewkeys") viewvalues = operator.methodcaller("viewvalues") viewitems = operator.methodcaller("viewitems") _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") _add_doc(itervalues, "Return an iterator over the values of a dictionary.") _add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.") _add_doc(iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary.") if PY3: def b(s): return s.encode("latin-1") def u(s): return s unichr = chr import struct int2byte = struct.Struct(">B").pack del struct byte2int = operator.itemgetter(0) indexbytes = operator.getitem iterbytes = iter import io StringIO = io.StringIO BytesIO = io.BytesIO _assertCountEqual = "assertCountEqual" if sys.version_info[1] <= 1: _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" else: _assertRaisesRegex = "assertRaisesRegex" _assertRegex = "assertRegex" else: def b(s): return s # Workaround for standalone backslash def u(s): return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") unichr = unichr int2byte = chr def byte2int(bs): return ord(bs[0]) def indexbytes(buf, i): return ord(buf[i]) iterbytes = functools.partial(itertools.imap, ord) import StringIO StringIO = BytesIO = StringIO.StringIO _assertCountEqual = "assertItemsEqual" _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs) def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs) def assertRegex(self, *args, **kwargs): return getattr(self, _assertRegex)(*args, **kwargs) if PY3: exec_ = getattr(moves.builtins, "exec") def reraise(tp, value, tb=None): if value is None: value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""") exec_("""def reraise(tp, value, tb=None): raise tp, value, tb """) if sys.version_info[:2] == (3, 2): exec_("""def raise_from(value, from_value): if from_value is None: raise value raise value from from_value """) elif sys.version_info[:2] > (3, 2): exec_("""def raise_from(value, from_value): raise value from from_value """) else: def raise_from(value, from_value): raise value print_ = getattr(moves.builtins, "print", None) if print_ is None: def print_(*args, **kwargs): """The new-style print function for Python 2.4 and 2.5.""" fp = kwargs.pop("file", sys.stdout) if fp is None: return def write(data): if not isinstance(data, basestring): data = str(data) # If the file has an encoding, encode unicode with it. if (isinstance(fp, file) and isinstance(data, unicode) and fp.encoding is not None): errors = getattr(fp, "errors", None) if errors is None: errors = "strict" data = data.encode(fp.encoding, errors) fp.write(data) want_unicode = False sep = kwargs.pop("sep", None) if sep is not None: if isinstance(sep, unicode): want_unicode = True elif not isinstance(sep, str): raise TypeError("sep must be None or a string") end = kwargs.pop("end", None) if end is not None: if isinstance(end, unicode): want_unicode = True elif not isinstance(end, str): raise TypeError("end must be None or a string") if kwargs: raise TypeError("invalid keyword arguments to print()") if not want_unicode: for arg in args: if isinstance(arg, unicode): want_unicode = True break if want_unicode: newline = unicode("\n") space = unicode(" ") else: newline = "\n" space = " " if sep is None: sep = space if end is None: end = newline for i, arg in enumerate(args): if i: write(sep) write(arg) write(end) if sys.version_info[:2] < (3, 3): _print = print_ def print_(*args, **kwargs): fp = kwargs.get("file", sys.stdout) flush = kwargs.pop("flush", False) _print(*args, **kwargs) if flush and fp is not None: fp.flush() _add_doc(reraise, """Reraise an exception.""") if sys.version_info[0:2] < (3, 4): def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES): def wrapper(f): f = functools.wraps(wrapped, assigned, updated)(f) f.__wrapped__ = wrapped return f return wrapper else: wraps = functools.wraps def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: if '__str__' not in klass.__dict__: raise ValueError("@python_2_unicode_compatible cannot be applied " "to %s because it doesn't define __str__()." % klass.__name__) klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass # Complete the moves implementation. # This code is at the end of this module to speed up module loading. # Turn this module into a package. __path__ = [] # required for PEP 302 and PEP 451 __package__ = __name__ # see PEP 366 @ReservedAssignment if globals().get("__spec__") is not None: __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable # Remove other six meta path importers, since they cause problems. This can # happen if six is removed from sys.modules and then reloaded. (Setuptools does # this for some reason.) if sys.meta_path: for i, importer in enumerate(sys.meta_path): # Here's some real nastiness: Another "instance" of the six module might # be floating around. Therefore, we can't use isinstance() to check for # the six meta path importer, since the other six instance will have # inserted an importer with different class. if (type(importer).__name__ == "_SixMetaPathImporter" and importer.name == __name__): del sys.meta_path[i] break del i, importer # Finally, add the importer to the meta path import hook. sys.meta_path.append(_importer)
joelddiaz/openshift-tools
refs/heads/prod
openshift/installer/vendored/openshift-ansible-3.6.173.0.59/roles/openshift_health_checker/openshift_checks/package_availability.py
5
"""Check that required RPM packages are available.""" from openshift_checks import OpenShiftCheck from openshift_checks.mixins import NotContainerizedMixin class PackageAvailability(NotContainerizedMixin, OpenShiftCheck): """Check that required RPM packages are available.""" name = "package_availability" tags = ["preflight"] def is_active(self): """Run only when yum is the package manager as the code is specific to it.""" return super(PackageAvailability, self).is_active() and self.get_var("ansible_pkg_mgr") == "yum" def run(self): rpm_prefix = self.get_var("openshift", "common", "service_type") group_names = self.get_var("group_names", default=[]) packages = set() if "masters" in group_names: packages.update(self.master_packages(rpm_prefix)) if "nodes" in group_names: packages.update(self.node_packages(rpm_prefix)) args = {"packages": sorted(set(packages))} return self.execute_module_with_retries("check_yum_update", args) @staticmethod def master_packages(rpm_prefix): """Return a list of RPMs that we expect a master install to have available.""" return [ "{rpm_prefix}".format(rpm_prefix=rpm_prefix), "{rpm_prefix}-clients".format(rpm_prefix=rpm_prefix), "{rpm_prefix}-master".format(rpm_prefix=rpm_prefix), "bash-completion", "cockpit-bridge", "cockpit-docker", "cockpit-system", "cockpit-ws", "etcd", "httpd-tools", ] @staticmethod def node_packages(rpm_prefix): """Return a list of RPMs that we expect a node install to have available.""" return [ "{rpm_prefix}".format(rpm_prefix=rpm_prefix), "{rpm_prefix}-node".format(rpm_prefix=rpm_prefix), "{rpm_prefix}-sdn-ovs".format(rpm_prefix=rpm_prefix), "bind", "ceph-common", "dnsmasq", "docker", "firewalld", "flannel", "glusterfs-fuse", "iptables-services", "iptables", "iscsi-initiator-utils", "libselinux-python", "nfs-utils", "ntp", "openssl", "pyparted", "python-httplib2", "PyYAML", "yum-utils", ]
Hydrospheredata/mist
refs/heads/master
mist-lib/src/main/python/tests/decorators/__init__.py
12133432
akshatharaj/django
refs/heads/master
tests/admin_scripts/management/commands/__init__.py
12133432
simongoffin/my_odoo_tutorial
refs/heads/master
addons/l10n_in_hr_payroll/report/__init__.py
424
#-*- coding:utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # d$ # # 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/>. # ############################################################################## import report_payslip_details import report_payroll_advice import report_hr_salary_employee_bymonth import payment_advice_report import report_hr_yearly_salary_detail import payslip_report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
ivan7farre/PyFreeFOAM
refs/heads/master
Foam/src/finiteVolume/__init__.py
338
## pythonFlu - Python wrapping for OpenFOAM C++ API ## Copyright (C) 2010- Alexey Petrov ## Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR) ## ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/>. ## ## See http://sourceforge.net/projects/pythonflu ## ## Author : Alexey PETROV ##
iwm911/plaso
refs/heads/master
plaso/lib/pfilter_test.py
1
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2012 The Plaso Project Authors. # Please see the AUTHORS file for details on individual 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. """Tests for the filters.""" import unittest from plaso.lib import event from plaso.lib import eventdata from plaso.lib import objectfilter from plaso.lib import parser from plaso.lib import pfilter from plaso.lib import timelib_test import pytz class Empty(object): """An empty object.""" class PfilterFakeFormatter(eventdata.EventFormatter): """A formatter for this fake class.""" DATA_TYPE = 'Weirdo:Made up Source:Last Written' FORMAT_STRING = '{text}' FORMAT_STRING_SHORT = '{text_short}' SOURCE_LONG = 'Fake Parsing Source' SOURCE_SHORT = 'REG' class PfilterFakeParser(parser.BaseParser): """A fake parser that does not parse anything, but registers.""" NAME = 'pfilter_fake_parser' DATA_TYPE = 'Weirdo:Made up Source:Last Written' def Parse(self, unused_file_entry): """Extract data from a fake plist file for testing. Args: unused_file_entry: A file entry object that is not used by the fake parser. Yields: An event object (instance of EventObject) that contains the parsed attributes. """ event_object = event.EventObject() event_object.timestamp = timelib_test.CopyStringToTimestamp( '2015-11-18 01:15:43') event_object.timestamp_desc = 'Last Written' event_object.text_short = 'This description is different than the long one.' event_object.text = ( u'User did a very bad thing, bad, bad thing that awoke Dr. Evil.') event_object.filename = ( u'/My Documents/goodfella/Documents/Hideout/myfile.txt') event_object.hostname = 'Agrabah' event_object.parser = 'Weirdo' event_object.inode = 1245 event_object.display_name = u'unknown:{0:s}'.format(event_object.filename) event_object.data_type = self.DATA_TYPE yield event_object class PfilterAnotherParser(PfilterFakeParser): """Another fake parser that does nothing but register as a parser.""" NAME = 'pfilter_another_fake' DATA_TYPE = 'Weirdo:AnotherFakeSource' class PfilterAnotherFakeFormatter(PfilterFakeFormatter): """Formatter for the AnotherParser event.""" DATA_TYPE = 'Weirdo:AnotherFakeSource' SOURCE_LONG = 'Another Fake Source' class PfilterAllEvilParser(PfilterFakeParser): """A class that does nothing but has a fancy name.""" NAME = 'pfilter_evil_fake_parser' DATA_TYPE = 'Weirdo:AllEvil' class PfilterEvilFormatter(PfilterFakeFormatter): """Formatter for the AllEvilParser.""" DATA_TYPE = 'Weirdo:AllEvil' SOURCE_LONG = 'A Truly Evil' class PFilterTest(unittest.TestCase): """Simple plaso specific tests to the pfilter implementation.""" def setUp(self): """Set up the necessary variables used in tests.""" self._pre = Empty() self._pre.zone = pytz.UTC def testPlasoEvents(self): """Test plaso EventObjects, both Python and Protobuf version. These are more plaso specific tests than the more generic objectfilter ones. It will create an EventObject that stores some attributes. These objects will then be serialzed into an EventObject protobuf and all tests run against both the native Python object as well as the protobuf. """ event_object = event.EventObject() event_object.data_type = 'Weirdo:Made up Source:Last Written' event_object.timestamp = timelib_test.CopyStringToTimestamp( '2015-11-18 01:15:43') event_object.timestamp_desc = 'Last Written' event_object.text_short = 'This description is different than the long one.' event_object.text = ( u'User did a very bad thing, bad, bad thing that awoke Dr. Evil.') event_object.filename = ( u'/My Documents/goodfella/Documents/Hideout/myfile.txt') event_object.hostname = 'Agrabah' event_object.parser = 'Weirdo' event_object.inode = 1245 event_object.mydict = { 'value': 134, 'another': 'value', 'A Key (with stuff)': 'Here'} event_object.display_name = u'unknown:{0:s}'.format(event_object.filename) # Series of tests. query = 'filename contains \'GoodFella\'' self.RunPlasoTest(event_object, query, True) # Double negative matching -> should be the same # as a positive one. query = 'filename not not contains \'GoodFella\'' my_parser = pfilter.BaseParser(query) self.assertRaises( objectfilter.ParseError, my_parser.Parse) # Test date filtering. query = 'date >= \'2015-11-18\'' self.RunPlasoTest(event_object, query, True) query = 'date < \'2015-11-19\'' self.RunPlasoTest(event_object, query, True) # 2015-11-18T01:15:43 query = ( 'date < \'2015-11-18T01:15:44.341\' and date > \'2015-11-18 01:15:42\'') self.RunPlasoTest(event_object, query, True) query = 'date > \'2015-11-19\'' self.RunPlasoTest(event_object, query, False) # Perform few attribute tests. query = 'filename not contains \'sometext\'' self.RunPlasoTest(event_object, query, True) query = ( 'timestamp_desc CONTAINS \'written\' AND date > \'2015-11-18\' AND ' 'date < \'2015-11-25 12:56:21\' AND (source_short contains \'LOG\' or ' 'source_short CONTAINS \'REG\')') self.RunPlasoTest(event_object, query, True) query = 'parser is not \'Made\'' self.RunPlasoTest(event_object, query, True) query = 'parser is not \'Weirdo\'' self.RunPlasoTest(event_object, query, False) query = 'mydict.value is 123' self.RunPlasoTest(event_object, query, False) query = 'mydict.akeywithstuff contains "ere"' self.RunPlasoTest(event_object, query, True) query = 'mydict.value is 134' self.RunPlasoTest(event_object, query, True) query = 'mydict.value < 200' self.RunPlasoTest(event_object, query, True) query = 'mydict.another contains "val"' self.RunPlasoTest(event_object, query, True) query = 'mydict.notthere is 123' self.RunPlasoTest(event_object, query, False) query = 'source_long not contains \'Fake\'' self.RunPlasoTest(event_object, query, False) query = 'source is \'REG\'' self.RunPlasoTest(event_object, query, True) query = 'source is not \'FILE\'' self.RunPlasoTest(event_object, query, True) # Multiple attributes. query = ( 'source_long is \'Fake Parsing Source\' AND description_long ' 'regexp \'bad, bad thing [\\sa-zA-Z\\.]+ evil\'') self.RunPlasoTest(event_object, query, False) query = ( 'source_long is \'Fake Parsing Source\' AND text iregexp ' '\'bad, bad thing [\\sa-zA-Z\\.]+ evil\'') self.RunPlasoTest(event_object, query, True) def RunPlasoTest(self, obj, query, result): """Run a simple test against an event object.""" my_parser = pfilter.BaseParser(query).Parse() matcher = my_parser.Compile( pfilter.PlasoAttributeFilterImplementation) self.assertEqual(result, matcher.Matches(obj)) if __name__ == "__main__": unittest.main()
colbyga/pychess
refs/heads/master
lib/pychess/Variants/suicide.py
20
from __future__ import print_function # Suicide Chess from pychess.Utils.const import * from pychess.Utils.Board import Board SUICIDESTART = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w - - 0 1" class SuicideBoard(Board): variant = SUICIDECHESS def __init__ (self, setup=False, lboard=None): if setup is True: Board.__init__(self, setup=SUICIDESTART, lboard=lboard) else: Board.__init__(self, setup=setup, lboard=lboard) class SuicideChess: __desc__ = _("FICS suicide: http://www.freechess.org/Help/HelpFiles/suicide_chess.html") name = _("Suicide") cecp_name = "suicide" board = SuicideBoard need_initial_board = True standard_rules = False variant_group = VARIANTS_OTHER_NONSTANDARD def pieceCount(board, color): return bin(board.friends[color]).count("1") if __name__ == '__main__': from pychess.Utils.Move import Move from pychess.Utils.lutils.lmove import parseAN from pychess.Utils.lutils.lmovegen import genCaptures FEN = "rnbqk1nr/pppp1pPp/4p3/8/8/8/PPPbPPP1/RNBQKBNR b - - 7 4" b = SuicideBoard(SUICIDESTART) b = b.move(Move(parseAN(b.board, "h2h4"))) print(b.board.__repr__()) for move in genCaptures(b.board): print(Move(move)) b = b.move(Move(parseAN(b.board, "e7e6"))) print(b.board.__repr__()) for move in genCaptures(b.board): print(Move(move)) b = b.move(Move(parseAN(b.board, "h4h5"))) print(b.board.__repr__()) for move in genCaptures(b.board): print(Move(move)) b = b.move(Move(parseAN(b.board, "f8b4"))) print(b.board.__repr__()) for move in genCaptures(b.board): print(Move(move)) b = b.move(Move(parseAN(b.board, "h5h6"))) print(b.board.__repr__()) for move in genCaptures(b.board): print(Move(move)) b = b.move(Move(parseAN(b.board, "b4d2"))) print(b.board.__repr__()) for move in genCaptures(b.board): print(Move(move)) b = b.move(Move(parseAN(b.board, "h6g7"))) print(b.board.__repr__()) for move in genCaptures(b.board): print(Move(move)) b = b.move(Move(parseAN(b.board, "d2e1"))) print(b.board.__repr__()) for move in genCaptures(b.board): print(Move(move))
boxed/CMi
refs/heads/master
web_frontend/CMi/cal/tests.py
6666
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2)
DD-L/deel.boost.python
refs/heads/master
revise/libs/python/pyste/dist/setup.py
13
# Copyright Bruno da Silva de Oliveira 2006. Distributed under the Boost # Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) from distutils.core import setup import py2exe import sys sys.path.append('../src') setup(name='pyste', scripts=['../src/pyste.py'])
palginpav/Cryptonite
refs/heads/master
qa/rpc-tests/python-bitcoinrpc/setup.py
182
#!/usr/bin/env python from distutils.core import setup setup(name='python-bitcoinrpc', version='0.1', description='Enhanced version of python-jsonrpc for use with Bitcoin', long_description=open('README').read(), author='Jeff Garzik', author_email='<jgarzik@exmulti.com>', maintainer='Jeff Garzik', maintainer_email='<jgarzik@exmulti.com>', url='http://www.github.com/jgarzik/python-bitcoinrpc', packages=['bitcoinrpc'], classifiers=['License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Operating System :: OS Independent'])
ol-loginov/intellij-community
refs/heads/master
python/helpers/pydev/third_party/pep8/lib2to3/lib2to3/fixes/fix_print.py
326
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for print. Change: 'print' into 'print()' 'print ...' into 'print(...)' 'print ... ,' into 'print(..., end=" ")' 'print >>x, ...' into 'print(..., file=x)' No changes are applied if print_function is imported from __future__ """ # Local imports from .. import patcomp from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Name, Call, Comma, String, is_tuple parend_expr = patcomp.compile_pattern( """atom< '(' [atom|STRING|NAME] ')' >""" ) class FixPrint(fixer_base.BaseFix): BM_compatible = True PATTERN = """ simple_stmt< any* bare='print' any* > | print_stmt """ def transform(self, node, results): assert results bare_print = results.get("bare") if bare_print: # Special-case print all by itself bare_print.replace(Call(Name(u"print"), [], prefix=bare_print.prefix)) return assert node.children[0] == Name(u"print") args = node.children[1:] if len(args) == 1 and parend_expr.match(args[0]): # We don't want to keep sticking parens around an # already-parenthesised expression. return sep = end = file = None if args and args[-1] == Comma(): args = args[:-1] end = " " if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, u">>"): assert len(args) >= 2 file = args[1].clone() args = args[3:] # Strip a possible comma after the file expression # Now synthesize a print(args, sep=..., end=..., file=...) node. l_args = [arg.clone() for arg in args] if l_args: l_args[0].prefix = u"" if sep is not None or end is not None or file is not None: if sep is not None: self.add_kwarg(l_args, u"sep", String(repr(sep))) if end is not None: self.add_kwarg(l_args, u"end", String(repr(end))) if file is not None: self.add_kwarg(l_args, u"file", file) n_stmt = Call(Name(u"print"), l_args) n_stmt.prefix = node.prefix return n_stmt def add_kwarg(self, l_nodes, s_kwd, n_expr): # XXX All this prefix-setting may lose comments (though rarely) n_expr.prefix = u"" n_argument = pytree.Node(self.syms.argument, (Name(s_kwd), pytree.Leaf(token.EQUAL, u"="), n_expr)) if l_nodes: l_nodes.append(Comma()) n_argument.prefix = u" " l_nodes.append(n_argument)
macbre/index-digest
refs/heads/master
indexdigest/test/linters/test_0019_queries_not_using_indices.py
1
from __future__ import print_function from unittest import TestCase from indexdigest.linters.linter_0019_queries_not_using_indices import check_queries_not_using_indices from indexdigest.test import DatabaseTestMixin, read_queries_from_log class TestQueriesNotUsingIndices(TestCase, DatabaseTestMixin): def test_queries(self): reports = list(check_queries_not_using_indices( database=self.connection, queries=read_queries_from_log('0019-queries-not-using-indices-log'))) print(*[f"{report.message} ({report.context['explain_extra']})" for report in reports], sep="\n") assert len(reports) == 3 self.assertEqual(str(reports[0]), '0019_queries_not_using_indices: "SELECT item_id FROM 0019_queries_not_using_indices..." query did not make use of any index') self.assertEqual(reports[0].table_name, '0019_queries_not_using_indices') self.assertEqual(str(reports[0].context['query']), 'SELECT item_id FROM 0019_queries_not_using_indices WHERE foo = "test" OR item_id > 1;') self.assertEqual(str(reports[0].context['explain_extra']), 'Using where') self.assertEqual(str(reports[0].context['explain_rows']), '3') self.assertEqual(reports[1].table_name, '0019_queries_not_using_indices') self.assertEqual(str(reports[1].context['query']), 'SELECT item_id FROM 0019_queries_not_using_indices WHERE foo = "test"') self.assertEqual(str(reports[1].context['explain_extra']), 'Using where') self.assertEqual(str(reports[1].context['explain_rows']), '3') self.assertEqual(reports[2].table_name, '0019_queries_not_using_indices') self.assertEqual(str(reports[2].context['query']), 'SELECT 1 AS one FROM dual WHERE exists ( SELECT item_id FROM 0019_queries_not_using_indices WHERE foo = "test" );') self.assertEqual(str(reports[2].context['explain_extra']), 'Using where') self.assertEqual(str(reports[2].context['explain_rows']), '3') # assert False
enirinth/free-food-calendar
refs/heads/master
foodscrape/spiders/__init__.py
2415
# This package will contain the spiders of your Scrapy project # # Please refer to the documentation for information on how to create and manage # your spiders.
ubc/lti-parser
refs/heads/master
oauth_store.py
1
class OAuthStoreError(Exception): pass class OAuthStoreSaveError(OAuthStoreError): ''' Throw this error if saving to the data store fails. ''' pass class OAuthStore: ''' Base class for OAuth data storage. This is intended to abstract the actual details of the storage of data necessary for OAuth verification into a unified interface. A simple implementation which stores the data in memory as a dict is provided. More complex implementations should inherit from this class and override appropriate methods. ''' def __init__(self): ''' Inherited classes don't have to call this constructor. This is only for the in memory dict implementation. ''' self.secrets = {} def set_secret(self, key, secret): ''' Save a key and secret pair into the database. ''' self.secrets[key] = secret def get_secret(self, key): ''' Given a key, return the associated secret. If the key is unfamiliar, then just return an empty string. ''' return self.secrets.get(key, "") def has_key(self, key): ''' Returns true if we know key exists, false otherwise. ''' return key in self.secrets
yannrouillard/weboob
refs/heads/master
modules/banquepopulaire/backend.py
2
# -*- coding: utf-8 -*- # Copyright(C) 2012-2013 Romain Bignon # # This file is part of weboob. # # weboob 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. # # weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>. from weboob.capabilities.bank import ICapBank, AccountNotFound from weboob.tools.backend import BaseBackend, BackendConfig from weboob.tools.ordereddict import OrderedDict from weboob.tools.value import ValueBackendPassword, Value from .browser import BanquePopulaire __all__ = ['BanquePopulaireBackend'] class BanquePopulaireBackend(BaseBackend, ICapBank): NAME = 'banquepopulaire' MAINTAINER = u'Romain Bignon' EMAIL = 'romain@weboob.org' VERSION = '0.i' DESCRIPTION = u'Banque Populaire' LICENSE = 'AGPLv3+' website_choices = OrderedDict([(k, u'%s (%s)' % (v, k)) for k, v in sorted({ 'www.ibps.alpes.banquepopulaire.fr': u'Alpes', 'www.ibps.alsace.banquepopulaire.fr': u'Alsace', 'www.ibps.bpaca.banquepopulaire.fr': u'Aquitaine Centre atlantique', 'www.ibps.atlantique.banquepopulaire.fr': u'Atlantique', 'www.ibps.bpbfc.banquepopulaire.fr': u'Bourgogne-Franche Comté', 'www.ibps.bretagnenormandie.cmm.groupe.banquepopulaire.fr': u'Crédit Maritime Bretagne Normandie', 'www.ibps.atlantique.creditmaritime.groupe.banquepopulaire.fr': u'Crédit Maritime Atlantique', 'www.ibps.sudouest.creditmaritime.groupe.banquepopulaire.fr': u'Crédit Maritime du Littoral du Sud-Ouest', 'www.ibps.cotedazur.banquepopulaire.fr': u'Côte d\'azur', 'www.ibps.loirelyonnais.banquepopulaire.fr': u'Loire et Lyonnais', 'www.ibps.lorrainechampagne.banquepopulaire.fr': u'Lorraine Champagne', 'www.ibps.massifcentral.banquepopulaire.fr': u'Massif central', 'www.ibps.nord.banquepopulaire.fr': u'Nord', 'www.ibps.occitane.banquepopulaire.fr': u'Occitane', 'www.ibps.ouest.banquepopulaire.fr': u'Ouest', 'www.ibps.provencecorse.banquepopulaire.fr': u'Provence et Corse', 'www.ibps.rivesparis.banquepopulaire.fr': u'Rives de Paris', 'www.ibps.sud.banquepopulaire.fr': u'Sud', 'www.ibps.valdefrance.banquepopulaire.fr': u'Val de France', }.iteritems(), key=lambda (k, v): (v, k))]) CONFIG = BackendConfig(Value('website', label=u'Région', choices=website_choices), ValueBackendPassword('login', label='Identifiant', masked=False), ValueBackendPassword('password', label='Mot de passee')) BROWSER = BanquePopulaire def create_default_browser(self): return self.create_browser(self.config['website'].get(), self.config['login'].get(), self.config['password'].get()) def iter_accounts(self): with self.browser: return self.browser.get_accounts_list() def get_account(self, _id): with self.browser: account = self.browser.get_account(_id) if account: return account else: raise AccountNotFound() def iter_history(self, account): with self.browser: return self.browser.get_history(account) def iter_coming(self, account): with self.browser: return self.browser.get_history(account, coming=True)
rsvip/Django
refs/heads/master
django/contrib/auth/models.py
13
from __future__ import unicode_literals from django.contrib import auth from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.signals import user_logged_in from django.contrib.contenttypes.models import ContentType from django.core import validators from django.core.exceptions import PermissionDenied from django.core.mail import send_mail from django.db import models from django.db.models.manager import EmptyManager from django.utils import six, timezone from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ def update_last_login(sender, user, **kwargs): """ A signal receiver which updates the last_login date for the user logging in. """ user.last_login = timezone.now() user.save(update_fields=['last_login']) user_logged_in.connect(update_last_login) class PermissionManager(models.Manager): use_in_migrations = True def get_by_natural_key(self, codename, app_label, model): return self.get( codename=codename, content_type=ContentType.objects.db_manager(self.db).get_by_natural_key(app_label, model), ) @python_2_unicode_compatible class Permission(models.Model): """ The permissions system provides a way to assign permissions to specific users and groups of users. The permission system is used by the Django admin site, but may also be useful in your own code. The Django admin site uses permissions as follows: - The "add" permission limits the user's ability to view the "add" form and add an object. - The "change" permission limits a user's ability to view the change list, view the "change" form and change an object. - The "delete" permission limits the ability to delete an object. Permissions are set globally per type of object, not per specific object instance. It is possible to say "Mary may change news stories," but it's not currently possible to say "Mary may change news stories, but only the ones she created herself" or "Mary may only change news stories that have a certain status or publication date." Three basic permissions -- add, change and delete -- are automatically created for each Django model. """ name = models.CharField(_('name'), max_length=255) content_type = models.ForeignKey(ContentType) codename = models.CharField(_('codename'), max_length=100) objects = PermissionManager() class Meta: verbose_name = _('permission') verbose_name_plural = _('permissions') unique_together = (('content_type', 'codename'),) ordering = ('content_type__app_label', 'content_type__model', 'codename') def __str__(self): return "%s | %s | %s" % ( six.text_type(self.content_type.app_label), six.text_type(self.content_type), six.text_type(self.name)) def natural_key(self): return (self.codename,) + self.content_type.natural_key() natural_key.dependencies = ['contenttypes.contenttype'] class GroupManager(models.Manager): """ The manager for the auth's Group model. """ use_in_migrations = True def get_by_natural_key(self, name): return self.get(name=name) @python_2_unicode_compatible class Group(models.Model): """ Groups are a generic way of categorizing users to apply permissions, or some other label, to those users. A user can belong to any number of groups. A user in a group automatically has all the permissions granted to that group. For example, if the group Site editors has the permission can_edit_home_page, any user in that group will have that permission. Beyond permissions, groups are a convenient way to categorize users to apply some label, or extended functionality, to them. For example, you could create a group 'Special users', and you could write code that would do special things to those users -- such as giving them access to a members-only portion of your site, or sending them members-only email messages. """ name = models.CharField(_('name'), max_length=80, unique=True) permissions = models.ManyToManyField( Permission, verbose_name=_('permissions'), blank=True, ) objects = GroupManager() class Meta: verbose_name = _('group') verbose_name_plural = _('groups') def __str__(self): return self.name def natural_key(self): return (self.name,) class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, email, password, **extra_fields): """ Creates and saves a User with the given username, email and password. """ if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(username, email, password, **extra_fields) def create_superuser(self, username, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(username, email, password, **extra_fields) # A few helper functions for common logic between User and AnonymousUser. def _user_get_all_permissions(user, obj): permissions = set() for backend in auth.get_backends(): if hasattr(backend, "get_all_permissions"): permissions.update(backend.get_all_permissions(user, obj)) return permissions def _user_has_perm(user, perm, obj): """ A backend can raise `PermissionDenied` to short-circuit permission checking. """ for backend in auth.get_backends(): if not hasattr(backend, 'has_perm'): continue try: if backend.has_perm(user, perm, obj): return True except PermissionDenied: return False return False def _user_has_module_perms(user, app_label): """ A backend can raise `PermissionDenied` to short-circuit permission checking. """ for backend in auth.get_backends(): if not hasattr(backend, 'has_module_perms'): continue try: if backend.has_module_perms(user, app_label): return True except PermissionDenied: return False return False class PermissionsMixin(models.Model): """ A mixin class that adds the fields and methods necessary to support Django's Group and Permission model using the ModelBackend. """ is_superuser = models.BooleanField( _('superuser status'), default=False, help_text=_( 'Designates that this user has all permissions without ' 'explicitly assigning them.' ), ) groups = models.ManyToManyField( Group, verbose_name=_('groups'), blank=True, help_text=_( 'The groups this user belongs to. A user will get all permissions ' 'granted to each of their groups.' ), related_name="user_set", related_query_name="user", ) user_permissions = models.ManyToManyField( Permission, verbose_name=_('user permissions'), blank=True, help_text=_('Specific permissions for this user.'), related_name="user_set", related_query_name="user", ) class Meta: abstract = True def get_group_permissions(self, obj=None): """ Returns a list of permission strings that this user has through their groups. This method queries all available auth backends. If an object is passed in, only permissions matching this object are returned. """ permissions = set() for backend in auth.get_backends(): if hasattr(backend, "get_group_permissions"): permissions.update(backend.get_group_permissions(self, obj)) return permissions def get_all_permissions(self, obj=None): return _user_get_all_permissions(self, obj) def has_perm(self, perm, obj=None): """ Returns True if the user has the specified permission. This method queries all available auth backends, but returns immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have permission in general. If an object is provided, permissions for this specific object are checked. """ # Active superusers have all permissions. if self.is_active and self.is_superuser: return True # Otherwise we need to check the backends. return _user_has_perm(self, perm, obj) def has_perms(self, perm_list, obj=None): """ Returns True if the user has each of the specified permissions. If object is passed, it checks if the user has all required perms for this object. """ for perm in perm_list: if not self.has_perm(perm, obj): return False return True def has_module_perms(self, app_label): """ Returns True if the user has any permissions in the given app label. Uses pretty much the same logic as has_perm, above. """ # Active superusers have all permissions. if self.is_active and self.is_superuser: return True return _user_has_module_perms(self, app_label) class AbstractUser(AbstractBaseUser, PermissionsMixin): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. Username and password are required. Other fields are optional. """ username = models.CharField( _('username'), max_length=30, unique=True, help_text=_('Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[ validators.RegexValidator( r'^[\w.@+-]+$', _('Enter a valid username. This value may contain only ' 'letters, numbers ' 'and @/./+/-/_ characters.') ), ], error_messages={ 'unique': _("A user with that username already exists."), }, ) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(_('email address'), blank=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] class Meta: verbose_name = _('user') verbose_name_plural = _('users') abstract = True def get_full_name(self): """ Returns the first_name plus the last_name, with a space in between. """ full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): "Returns the short name for the user." return self.first_name def email_user(self, subject, message, from_email=None, **kwargs): """ Sends an email to this User. """ send_mail(subject, message, from_email, [self.email], **kwargs) class User(AbstractUser): """ Users within the Django authentication system are represented by this model. Username, password and email are required. Other fields are optional. """ class Meta(AbstractUser.Meta): swappable = 'AUTH_USER_MODEL' @python_2_unicode_compatible class AnonymousUser(object): id = None pk = None username = '' is_staff = False is_active = False is_superuser = False _groups = EmptyManager(Group) _user_permissions = EmptyManager(Permission) def __init__(self): pass def __str__(self): return 'AnonymousUser' def __eq__(self, other): return isinstance(other, self.__class__) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return 1 # instances always return the same hash value def save(self): raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.") def delete(self): raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.") def set_password(self, raw_password): raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.") def check_password(self, raw_password): raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.") def _get_groups(self): return self._groups groups = property(_get_groups) def _get_user_permissions(self): return self._user_permissions user_permissions = property(_get_user_permissions) def get_group_permissions(self, obj=None): return set() def get_all_permissions(self, obj=None): return _user_get_all_permissions(self, obj=obj) def has_perm(self, perm, obj=None): return _user_has_perm(self, perm, obj=obj) def has_perms(self, perm_list, obj=None): for perm in perm_list: if not self.has_perm(perm, obj): return False return True def has_module_perms(self, module): return _user_has_module_perms(self, module) def is_anonymous(self): return True def is_authenticated(self): return False def get_username(self): return self.username
sublime1809/django
refs/heads/master
tests/view_tests/__init__.py
435
# -*- coding: utf-8 -*- from __future__ import unicode_literals class BrokenException(Exception): pass except_args = (b'Broken!', # plain exception with ASCII text '¡Broken!', # non-ASCII unicode data '¡Broken!'.encode('utf-8'), # non-ASCII, utf-8 encoded bytestring b'\xa1Broken!', ) # non-ASCII, latin1 bytestring
Murii/Bonding
refs/heads/master
src/3rdparty/freetype/src/tools/glnames.py
360
#!/usr/bin/env python # # # FreeType 2 glyph name builder # # Copyright 1996-2000, 2003, 2005, 2007, 2008, 2011 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. """\ usage: %s <output-file> This python script generates the glyph names tables defined in the `psnames' module. Its single argument is the name of the header file to be created. """ import sys, string, struct, re, os.path # This table lists the glyphs according to the Macintosh specification. # It is used by the TrueType Postscript names table. # # See # # http://fonts.apple.com/TTRefMan/RM06/Chap6post.html # # for the official list. # mac_standard_names = \ [ # 0 ".notdef", ".null", "nonmarkingreturn", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", # 10 "quotesingle", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", # 20 "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", # 30 "semicolon", "less", "equal", "greater", "question", "at", "A", "B", "C", "D", # 40 "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", # 50 "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", # 60 "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "grave", "a", "b", # 70 "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", # 80 "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", # 90 "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", "Adieresis", "Aring", # 100 "Ccedilla", "Eacute", "Ntilde", "Odieresis", "Udieresis", "aacute", "agrave", "acircumflex", "adieresis", "atilde", # 110 "aring", "ccedilla", "eacute", "egrave", "ecircumflex", "edieresis", "iacute", "igrave", "icircumflex", "idieresis", # 120 "ntilde", "oacute", "ograve", "ocircumflex", "odieresis", "otilde", "uacute", "ugrave", "ucircumflex", "udieresis", # 130 "dagger", "degree", "cent", "sterling", "section", "bullet", "paragraph", "germandbls", "registered", "copyright", # 140 "trademark", "acute", "dieresis", "notequal", "AE", "Oslash", "infinity", "plusminus", "lessequal", "greaterequal", # 150 "yen", "mu", "partialdiff", "summation", "product", "pi", "integral", "ordfeminine", "ordmasculine", "Omega", # 160 "ae", "oslash", "questiondown", "exclamdown", "logicalnot", "radical", "florin", "approxequal", "Delta", "guillemotleft", # 170 "guillemotright", "ellipsis", "nonbreakingspace", "Agrave", "Atilde", "Otilde", "OE", "oe", "endash", "emdash", # 180 "quotedblleft", "quotedblright", "quoteleft", "quoteright", "divide", "lozenge", "ydieresis", "Ydieresis", "fraction", "currency", # 190 "guilsinglleft", "guilsinglright", "fi", "fl", "daggerdbl", "periodcentered", "quotesinglbase", "quotedblbase", "perthousand", "Acircumflex", # 200 "Ecircumflex", "Aacute", "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave", "Oacute", "Ocircumflex", # 210 "apple", "Ograve", "Uacute", "Ucircumflex", "Ugrave", "dotlessi", "circumflex", "tilde", "macron", "breve", # 220 "dotaccent", "ring", "cedilla", "hungarumlaut", "ogonek", "caron", "Lslash", "lslash", "Scaron", "scaron", # 230 "Zcaron", "zcaron", "brokenbar", "Eth", "eth", "Yacute", "yacute", "Thorn", "thorn", "minus", # 240 "multiply", "onesuperior", "twosuperior", "threesuperior", "onehalf", "onequarter", "threequarters", "franc", "Gbreve", "gbreve", # 250 "Idotaccent", "Scedilla", "scedilla", "Cacute", "cacute", "Ccaron", "ccaron", "dcroat" ] # The list of standard `SID' glyph names. For the official list, # see Annex A of document at # # http://partners.adobe.com/public/developer/en/font/5176.CFF.pdf . # sid_standard_names = \ [ # 0 ".notdef", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quoteright", "parenleft", # 10 "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", # 20 "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", # 30 "equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F", # 40 "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", # 50 "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", # 60 "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "quoteleft", "a", "b", "c", "d", # 70 "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", # 80 "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", # 90 "y", "z", "braceleft", "bar", "braceright", "asciitilde", "exclamdown", "cent", "sterling", "fraction", # 100 "yen", "florin", "section", "currency", "quotesingle", "quotedblleft", "guillemotleft", "guilsinglleft", "guilsinglright", "fi", # 110 "fl", "endash", "dagger", "daggerdbl", "periodcentered", "paragraph", "bullet", "quotesinglbase", "quotedblbase", "quotedblright", # 120 "guillemotright", "ellipsis", "perthousand", "questiondown", "grave", "acute", "circumflex", "tilde", "macron", "breve", # 130 "dotaccent", "dieresis", "ring", "cedilla", "hungarumlaut", "ogonek", "caron", "emdash", "AE", "ordfeminine", # 140 "Lslash", "Oslash", "OE", "ordmasculine", "ae", "dotlessi", "lslash", "oslash", "oe", "germandbls", # 150 "onesuperior", "logicalnot", "mu", "trademark", "Eth", "onehalf", "plusminus", "Thorn", "onequarter", "divide", # 160 "brokenbar", "degree", "thorn", "threequarters", "twosuperior", "registered", "minus", "eth", "multiply", "threesuperior", # 170 "copyright", "Aacute", "Acircumflex", "Adieresis", "Agrave", "Aring", "Atilde", "Ccedilla", "Eacute", "Ecircumflex", # 180 "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave", "Ntilde", "Oacute", "Ocircumflex", "Odieresis", # 190 "Ograve", "Otilde", "Scaron", "Uacute", "Ucircumflex", "Udieresis", "Ugrave", "Yacute", "Ydieresis", "Zcaron", # 200 "aacute", "acircumflex", "adieresis", "agrave", "aring", "atilde", "ccedilla", "eacute", "ecircumflex", "edieresis", # 210 "egrave", "iacute", "icircumflex", "idieresis", "igrave", "ntilde", "oacute", "ocircumflex", "odieresis", "ograve", # 220 "otilde", "scaron", "uacute", "ucircumflex", "udieresis", "ugrave", "yacute", "ydieresis", "zcaron", "exclamsmall", # 230 "Hungarumlautsmall", "dollaroldstyle", "dollarsuperior", "ampersandsmall", "Acutesmall", "parenleftsuperior", "parenrightsuperior", "twodotenleader", "onedotenleader", "zerooldstyle", # 240 "oneoldstyle", "twooldstyle", "threeoldstyle", "fouroldstyle", "fiveoldstyle", "sixoldstyle", "sevenoldstyle", "eightoldstyle", "nineoldstyle", "commasuperior", # 250 "threequartersemdash", "periodsuperior", "questionsmall", "asuperior", "bsuperior", "centsuperior", "dsuperior", "esuperior", "isuperior", "lsuperior", # 260 "msuperior", "nsuperior", "osuperior", "rsuperior", "ssuperior", "tsuperior", "ff", "ffi", "ffl", "parenleftinferior", # 270 "parenrightinferior", "Circumflexsmall", "hyphensuperior", "Gravesmall", "Asmall", "Bsmall", "Csmall", "Dsmall", "Esmall", "Fsmall", # 280 "Gsmall", "Hsmall", "Ismall", "Jsmall", "Ksmall", "Lsmall", "Msmall", "Nsmall", "Osmall", "Psmall", # 290 "Qsmall", "Rsmall", "Ssmall", "Tsmall", "Usmall", "Vsmall", "Wsmall", "Xsmall", "Ysmall", "Zsmall", # 300 "colonmonetary", "onefitted", "rupiah", "Tildesmall", "exclamdownsmall", "centoldstyle", "Lslashsmall", "Scaronsmall", "Zcaronsmall", "Dieresissmall", # 310 "Brevesmall", "Caronsmall", "Dotaccentsmall", "Macronsmall", "figuredash", "hypheninferior", "Ogoneksmall", "Ringsmall", "Cedillasmall", "questiondownsmall", # 320 "oneeighth", "threeeighths", "fiveeighths", "seveneighths", "onethird", "twothirds", "zerosuperior", "foursuperior", "fivesuperior", "sixsuperior", # 330 "sevensuperior", "eightsuperior", "ninesuperior", "zeroinferior", "oneinferior", "twoinferior", "threeinferior", "fourinferior", "fiveinferior", "sixinferior", # 340 "seveninferior", "eightinferior", "nineinferior", "centinferior", "dollarinferior", "periodinferior", "commainferior", "Agravesmall", "Aacutesmall", "Acircumflexsmall", # 350 "Atildesmall", "Adieresissmall", "Aringsmall", "AEsmall", "Ccedillasmall", "Egravesmall", "Eacutesmall", "Ecircumflexsmall", "Edieresissmall", "Igravesmall", # 360 "Iacutesmall", "Icircumflexsmall", "Idieresissmall", "Ethsmall", "Ntildesmall", "Ogravesmall", "Oacutesmall", "Ocircumflexsmall", "Otildesmall", "Odieresissmall", # 370 "OEsmall", "Oslashsmall", "Ugravesmall", "Uacutesmall", "Ucircumflexsmall", "Udieresissmall", "Yacutesmall", "Thornsmall", "Ydieresissmall", "001.000", # 380 "001.001", "001.002", "001.003", "Black", "Bold", "Book", "Light", "Medium", "Regular", "Roman", # 390 "Semibold" ] # This table maps character codes of the Adobe Standard Type 1 # encoding to glyph indices in the sid_standard_names table. # t1_standard_encoding = \ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 0, 111, 112, 113, 114, 0, 115, 116, 117, 118, 119, 120, 121, 122, 0, 123, 0, 124, 125, 126, 127, 128, 129, 130, 131, 0, 132, 133, 0, 134, 135, 136, 137, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 138, 0, 139, 0, 0, 0, 0, 140, 141, 142, 143, 0, 0, 0, 0, 0, 144, 0, 0, 0, 145, 0, 0, 146, 147, 148, 149, 0, 0, 0, 0 ] # This table maps character codes of the Adobe Expert Type 1 # encoding to glyph indices in the sid_standard_names table. # t1_expert_encoding = \ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 229, 230, 0, 231, 232, 233, 234, 235, 236, 237, 238, 13, 14, 15, 99, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27, 28, 249, 250, 251, 252, 0, 253, 254, 255, 256, 257, 0, 0, 0, 258, 0, 0, 259, 260, 261, 262, 0, 0, 263, 264, 265, 0, 266, 109, 110, 267, 268, 269, 0, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 304, 305, 306, 0, 0, 307, 308, 309, 310, 311, 0, 312, 0, 0, 313, 0, 0, 314, 315, 0, 0, 316, 317, 318, 0, 0, 0, 158, 155, 163, 319, 320, 321, 322, 323, 324, 325, 0, 0, 326, 150, 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378 ] # This data has been taken literally from the files `glyphlist.txt' # and `zapfdingbats.txt' version 2.0, Sept 2002. It is available from # # http://sourceforge.net/adobe/aglfn/ # adobe_glyph_list = """\ A;0041 AE;00C6 AEacute;01FC AEmacron;01E2 AEsmall;F7E6 Aacute;00C1 Aacutesmall;F7E1 Abreve;0102 Abreveacute;1EAE Abrevecyrillic;04D0 Abrevedotbelow;1EB6 Abrevegrave;1EB0 Abrevehookabove;1EB2 Abrevetilde;1EB4 Acaron;01CD Acircle;24B6 Acircumflex;00C2 Acircumflexacute;1EA4 Acircumflexdotbelow;1EAC Acircumflexgrave;1EA6 Acircumflexhookabove;1EA8 Acircumflexsmall;F7E2 Acircumflextilde;1EAA Acute;F6C9 Acutesmall;F7B4 Acyrillic;0410 Adblgrave;0200 Adieresis;00C4 Adieresiscyrillic;04D2 Adieresismacron;01DE Adieresissmall;F7E4 Adotbelow;1EA0 Adotmacron;01E0 Agrave;00C0 Agravesmall;F7E0 Ahookabove;1EA2 Aiecyrillic;04D4 Ainvertedbreve;0202 Alpha;0391 Alphatonos;0386 Amacron;0100 Amonospace;FF21 Aogonek;0104 Aring;00C5 Aringacute;01FA Aringbelow;1E00 Aringsmall;F7E5 Asmall;F761 Atilde;00C3 Atildesmall;F7E3 Aybarmenian;0531 B;0042 Bcircle;24B7 Bdotaccent;1E02 Bdotbelow;1E04 Becyrillic;0411 Benarmenian;0532 Beta;0392 Bhook;0181 Blinebelow;1E06 Bmonospace;FF22 Brevesmall;F6F4 Bsmall;F762 Btopbar;0182 C;0043 Caarmenian;053E Cacute;0106 Caron;F6CA Caronsmall;F6F5 Ccaron;010C Ccedilla;00C7 Ccedillaacute;1E08 Ccedillasmall;F7E7 Ccircle;24B8 Ccircumflex;0108 Cdot;010A Cdotaccent;010A Cedillasmall;F7B8 Chaarmenian;0549 Cheabkhasiancyrillic;04BC Checyrillic;0427 Chedescenderabkhasiancyrillic;04BE Chedescendercyrillic;04B6 Chedieresiscyrillic;04F4 Cheharmenian;0543 Chekhakassiancyrillic;04CB Cheverticalstrokecyrillic;04B8 Chi;03A7 Chook;0187 Circumflexsmall;F6F6 Cmonospace;FF23 Coarmenian;0551 Csmall;F763 D;0044 DZ;01F1 DZcaron;01C4 Daarmenian;0534 Dafrican;0189 Dcaron;010E Dcedilla;1E10 Dcircle;24B9 Dcircumflexbelow;1E12 Dcroat;0110 Ddotaccent;1E0A Ddotbelow;1E0C Decyrillic;0414 Deicoptic;03EE Delta;2206 Deltagreek;0394 Dhook;018A Dieresis;F6CB DieresisAcute;F6CC DieresisGrave;F6CD Dieresissmall;F7A8 Digammagreek;03DC Djecyrillic;0402 Dlinebelow;1E0E Dmonospace;FF24 Dotaccentsmall;F6F7 Dslash;0110 Dsmall;F764 Dtopbar;018B Dz;01F2 Dzcaron;01C5 Dzeabkhasiancyrillic;04E0 Dzecyrillic;0405 Dzhecyrillic;040F E;0045 Eacute;00C9 Eacutesmall;F7E9 Ebreve;0114 Ecaron;011A Ecedillabreve;1E1C Echarmenian;0535 Ecircle;24BA Ecircumflex;00CA Ecircumflexacute;1EBE Ecircumflexbelow;1E18 Ecircumflexdotbelow;1EC6 Ecircumflexgrave;1EC0 Ecircumflexhookabove;1EC2 Ecircumflexsmall;F7EA Ecircumflextilde;1EC4 Ecyrillic;0404 Edblgrave;0204 Edieresis;00CB Edieresissmall;F7EB Edot;0116 Edotaccent;0116 Edotbelow;1EB8 Efcyrillic;0424 Egrave;00C8 Egravesmall;F7E8 Eharmenian;0537 Ehookabove;1EBA Eightroman;2167 Einvertedbreve;0206 Eiotifiedcyrillic;0464 Elcyrillic;041B Elevenroman;216A Emacron;0112 Emacronacute;1E16 Emacrongrave;1E14 Emcyrillic;041C Emonospace;FF25 Encyrillic;041D Endescendercyrillic;04A2 Eng;014A Enghecyrillic;04A4 Enhookcyrillic;04C7 Eogonek;0118 Eopen;0190 Epsilon;0395 Epsilontonos;0388 Ercyrillic;0420 Ereversed;018E Ereversedcyrillic;042D Escyrillic;0421 Esdescendercyrillic;04AA Esh;01A9 Esmall;F765 Eta;0397 Etarmenian;0538 Etatonos;0389 Eth;00D0 Ethsmall;F7F0 Etilde;1EBC Etildebelow;1E1A Euro;20AC Ezh;01B7 Ezhcaron;01EE Ezhreversed;01B8 F;0046 Fcircle;24BB Fdotaccent;1E1E Feharmenian;0556 Feicoptic;03E4 Fhook;0191 Fitacyrillic;0472 Fiveroman;2164 Fmonospace;FF26 Fourroman;2163 Fsmall;F766 G;0047 GBsquare;3387 Gacute;01F4 Gamma;0393 Gammaafrican;0194 Gangiacoptic;03EA Gbreve;011E Gcaron;01E6 Gcedilla;0122 Gcircle;24BC Gcircumflex;011C Gcommaaccent;0122 Gdot;0120 Gdotaccent;0120 Gecyrillic;0413 Ghadarmenian;0542 Ghemiddlehookcyrillic;0494 Ghestrokecyrillic;0492 Gheupturncyrillic;0490 Ghook;0193 Gimarmenian;0533 Gjecyrillic;0403 Gmacron;1E20 Gmonospace;FF27 Grave;F6CE Gravesmall;F760 Gsmall;F767 Gsmallhook;029B Gstroke;01E4 H;0048 H18533;25CF H18543;25AA H18551;25AB H22073;25A1 HPsquare;33CB Haabkhasiancyrillic;04A8 Hadescendercyrillic;04B2 Hardsigncyrillic;042A Hbar;0126 Hbrevebelow;1E2A Hcedilla;1E28 Hcircle;24BD Hcircumflex;0124 Hdieresis;1E26 Hdotaccent;1E22 Hdotbelow;1E24 Hmonospace;FF28 Hoarmenian;0540 Horicoptic;03E8 Hsmall;F768 Hungarumlaut;F6CF Hungarumlautsmall;F6F8 Hzsquare;3390 I;0049 IAcyrillic;042F IJ;0132 IUcyrillic;042E Iacute;00CD Iacutesmall;F7ED Ibreve;012C Icaron;01CF Icircle;24BE Icircumflex;00CE Icircumflexsmall;F7EE Icyrillic;0406 Idblgrave;0208 Idieresis;00CF Idieresisacute;1E2E Idieresiscyrillic;04E4 Idieresissmall;F7EF Idot;0130 Idotaccent;0130 Idotbelow;1ECA Iebrevecyrillic;04D6 Iecyrillic;0415 Ifraktur;2111 Igrave;00CC Igravesmall;F7EC Ihookabove;1EC8 Iicyrillic;0418 Iinvertedbreve;020A Iishortcyrillic;0419 Imacron;012A Imacroncyrillic;04E2 Imonospace;FF29 Iniarmenian;053B Iocyrillic;0401 Iogonek;012E Iota;0399 Iotaafrican;0196 Iotadieresis;03AA Iotatonos;038A Ismall;F769 Istroke;0197 Itilde;0128 Itildebelow;1E2C Izhitsacyrillic;0474 Izhitsadblgravecyrillic;0476 J;004A Jaarmenian;0541 Jcircle;24BF Jcircumflex;0134 Jecyrillic;0408 Jheharmenian;054B Jmonospace;FF2A Jsmall;F76A K;004B KBsquare;3385 KKsquare;33CD Kabashkircyrillic;04A0 Kacute;1E30 Kacyrillic;041A Kadescendercyrillic;049A Kahookcyrillic;04C3 Kappa;039A Kastrokecyrillic;049E Kaverticalstrokecyrillic;049C Kcaron;01E8 Kcedilla;0136 Kcircle;24C0 Kcommaaccent;0136 Kdotbelow;1E32 Keharmenian;0554 Kenarmenian;053F Khacyrillic;0425 Kheicoptic;03E6 Khook;0198 Kjecyrillic;040C Klinebelow;1E34 Kmonospace;FF2B Koppacyrillic;0480 Koppagreek;03DE Ksicyrillic;046E Ksmall;F76B L;004C LJ;01C7 LL;F6BF Lacute;0139 Lambda;039B Lcaron;013D Lcedilla;013B Lcircle;24C1 Lcircumflexbelow;1E3C Lcommaaccent;013B Ldot;013F Ldotaccent;013F Ldotbelow;1E36 Ldotbelowmacron;1E38 Liwnarmenian;053C Lj;01C8 Ljecyrillic;0409 Llinebelow;1E3A Lmonospace;FF2C Lslash;0141 Lslashsmall;F6F9 Lsmall;F76C M;004D MBsquare;3386 Macron;F6D0 Macronsmall;F7AF Macute;1E3E Mcircle;24C2 Mdotaccent;1E40 Mdotbelow;1E42 Menarmenian;0544 Mmonospace;FF2D Msmall;F76D Mturned;019C Mu;039C N;004E NJ;01CA Nacute;0143 Ncaron;0147 Ncedilla;0145 Ncircle;24C3 Ncircumflexbelow;1E4A Ncommaaccent;0145 Ndotaccent;1E44 Ndotbelow;1E46 Nhookleft;019D Nineroman;2168 Nj;01CB Njecyrillic;040A Nlinebelow;1E48 Nmonospace;FF2E Nowarmenian;0546 Nsmall;F76E Ntilde;00D1 Ntildesmall;F7F1 Nu;039D O;004F OE;0152 OEsmall;F6FA Oacute;00D3 Oacutesmall;F7F3 Obarredcyrillic;04E8 Obarreddieresiscyrillic;04EA Obreve;014E Ocaron;01D1 Ocenteredtilde;019F Ocircle;24C4 Ocircumflex;00D4 Ocircumflexacute;1ED0 Ocircumflexdotbelow;1ED8 Ocircumflexgrave;1ED2 Ocircumflexhookabove;1ED4 Ocircumflexsmall;F7F4 Ocircumflextilde;1ED6 Ocyrillic;041E Odblacute;0150 Odblgrave;020C Odieresis;00D6 Odieresiscyrillic;04E6 Odieresissmall;F7F6 Odotbelow;1ECC Ogoneksmall;F6FB Ograve;00D2 Ogravesmall;F7F2 Oharmenian;0555 Ohm;2126 Ohookabove;1ECE Ohorn;01A0 Ohornacute;1EDA Ohorndotbelow;1EE2 Ohorngrave;1EDC Ohornhookabove;1EDE Ohorntilde;1EE0 Ohungarumlaut;0150 Oi;01A2 Oinvertedbreve;020E Omacron;014C Omacronacute;1E52 Omacrongrave;1E50 Omega;2126 Omegacyrillic;0460 Omegagreek;03A9 Omegaroundcyrillic;047A Omegatitlocyrillic;047C Omegatonos;038F Omicron;039F Omicrontonos;038C Omonospace;FF2F Oneroman;2160 Oogonek;01EA Oogonekmacron;01EC Oopen;0186 Oslash;00D8 Oslashacute;01FE Oslashsmall;F7F8 Osmall;F76F Ostrokeacute;01FE Otcyrillic;047E Otilde;00D5 Otildeacute;1E4C Otildedieresis;1E4E Otildesmall;F7F5 P;0050 Pacute;1E54 Pcircle;24C5 Pdotaccent;1E56 Pecyrillic;041F Peharmenian;054A Pemiddlehookcyrillic;04A6 Phi;03A6 Phook;01A4 Pi;03A0 Piwrarmenian;0553 Pmonospace;FF30 Psi;03A8 Psicyrillic;0470 Psmall;F770 Q;0051 Qcircle;24C6 Qmonospace;FF31 Qsmall;F771 R;0052 Raarmenian;054C Racute;0154 Rcaron;0158 Rcedilla;0156 Rcircle;24C7 Rcommaaccent;0156 Rdblgrave;0210 Rdotaccent;1E58 Rdotbelow;1E5A Rdotbelowmacron;1E5C Reharmenian;0550 Rfraktur;211C Rho;03A1 Ringsmall;F6FC Rinvertedbreve;0212 Rlinebelow;1E5E Rmonospace;FF32 Rsmall;F772 Rsmallinverted;0281 Rsmallinvertedsuperior;02B6 S;0053 SF010000;250C SF020000;2514 SF030000;2510 SF040000;2518 SF050000;253C SF060000;252C SF070000;2534 SF080000;251C SF090000;2524 SF100000;2500 SF110000;2502 SF190000;2561 SF200000;2562 SF210000;2556 SF220000;2555 SF230000;2563 SF240000;2551 SF250000;2557 SF260000;255D SF270000;255C SF280000;255B SF360000;255E SF370000;255F SF380000;255A SF390000;2554 SF400000;2569 SF410000;2566 SF420000;2560 SF430000;2550 SF440000;256C SF450000;2567 SF460000;2568 SF470000;2564 SF480000;2565 SF490000;2559 SF500000;2558 SF510000;2552 SF520000;2553 SF530000;256B SF540000;256A Sacute;015A Sacutedotaccent;1E64 Sampigreek;03E0 Scaron;0160 Scarondotaccent;1E66 Scaronsmall;F6FD Scedilla;015E Schwa;018F Schwacyrillic;04D8 Schwadieresiscyrillic;04DA Scircle;24C8 Scircumflex;015C Scommaaccent;0218 Sdotaccent;1E60 Sdotbelow;1E62 Sdotbelowdotaccent;1E68 Seharmenian;054D Sevenroman;2166 Shaarmenian;0547 Shacyrillic;0428 Shchacyrillic;0429 Sheicoptic;03E2 Shhacyrillic;04BA Shimacoptic;03EC Sigma;03A3 Sixroman;2165 Smonospace;FF33 Softsigncyrillic;042C Ssmall;F773 Stigmagreek;03DA T;0054 Tau;03A4 Tbar;0166 Tcaron;0164 Tcedilla;0162 Tcircle;24C9 Tcircumflexbelow;1E70 Tcommaaccent;0162 Tdotaccent;1E6A Tdotbelow;1E6C Tecyrillic;0422 Tedescendercyrillic;04AC Tenroman;2169 Tetsecyrillic;04B4 Theta;0398 Thook;01AC Thorn;00DE Thornsmall;F7FE Threeroman;2162 Tildesmall;F6FE Tiwnarmenian;054F Tlinebelow;1E6E Tmonospace;FF34 Toarmenian;0539 Tonefive;01BC Tonesix;0184 Tonetwo;01A7 Tretroflexhook;01AE Tsecyrillic;0426 Tshecyrillic;040B Tsmall;F774 Twelveroman;216B Tworoman;2161 U;0055 Uacute;00DA Uacutesmall;F7FA Ubreve;016C Ucaron;01D3 Ucircle;24CA Ucircumflex;00DB Ucircumflexbelow;1E76 Ucircumflexsmall;F7FB Ucyrillic;0423 Udblacute;0170 Udblgrave;0214 Udieresis;00DC Udieresisacute;01D7 Udieresisbelow;1E72 Udieresiscaron;01D9 Udieresiscyrillic;04F0 Udieresisgrave;01DB Udieresismacron;01D5 Udieresissmall;F7FC Udotbelow;1EE4 Ugrave;00D9 Ugravesmall;F7F9 Uhookabove;1EE6 Uhorn;01AF Uhornacute;1EE8 Uhorndotbelow;1EF0 Uhorngrave;1EEA Uhornhookabove;1EEC Uhorntilde;1EEE Uhungarumlaut;0170 Uhungarumlautcyrillic;04F2 Uinvertedbreve;0216 Ukcyrillic;0478 Umacron;016A Umacroncyrillic;04EE Umacrondieresis;1E7A Umonospace;FF35 Uogonek;0172 Upsilon;03A5 Upsilon1;03D2 Upsilonacutehooksymbolgreek;03D3 Upsilonafrican;01B1 Upsilondieresis;03AB Upsilondieresishooksymbolgreek;03D4 Upsilonhooksymbol;03D2 Upsilontonos;038E Uring;016E Ushortcyrillic;040E Usmall;F775 Ustraightcyrillic;04AE Ustraightstrokecyrillic;04B0 Utilde;0168 Utildeacute;1E78 Utildebelow;1E74 V;0056 Vcircle;24CB Vdotbelow;1E7E Vecyrillic;0412 Vewarmenian;054E Vhook;01B2 Vmonospace;FF36 Voarmenian;0548 Vsmall;F776 Vtilde;1E7C W;0057 Wacute;1E82 Wcircle;24CC Wcircumflex;0174 Wdieresis;1E84 Wdotaccent;1E86 Wdotbelow;1E88 Wgrave;1E80 Wmonospace;FF37 Wsmall;F777 X;0058 Xcircle;24CD Xdieresis;1E8C Xdotaccent;1E8A Xeharmenian;053D Xi;039E Xmonospace;FF38 Xsmall;F778 Y;0059 Yacute;00DD Yacutesmall;F7FD Yatcyrillic;0462 Ycircle;24CE Ycircumflex;0176 Ydieresis;0178 Ydieresissmall;F7FF Ydotaccent;1E8E Ydotbelow;1EF4 Yericyrillic;042B Yerudieresiscyrillic;04F8 Ygrave;1EF2 Yhook;01B3 Yhookabove;1EF6 Yiarmenian;0545 Yicyrillic;0407 Yiwnarmenian;0552 Ymonospace;FF39 Ysmall;F779 Ytilde;1EF8 Yusbigcyrillic;046A Yusbigiotifiedcyrillic;046C Yuslittlecyrillic;0466 Yuslittleiotifiedcyrillic;0468 Z;005A Zaarmenian;0536 Zacute;0179 Zcaron;017D Zcaronsmall;F6FF Zcircle;24CF Zcircumflex;1E90 Zdot;017B Zdotaccent;017B Zdotbelow;1E92 Zecyrillic;0417 Zedescendercyrillic;0498 Zedieresiscyrillic;04DE Zeta;0396 Zhearmenian;053A Zhebrevecyrillic;04C1 Zhecyrillic;0416 Zhedescendercyrillic;0496 Zhedieresiscyrillic;04DC Zlinebelow;1E94 Zmonospace;FF3A Zsmall;F77A Zstroke;01B5 a;0061 aabengali;0986 aacute;00E1 aadeva;0906 aagujarati;0A86 aagurmukhi;0A06 aamatragurmukhi;0A3E aarusquare;3303 aavowelsignbengali;09BE aavowelsigndeva;093E aavowelsigngujarati;0ABE abbreviationmarkarmenian;055F abbreviationsigndeva;0970 abengali;0985 abopomofo;311A abreve;0103 abreveacute;1EAF abrevecyrillic;04D1 abrevedotbelow;1EB7 abrevegrave;1EB1 abrevehookabove;1EB3 abrevetilde;1EB5 acaron;01CE acircle;24D0 acircumflex;00E2 acircumflexacute;1EA5 acircumflexdotbelow;1EAD acircumflexgrave;1EA7 acircumflexhookabove;1EA9 acircumflextilde;1EAB acute;00B4 acutebelowcmb;0317 acutecmb;0301 acutecomb;0301 acutedeva;0954 acutelowmod;02CF acutetonecmb;0341 acyrillic;0430 adblgrave;0201 addakgurmukhi;0A71 adeva;0905 adieresis;00E4 adieresiscyrillic;04D3 adieresismacron;01DF adotbelow;1EA1 adotmacron;01E1 ae;00E6 aeacute;01FD aekorean;3150 aemacron;01E3 afii00208;2015 afii08941;20A4 afii10017;0410 afii10018;0411 afii10019;0412 afii10020;0413 afii10021;0414 afii10022;0415 afii10023;0401 afii10024;0416 afii10025;0417 afii10026;0418 afii10027;0419 afii10028;041A afii10029;041B afii10030;041C afii10031;041D afii10032;041E afii10033;041F afii10034;0420 afii10035;0421 afii10036;0422 afii10037;0423 afii10038;0424 afii10039;0425 afii10040;0426 afii10041;0427 afii10042;0428 afii10043;0429 afii10044;042A afii10045;042B afii10046;042C afii10047;042D afii10048;042E afii10049;042F afii10050;0490 afii10051;0402 afii10052;0403 afii10053;0404 afii10054;0405 afii10055;0406 afii10056;0407 afii10057;0408 afii10058;0409 afii10059;040A afii10060;040B afii10061;040C afii10062;040E afii10063;F6C4 afii10064;F6C5 afii10065;0430 afii10066;0431 afii10067;0432 afii10068;0433 afii10069;0434 afii10070;0435 afii10071;0451 afii10072;0436 afii10073;0437 afii10074;0438 afii10075;0439 afii10076;043A afii10077;043B afii10078;043C afii10079;043D afii10080;043E afii10081;043F afii10082;0440 afii10083;0441 afii10084;0442 afii10085;0443 afii10086;0444 afii10087;0445 afii10088;0446 afii10089;0447 afii10090;0448 afii10091;0449 afii10092;044A afii10093;044B afii10094;044C afii10095;044D afii10096;044E afii10097;044F afii10098;0491 afii10099;0452 afii10100;0453 afii10101;0454 afii10102;0455 afii10103;0456 afii10104;0457 afii10105;0458 afii10106;0459 afii10107;045A afii10108;045B afii10109;045C afii10110;045E afii10145;040F afii10146;0462 afii10147;0472 afii10148;0474 afii10192;F6C6 afii10193;045F afii10194;0463 afii10195;0473 afii10196;0475 afii10831;F6C7 afii10832;F6C8 afii10846;04D9 afii299;200E afii300;200F afii301;200D afii57381;066A afii57388;060C afii57392;0660 afii57393;0661 afii57394;0662 afii57395;0663 afii57396;0664 afii57397;0665 afii57398;0666 afii57399;0667 afii57400;0668 afii57401;0669 afii57403;061B afii57407;061F afii57409;0621 afii57410;0622 afii57411;0623 afii57412;0624 afii57413;0625 afii57414;0626 afii57415;0627 afii57416;0628 afii57417;0629 afii57418;062A afii57419;062B afii57420;062C afii57421;062D afii57422;062E afii57423;062F afii57424;0630 afii57425;0631 afii57426;0632 afii57427;0633 afii57428;0634 afii57429;0635 afii57430;0636 afii57431;0637 afii57432;0638 afii57433;0639 afii57434;063A afii57440;0640 afii57441;0641 afii57442;0642 afii57443;0643 afii57444;0644 afii57445;0645 afii57446;0646 afii57448;0648 afii57449;0649 afii57450;064A afii57451;064B afii57452;064C afii57453;064D afii57454;064E afii57455;064F afii57456;0650 afii57457;0651 afii57458;0652 afii57470;0647 afii57505;06A4 afii57506;067E afii57507;0686 afii57508;0698 afii57509;06AF afii57511;0679 afii57512;0688 afii57513;0691 afii57514;06BA afii57519;06D2 afii57534;06D5 afii57636;20AA afii57645;05BE afii57658;05C3 afii57664;05D0 afii57665;05D1 afii57666;05D2 afii57667;05D3 afii57668;05D4 afii57669;05D5 afii57670;05D6 afii57671;05D7 afii57672;05D8 afii57673;05D9 afii57674;05DA afii57675;05DB afii57676;05DC afii57677;05DD afii57678;05DE afii57679;05DF afii57680;05E0 afii57681;05E1 afii57682;05E2 afii57683;05E3 afii57684;05E4 afii57685;05E5 afii57686;05E6 afii57687;05E7 afii57688;05E8 afii57689;05E9 afii57690;05EA afii57694;FB2A afii57695;FB2B afii57700;FB4B afii57705;FB1F afii57716;05F0 afii57717;05F1 afii57718;05F2 afii57723;FB35 afii57793;05B4 afii57794;05B5 afii57795;05B6 afii57796;05BB afii57797;05B8 afii57798;05B7 afii57799;05B0 afii57800;05B2 afii57801;05B1 afii57802;05B3 afii57803;05C2 afii57804;05C1 afii57806;05B9 afii57807;05BC afii57839;05BD afii57841;05BF afii57842;05C0 afii57929;02BC afii61248;2105 afii61289;2113 afii61352;2116 afii61573;202C afii61574;202D afii61575;202E afii61664;200C afii63167;066D afii64937;02BD agrave;00E0 agujarati;0A85 agurmukhi;0A05 ahiragana;3042 ahookabove;1EA3 aibengali;0990 aibopomofo;311E aideva;0910 aiecyrillic;04D5 aigujarati;0A90 aigurmukhi;0A10 aimatragurmukhi;0A48 ainarabic;0639 ainfinalarabic;FECA aininitialarabic;FECB ainmedialarabic;FECC ainvertedbreve;0203 aivowelsignbengali;09C8 aivowelsigndeva;0948 aivowelsigngujarati;0AC8 akatakana;30A2 akatakanahalfwidth;FF71 akorean;314F alef;05D0 alefarabic;0627 alefdageshhebrew;FB30 aleffinalarabic;FE8E alefhamzaabovearabic;0623 alefhamzaabovefinalarabic;FE84 alefhamzabelowarabic;0625 alefhamzabelowfinalarabic;FE88 alefhebrew;05D0 aleflamedhebrew;FB4F alefmaddaabovearabic;0622 alefmaddaabovefinalarabic;FE82 alefmaksuraarabic;0649 alefmaksurafinalarabic;FEF0 alefmaksurainitialarabic;FEF3 alefmaksuramedialarabic;FEF4 alefpatahhebrew;FB2E alefqamatshebrew;FB2F aleph;2135 allequal;224C alpha;03B1 alphatonos;03AC amacron;0101 amonospace;FF41 ampersand;0026 ampersandmonospace;FF06 ampersandsmall;F726 amsquare;33C2 anbopomofo;3122 angbopomofo;3124 angkhankhuthai;0E5A angle;2220 anglebracketleft;3008 anglebracketleftvertical;FE3F anglebracketright;3009 anglebracketrightvertical;FE40 angleleft;2329 angleright;232A angstrom;212B anoteleia;0387 anudattadeva;0952 anusvarabengali;0982 anusvaradeva;0902 anusvaragujarati;0A82 aogonek;0105 apaatosquare;3300 aparen;249C apostrophearmenian;055A apostrophemod;02BC apple;F8FF approaches;2250 approxequal;2248 approxequalorimage;2252 approximatelyequal;2245 araeaekorean;318E araeakorean;318D arc;2312 arighthalfring;1E9A aring;00E5 aringacute;01FB aringbelow;1E01 arrowboth;2194 arrowdashdown;21E3 arrowdashleft;21E0 arrowdashright;21E2 arrowdashup;21E1 arrowdblboth;21D4 arrowdbldown;21D3 arrowdblleft;21D0 arrowdblright;21D2 arrowdblup;21D1 arrowdown;2193 arrowdownleft;2199 arrowdownright;2198 arrowdownwhite;21E9 arrowheaddownmod;02C5 arrowheadleftmod;02C2 arrowheadrightmod;02C3 arrowheadupmod;02C4 arrowhorizex;F8E7 arrowleft;2190 arrowleftdbl;21D0 arrowleftdblstroke;21CD arrowleftoverright;21C6 arrowleftwhite;21E6 arrowright;2192 arrowrightdblstroke;21CF arrowrightheavy;279E arrowrightoverleft;21C4 arrowrightwhite;21E8 arrowtableft;21E4 arrowtabright;21E5 arrowup;2191 arrowupdn;2195 arrowupdnbse;21A8 arrowupdownbase;21A8 arrowupleft;2196 arrowupleftofdown;21C5 arrowupright;2197 arrowupwhite;21E7 arrowvertex;F8E6 asciicircum;005E asciicircummonospace;FF3E asciitilde;007E asciitildemonospace;FF5E ascript;0251 ascriptturned;0252 asmallhiragana;3041 asmallkatakana;30A1 asmallkatakanahalfwidth;FF67 asterisk;002A asteriskaltonearabic;066D asteriskarabic;066D asteriskmath;2217 asteriskmonospace;FF0A asterisksmall;FE61 asterism;2042 asuperior;F6E9 asymptoticallyequal;2243 at;0040 atilde;00E3 atmonospace;FF20 atsmall;FE6B aturned;0250 aubengali;0994 aubopomofo;3120 audeva;0914 augujarati;0A94 augurmukhi;0A14 aulengthmarkbengali;09D7 aumatragurmukhi;0A4C auvowelsignbengali;09CC auvowelsigndeva;094C auvowelsigngujarati;0ACC avagrahadeva;093D aybarmenian;0561 ayin;05E2 ayinaltonehebrew;FB20 ayinhebrew;05E2 b;0062 babengali;09AC backslash;005C backslashmonospace;FF3C badeva;092C bagujarati;0AAC bagurmukhi;0A2C bahiragana;3070 bahtthai;0E3F bakatakana;30D0 bar;007C barmonospace;FF5C bbopomofo;3105 bcircle;24D1 bdotaccent;1E03 bdotbelow;1E05 beamedsixteenthnotes;266C because;2235 becyrillic;0431 beharabic;0628 behfinalarabic;FE90 behinitialarabic;FE91 behiragana;3079 behmedialarabic;FE92 behmeeminitialarabic;FC9F behmeemisolatedarabic;FC08 behnoonfinalarabic;FC6D bekatakana;30D9 benarmenian;0562 bet;05D1 beta;03B2 betasymbolgreek;03D0 betdagesh;FB31 betdageshhebrew;FB31 bethebrew;05D1 betrafehebrew;FB4C bhabengali;09AD bhadeva;092D bhagujarati;0AAD bhagurmukhi;0A2D bhook;0253 bihiragana;3073 bikatakana;30D3 bilabialclick;0298 bindigurmukhi;0A02 birusquare;3331 blackcircle;25CF blackdiamond;25C6 blackdownpointingtriangle;25BC blackleftpointingpointer;25C4 blackleftpointingtriangle;25C0 blacklenticularbracketleft;3010 blacklenticularbracketleftvertical;FE3B blacklenticularbracketright;3011 blacklenticularbracketrightvertical;FE3C blacklowerlefttriangle;25E3 blacklowerrighttriangle;25E2 blackrectangle;25AC blackrightpointingpointer;25BA blackrightpointingtriangle;25B6 blacksmallsquare;25AA blacksmilingface;263B blacksquare;25A0 blackstar;2605 blackupperlefttriangle;25E4 blackupperrighttriangle;25E5 blackuppointingsmalltriangle;25B4 blackuppointingtriangle;25B2 blank;2423 blinebelow;1E07 block;2588 bmonospace;FF42 bobaimaithai;0E1A bohiragana;307C bokatakana;30DC bparen;249D bqsquare;33C3 braceex;F8F4 braceleft;007B braceleftbt;F8F3 braceleftmid;F8F2 braceleftmonospace;FF5B braceleftsmall;FE5B bracelefttp;F8F1 braceleftvertical;FE37 braceright;007D bracerightbt;F8FE bracerightmid;F8FD bracerightmonospace;FF5D bracerightsmall;FE5C bracerighttp;F8FC bracerightvertical;FE38 bracketleft;005B bracketleftbt;F8F0 bracketleftex;F8EF bracketleftmonospace;FF3B bracketlefttp;F8EE bracketright;005D bracketrightbt;F8FB bracketrightex;F8FA bracketrightmonospace;FF3D bracketrighttp;F8F9 breve;02D8 brevebelowcmb;032E brevecmb;0306 breveinvertedbelowcmb;032F breveinvertedcmb;0311 breveinverteddoublecmb;0361 bridgebelowcmb;032A bridgeinvertedbelowcmb;033A brokenbar;00A6 bstroke;0180 bsuperior;F6EA btopbar;0183 buhiragana;3076 bukatakana;30D6 bullet;2022 bulletinverse;25D8 bulletoperator;2219 bullseye;25CE c;0063 caarmenian;056E cabengali;099A cacute;0107 cadeva;091A cagujarati;0A9A cagurmukhi;0A1A calsquare;3388 candrabindubengali;0981 candrabinducmb;0310 candrabindudeva;0901 candrabindugujarati;0A81 capslock;21EA careof;2105 caron;02C7 caronbelowcmb;032C caroncmb;030C carriagereturn;21B5 cbopomofo;3118 ccaron;010D ccedilla;00E7 ccedillaacute;1E09 ccircle;24D2 ccircumflex;0109 ccurl;0255 cdot;010B cdotaccent;010B cdsquare;33C5 cedilla;00B8 cedillacmb;0327 cent;00A2 centigrade;2103 centinferior;F6DF centmonospace;FFE0 centoldstyle;F7A2 centsuperior;F6E0 chaarmenian;0579 chabengali;099B chadeva;091B chagujarati;0A9B chagurmukhi;0A1B chbopomofo;3114 cheabkhasiancyrillic;04BD checkmark;2713 checyrillic;0447 chedescenderabkhasiancyrillic;04BF chedescendercyrillic;04B7 chedieresiscyrillic;04F5 cheharmenian;0573 chekhakassiancyrillic;04CC cheverticalstrokecyrillic;04B9 chi;03C7 chieuchacirclekorean;3277 chieuchaparenkorean;3217 chieuchcirclekorean;3269 chieuchkorean;314A chieuchparenkorean;3209 chochangthai;0E0A chochanthai;0E08 chochingthai;0E09 chochoethai;0E0C chook;0188 cieucacirclekorean;3276 cieucaparenkorean;3216 cieuccirclekorean;3268 cieuckorean;3148 cieucparenkorean;3208 cieucuparenkorean;321C circle;25CB circlemultiply;2297 circleot;2299 circleplus;2295 circlepostalmark;3036 circlewithlefthalfblack;25D0 circlewithrighthalfblack;25D1 circumflex;02C6 circumflexbelowcmb;032D circumflexcmb;0302 clear;2327 clickalveolar;01C2 clickdental;01C0 clicklateral;01C1 clickretroflex;01C3 club;2663 clubsuitblack;2663 clubsuitwhite;2667 cmcubedsquare;33A4 cmonospace;FF43 cmsquaredsquare;33A0 coarmenian;0581 colon;003A colonmonetary;20A1 colonmonospace;FF1A colonsign;20A1 colonsmall;FE55 colontriangularhalfmod;02D1 colontriangularmod;02D0 comma;002C commaabovecmb;0313 commaaboverightcmb;0315 commaaccent;F6C3 commaarabic;060C commaarmenian;055D commainferior;F6E1 commamonospace;FF0C commareversedabovecmb;0314 commareversedmod;02BD commasmall;FE50 commasuperior;F6E2 commaturnedabovecmb;0312 commaturnedmod;02BB compass;263C congruent;2245 contourintegral;222E control;2303 controlACK;0006 controlBEL;0007 controlBS;0008 controlCAN;0018 controlCR;000D controlDC1;0011 controlDC2;0012 controlDC3;0013 controlDC4;0014 controlDEL;007F controlDLE;0010 controlEM;0019 controlENQ;0005 controlEOT;0004 controlESC;001B controlETB;0017 controlETX;0003 controlFF;000C controlFS;001C controlGS;001D controlHT;0009 controlLF;000A controlNAK;0015 controlRS;001E controlSI;000F controlSO;000E controlSOT;0002 controlSTX;0001 controlSUB;001A controlSYN;0016 controlUS;001F controlVT;000B copyright;00A9 copyrightsans;F8E9 copyrightserif;F6D9 cornerbracketleft;300C cornerbracketlefthalfwidth;FF62 cornerbracketleftvertical;FE41 cornerbracketright;300D cornerbracketrighthalfwidth;FF63 cornerbracketrightvertical;FE42 corporationsquare;337F cosquare;33C7 coverkgsquare;33C6 cparen;249E cruzeiro;20A2 cstretched;0297 curlyand;22CF curlyor;22CE currency;00A4 cyrBreve;F6D1 cyrFlex;F6D2 cyrbreve;F6D4 cyrflex;F6D5 d;0064 daarmenian;0564 dabengali;09A6 dadarabic;0636 dadeva;0926 dadfinalarabic;FEBE dadinitialarabic;FEBF dadmedialarabic;FEC0 dagesh;05BC dageshhebrew;05BC dagger;2020 daggerdbl;2021 dagujarati;0AA6 dagurmukhi;0A26 dahiragana;3060 dakatakana;30C0 dalarabic;062F dalet;05D3 daletdagesh;FB33 daletdageshhebrew;FB33 dalethatafpatah;05D3 05B2 dalethatafpatahhebrew;05D3 05B2 dalethatafsegol;05D3 05B1 dalethatafsegolhebrew;05D3 05B1 dalethebrew;05D3 dalethiriq;05D3 05B4 dalethiriqhebrew;05D3 05B4 daletholam;05D3 05B9 daletholamhebrew;05D3 05B9 daletpatah;05D3 05B7 daletpatahhebrew;05D3 05B7 daletqamats;05D3 05B8 daletqamatshebrew;05D3 05B8 daletqubuts;05D3 05BB daletqubutshebrew;05D3 05BB daletsegol;05D3 05B6 daletsegolhebrew;05D3 05B6 daletsheva;05D3 05B0 daletshevahebrew;05D3 05B0 dalettsere;05D3 05B5 dalettserehebrew;05D3 05B5 dalfinalarabic;FEAA dammaarabic;064F dammalowarabic;064F dammatanaltonearabic;064C dammatanarabic;064C danda;0964 dargahebrew;05A7 dargalefthebrew;05A7 dasiapneumatacyrilliccmb;0485 dblGrave;F6D3 dblanglebracketleft;300A dblanglebracketleftvertical;FE3D dblanglebracketright;300B dblanglebracketrightvertical;FE3E dblarchinvertedbelowcmb;032B dblarrowleft;21D4 dblarrowright;21D2 dbldanda;0965 dblgrave;F6D6 dblgravecmb;030F dblintegral;222C dbllowline;2017 dbllowlinecmb;0333 dbloverlinecmb;033F dblprimemod;02BA dblverticalbar;2016 dblverticallineabovecmb;030E dbopomofo;3109 dbsquare;33C8 dcaron;010F dcedilla;1E11 dcircle;24D3 dcircumflexbelow;1E13 dcroat;0111 ddabengali;09A1 ddadeva;0921 ddagujarati;0AA1 ddagurmukhi;0A21 ddalarabic;0688 ddalfinalarabic;FB89 dddhadeva;095C ddhabengali;09A2 ddhadeva;0922 ddhagujarati;0AA2 ddhagurmukhi;0A22 ddotaccent;1E0B ddotbelow;1E0D decimalseparatorarabic;066B decimalseparatorpersian;066B decyrillic;0434 degree;00B0 dehihebrew;05AD dehiragana;3067 deicoptic;03EF dekatakana;30C7 deleteleft;232B deleteright;2326 delta;03B4 deltaturned;018D denominatorminusonenumeratorbengali;09F8 dezh;02A4 dhabengali;09A7 dhadeva;0927 dhagujarati;0AA7 dhagurmukhi;0A27 dhook;0257 dialytikatonos;0385 dialytikatonoscmb;0344 diamond;2666 diamondsuitwhite;2662 dieresis;00A8 dieresisacute;F6D7 dieresisbelowcmb;0324 dieresiscmb;0308 dieresisgrave;F6D8 dieresistonos;0385 dihiragana;3062 dikatakana;30C2 dittomark;3003 divide;00F7 divides;2223 divisionslash;2215 djecyrillic;0452 dkshade;2593 dlinebelow;1E0F dlsquare;3397 dmacron;0111 dmonospace;FF44 dnblock;2584 dochadathai;0E0E dodekthai;0E14 dohiragana;3069 dokatakana;30C9 dollar;0024 dollarinferior;F6E3 dollarmonospace;FF04 dollaroldstyle;F724 dollarsmall;FE69 dollarsuperior;F6E4 dong;20AB dorusquare;3326 dotaccent;02D9 dotaccentcmb;0307 dotbelowcmb;0323 dotbelowcomb;0323 dotkatakana;30FB dotlessi;0131 dotlessj;F6BE dotlessjstrokehook;0284 dotmath;22C5 dottedcircle;25CC doubleyodpatah;FB1F doubleyodpatahhebrew;FB1F downtackbelowcmb;031E downtackmod;02D5 dparen;249F dsuperior;F6EB dtail;0256 dtopbar;018C duhiragana;3065 dukatakana;30C5 dz;01F3 dzaltone;02A3 dzcaron;01C6 dzcurl;02A5 dzeabkhasiancyrillic;04E1 dzecyrillic;0455 dzhecyrillic;045F e;0065 eacute;00E9 earth;2641 ebengali;098F ebopomofo;311C ebreve;0115 ecandradeva;090D ecandragujarati;0A8D ecandravowelsigndeva;0945 ecandravowelsigngujarati;0AC5 ecaron;011B ecedillabreve;1E1D echarmenian;0565 echyiwnarmenian;0587 ecircle;24D4 ecircumflex;00EA ecircumflexacute;1EBF ecircumflexbelow;1E19 ecircumflexdotbelow;1EC7 ecircumflexgrave;1EC1 ecircumflexhookabove;1EC3 ecircumflextilde;1EC5 ecyrillic;0454 edblgrave;0205 edeva;090F edieresis;00EB edot;0117 edotaccent;0117 edotbelow;1EB9 eegurmukhi;0A0F eematragurmukhi;0A47 efcyrillic;0444 egrave;00E8 egujarati;0A8F eharmenian;0567 ehbopomofo;311D ehiragana;3048 ehookabove;1EBB eibopomofo;311F eight;0038 eightarabic;0668 eightbengali;09EE eightcircle;2467 eightcircleinversesansserif;2791 eightdeva;096E eighteencircle;2471 eighteenparen;2485 eighteenperiod;2499 eightgujarati;0AEE eightgurmukhi;0A6E eighthackarabic;0668 eighthangzhou;3028 eighthnotebeamed;266B eightideographicparen;3227 eightinferior;2088 eightmonospace;FF18 eightoldstyle;F738 eightparen;247B eightperiod;248F eightpersian;06F8 eightroman;2177 eightsuperior;2078 eightthai;0E58 einvertedbreve;0207 eiotifiedcyrillic;0465 ekatakana;30A8 ekatakanahalfwidth;FF74 ekonkargurmukhi;0A74 ekorean;3154 elcyrillic;043B element;2208 elevencircle;246A elevenparen;247E elevenperiod;2492 elevenroman;217A ellipsis;2026 ellipsisvertical;22EE emacron;0113 emacronacute;1E17 emacrongrave;1E15 emcyrillic;043C emdash;2014 emdashvertical;FE31 emonospace;FF45 emphasismarkarmenian;055B emptyset;2205 enbopomofo;3123 encyrillic;043D endash;2013 endashvertical;FE32 endescendercyrillic;04A3 eng;014B engbopomofo;3125 enghecyrillic;04A5 enhookcyrillic;04C8 enspace;2002 eogonek;0119 eokorean;3153 eopen;025B eopenclosed;029A eopenreversed;025C eopenreversedclosed;025E eopenreversedhook;025D eparen;24A0 epsilon;03B5 epsilontonos;03AD equal;003D equalmonospace;FF1D equalsmall;FE66 equalsuperior;207C equivalence;2261 erbopomofo;3126 ercyrillic;0440 ereversed;0258 ereversedcyrillic;044D escyrillic;0441 esdescendercyrillic;04AB esh;0283 eshcurl;0286 eshortdeva;090E eshortvowelsigndeva;0946 eshreversedloop;01AA eshsquatreversed;0285 esmallhiragana;3047 esmallkatakana;30A7 esmallkatakanahalfwidth;FF6A estimated;212E esuperior;F6EC eta;03B7 etarmenian;0568 etatonos;03AE eth;00F0 etilde;1EBD etildebelow;1E1B etnahtafoukhhebrew;0591 etnahtafoukhlefthebrew;0591 etnahtahebrew;0591 etnahtalefthebrew;0591 eturned;01DD eukorean;3161 euro;20AC evowelsignbengali;09C7 evowelsigndeva;0947 evowelsigngujarati;0AC7 exclam;0021 exclamarmenian;055C exclamdbl;203C exclamdown;00A1 exclamdownsmall;F7A1 exclammonospace;FF01 exclamsmall;F721 existential;2203 ezh;0292 ezhcaron;01EF ezhcurl;0293 ezhreversed;01B9 ezhtail;01BA f;0066 fadeva;095E fagurmukhi;0A5E fahrenheit;2109 fathaarabic;064E fathalowarabic;064E fathatanarabic;064B fbopomofo;3108 fcircle;24D5 fdotaccent;1E1F feharabic;0641 feharmenian;0586 fehfinalarabic;FED2 fehinitialarabic;FED3 fehmedialarabic;FED4 feicoptic;03E5 female;2640 ff;FB00 ffi;FB03 ffl;FB04 fi;FB01 fifteencircle;246E fifteenparen;2482 fifteenperiod;2496 figuredash;2012 filledbox;25A0 filledrect;25AC finalkaf;05DA finalkafdagesh;FB3A finalkafdageshhebrew;FB3A finalkafhebrew;05DA finalkafqamats;05DA 05B8 finalkafqamatshebrew;05DA 05B8 finalkafsheva;05DA 05B0 finalkafshevahebrew;05DA 05B0 finalmem;05DD finalmemhebrew;05DD finalnun;05DF finalnunhebrew;05DF finalpe;05E3 finalpehebrew;05E3 finaltsadi;05E5 finaltsadihebrew;05E5 firsttonechinese;02C9 fisheye;25C9 fitacyrillic;0473 five;0035 fivearabic;0665 fivebengali;09EB fivecircle;2464 fivecircleinversesansserif;278E fivedeva;096B fiveeighths;215D fivegujarati;0AEB fivegurmukhi;0A6B fivehackarabic;0665 fivehangzhou;3025 fiveideographicparen;3224 fiveinferior;2085 fivemonospace;FF15 fiveoldstyle;F735 fiveparen;2478 fiveperiod;248C fivepersian;06F5 fiveroman;2174 fivesuperior;2075 fivethai;0E55 fl;FB02 florin;0192 fmonospace;FF46 fmsquare;3399 fofanthai;0E1F fofathai;0E1D fongmanthai;0E4F forall;2200 four;0034 fourarabic;0664 fourbengali;09EA fourcircle;2463 fourcircleinversesansserif;278D fourdeva;096A fourgujarati;0AEA fourgurmukhi;0A6A fourhackarabic;0664 fourhangzhou;3024 fourideographicparen;3223 fourinferior;2084 fourmonospace;FF14 fournumeratorbengali;09F7 fouroldstyle;F734 fourparen;2477 fourperiod;248B fourpersian;06F4 fourroman;2173 foursuperior;2074 fourteencircle;246D fourteenparen;2481 fourteenperiod;2495 fourthai;0E54 fourthtonechinese;02CB fparen;24A1 fraction;2044 franc;20A3 g;0067 gabengali;0997 gacute;01F5 gadeva;0917 gafarabic;06AF gaffinalarabic;FB93 gafinitialarabic;FB94 gafmedialarabic;FB95 gagujarati;0A97 gagurmukhi;0A17 gahiragana;304C gakatakana;30AC gamma;03B3 gammalatinsmall;0263 gammasuperior;02E0 gangiacoptic;03EB gbopomofo;310D gbreve;011F gcaron;01E7 gcedilla;0123 gcircle;24D6 gcircumflex;011D gcommaaccent;0123 gdot;0121 gdotaccent;0121 gecyrillic;0433 gehiragana;3052 gekatakana;30B2 geometricallyequal;2251 gereshaccenthebrew;059C gereshhebrew;05F3 gereshmuqdamhebrew;059D germandbls;00DF gershayimaccenthebrew;059E gershayimhebrew;05F4 getamark;3013 ghabengali;0998 ghadarmenian;0572 ghadeva;0918 ghagujarati;0A98 ghagurmukhi;0A18 ghainarabic;063A ghainfinalarabic;FECE ghaininitialarabic;FECF ghainmedialarabic;FED0 ghemiddlehookcyrillic;0495 ghestrokecyrillic;0493 gheupturncyrillic;0491 ghhadeva;095A ghhagurmukhi;0A5A ghook;0260 ghzsquare;3393 gihiragana;304E gikatakana;30AE gimarmenian;0563 gimel;05D2 gimeldagesh;FB32 gimeldageshhebrew;FB32 gimelhebrew;05D2 gjecyrillic;0453 glottalinvertedstroke;01BE glottalstop;0294 glottalstopinverted;0296 glottalstopmod;02C0 glottalstopreversed;0295 glottalstopreversedmod;02C1 glottalstopreversedsuperior;02E4 glottalstopstroke;02A1 glottalstopstrokereversed;02A2 gmacron;1E21 gmonospace;FF47 gohiragana;3054 gokatakana;30B4 gparen;24A2 gpasquare;33AC gradient;2207 grave;0060 gravebelowcmb;0316 gravecmb;0300 gravecomb;0300 gravedeva;0953 gravelowmod;02CE gravemonospace;FF40 gravetonecmb;0340 greater;003E greaterequal;2265 greaterequalorless;22DB greatermonospace;FF1E greaterorequivalent;2273 greaterorless;2277 greateroverequal;2267 greatersmall;FE65 gscript;0261 gstroke;01E5 guhiragana;3050 guillemotleft;00AB guillemotright;00BB guilsinglleft;2039 guilsinglright;203A gukatakana;30B0 guramusquare;3318 gysquare;33C9 h;0068 haabkhasiancyrillic;04A9 haaltonearabic;06C1 habengali;09B9 hadescendercyrillic;04B3 hadeva;0939 hagujarati;0AB9 hagurmukhi;0A39 haharabic;062D hahfinalarabic;FEA2 hahinitialarabic;FEA3 hahiragana;306F hahmedialarabic;FEA4 haitusquare;332A hakatakana;30CF hakatakanahalfwidth;FF8A halantgurmukhi;0A4D hamzaarabic;0621 hamzadammaarabic;0621 064F hamzadammatanarabic;0621 064C hamzafathaarabic;0621 064E hamzafathatanarabic;0621 064B hamzalowarabic;0621 hamzalowkasraarabic;0621 0650 hamzalowkasratanarabic;0621 064D hamzasukunarabic;0621 0652 hangulfiller;3164 hardsigncyrillic;044A harpoonleftbarbup;21BC harpoonrightbarbup;21C0 hasquare;33CA hatafpatah;05B2 hatafpatah16;05B2 hatafpatah23;05B2 hatafpatah2f;05B2 hatafpatahhebrew;05B2 hatafpatahnarrowhebrew;05B2 hatafpatahquarterhebrew;05B2 hatafpatahwidehebrew;05B2 hatafqamats;05B3 hatafqamats1b;05B3 hatafqamats28;05B3 hatafqamats34;05B3 hatafqamatshebrew;05B3 hatafqamatsnarrowhebrew;05B3 hatafqamatsquarterhebrew;05B3 hatafqamatswidehebrew;05B3 hatafsegol;05B1 hatafsegol17;05B1 hatafsegol24;05B1 hatafsegol30;05B1 hatafsegolhebrew;05B1 hatafsegolnarrowhebrew;05B1 hatafsegolquarterhebrew;05B1 hatafsegolwidehebrew;05B1 hbar;0127 hbopomofo;310F hbrevebelow;1E2B hcedilla;1E29 hcircle;24D7 hcircumflex;0125 hdieresis;1E27 hdotaccent;1E23 hdotbelow;1E25 he;05D4 heart;2665 heartsuitblack;2665 heartsuitwhite;2661 hedagesh;FB34 hedageshhebrew;FB34 hehaltonearabic;06C1 heharabic;0647 hehebrew;05D4 hehfinalaltonearabic;FBA7 hehfinalalttwoarabic;FEEA hehfinalarabic;FEEA hehhamzaabovefinalarabic;FBA5 hehhamzaaboveisolatedarabic;FBA4 hehinitialaltonearabic;FBA8 hehinitialarabic;FEEB hehiragana;3078 hehmedialaltonearabic;FBA9 hehmedialarabic;FEEC heiseierasquare;337B hekatakana;30D8 hekatakanahalfwidth;FF8D hekutaarusquare;3336 henghook;0267 herutusquare;3339 het;05D7 hethebrew;05D7 hhook;0266 hhooksuperior;02B1 hieuhacirclekorean;327B hieuhaparenkorean;321B hieuhcirclekorean;326D hieuhkorean;314E hieuhparenkorean;320D hihiragana;3072 hikatakana;30D2 hikatakanahalfwidth;FF8B hiriq;05B4 hiriq14;05B4 hiriq21;05B4 hiriq2d;05B4 hiriqhebrew;05B4 hiriqnarrowhebrew;05B4 hiriqquarterhebrew;05B4 hiriqwidehebrew;05B4 hlinebelow;1E96 hmonospace;FF48 hoarmenian;0570 hohipthai;0E2B hohiragana;307B hokatakana;30DB hokatakanahalfwidth;FF8E holam;05B9 holam19;05B9 holam26;05B9 holam32;05B9 holamhebrew;05B9 holamnarrowhebrew;05B9 holamquarterhebrew;05B9 holamwidehebrew;05B9 honokhukthai;0E2E hookabovecomb;0309 hookcmb;0309 hookpalatalizedbelowcmb;0321 hookretroflexbelowcmb;0322 hoonsquare;3342 horicoptic;03E9 horizontalbar;2015 horncmb;031B hotsprings;2668 house;2302 hparen;24A3 hsuperior;02B0 hturned;0265 huhiragana;3075 huiitosquare;3333 hukatakana;30D5 hukatakanahalfwidth;FF8C hungarumlaut;02DD hungarumlautcmb;030B hv;0195 hyphen;002D hypheninferior;F6E5 hyphenmonospace;FF0D hyphensmall;FE63 hyphensuperior;F6E6 hyphentwo;2010 i;0069 iacute;00ED iacyrillic;044F ibengali;0987 ibopomofo;3127 ibreve;012D icaron;01D0 icircle;24D8 icircumflex;00EE icyrillic;0456 idblgrave;0209 ideographearthcircle;328F ideographfirecircle;328B ideographicallianceparen;323F ideographiccallparen;323A ideographiccentrecircle;32A5 ideographicclose;3006 ideographiccomma;3001 ideographiccommaleft;FF64 ideographiccongratulationparen;3237 ideographiccorrectcircle;32A3 ideographicearthparen;322F ideographicenterpriseparen;323D ideographicexcellentcircle;329D ideographicfestivalparen;3240 ideographicfinancialcircle;3296 ideographicfinancialparen;3236 ideographicfireparen;322B ideographichaveparen;3232 ideographichighcircle;32A4 ideographiciterationmark;3005 ideographiclaborcircle;3298 ideographiclaborparen;3238 ideographicleftcircle;32A7 ideographiclowcircle;32A6 ideographicmedicinecircle;32A9 ideographicmetalparen;322E ideographicmoonparen;322A ideographicnameparen;3234 ideographicperiod;3002 ideographicprintcircle;329E ideographicreachparen;3243 ideographicrepresentparen;3239 ideographicresourceparen;323E ideographicrightcircle;32A8 ideographicsecretcircle;3299 ideographicselfparen;3242 ideographicsocietyparen;3233 ideographicspace;3000 ideographicspecialparen;3235 ideographicstockparen;3231 ideographicstudyparen;323B ideographicsunparen;3230 ideographicsuperviseparen;323C ideographicwaterparen;322C ideographicwoodparen;322D ideographiczero;3007 ideographmetalcircle;328E ideographmooncircle;328A ideographnamecircle;3294 ideographsuncircle;3290 ideographwatercircle;328C ideographwoodcircle;328D ideva;0907 idieresis;00EF idieresisacute;1E2F idieresiscyrillic;04E5 idotbelow;1ECB iebrevecyrillic;04D7 iecyrillic;0435 ieungacirclekorean;3275 ieungaparenkorean;3215 ieungcirclekorean;3267 ieungkorean;3147 ieungparenkorean;3207 igrave;00EC igujarati;0A87 igurmukhi;0A07 ihiragana;3044 ihookabove;1EC9 iibengali;0988 iicyrillic;0438 iideva;0908 iigujarati;0A88 iigurmukhi;0A08 iimatragurmukhi;0A40 iinvertedbreve;020B iishortcyrillic;0439 iivowelsignbengali;09C0 iivowelsigndeva;0940 iivowelsigngujarati;0AC0 ij;0133 ikatakana;30A4 ikatakanahalfwidth;FF72 ikorean;3163 ilde;02DC iluyhebrew;05AC imacron;012B imacroncyrillic;04E3 imageorapproximatelyequal;2253 imatragurmukhi;0A3F imonospace;FF49 increment;2206 infinity;221E iniarmenian;056B integral;222B integralbottom;2321 integralbt;2321 integralex;F8F5 integraltop;2320 integraltp;2320 intersection;2229 intisquare;3305 invbullet;25D8 invcircle;25D9 invsmileface;263B iocyrillic;0451 iogonek;012F iota;03B9 iotadieresis;03CA iotadieresistonos;0390 iotalatin;0269 iotatonos;03AF iparen;24A4 irigurmukhi;0A72 ismallhiragana;3043 ismallkatakana;30A3 ismallkatakanahalfwidth;FF68 issharbengali;09FA istroke;0268 isuperior;F6ED iterationhiragana;309D iterationkatakana;30FD itilde;0129 itildebelow;1E2D iubopomofo;3129 iucyrillic;044E ivowelsignbengali;09BF ivowelsigndeva;093F ivowelsigngujarati;0ABF izhitsacyrillic;0475 izhitsadblgravecyrillic;0477 j;006A jaarmenian;0571 jabengali;099C jadeva;091C jagujarati;0A9C jagurmukhi;0A1C jbopomofo;3110 jcaron;01F0 jcircle;24D9 jcircumflex;0135 jcrossedtail;029D jdotlessstroke;025F jecyrillic;0458 jeemarabic;062C jeemfinalarabic;FE9E jeeminitialarabic;FE9F jeemmedialarabic;FEA0 jeharabic;0698 jehfinalarabic;FB8B jhabengali;099D jhadeva;091D jhagujarati;0A9D jhagurmukhi;0A1D jheharmenian;057B jis;3004 jmonospace;FF4A jparen;24A5 jsuperior;02B2 k;006B kabashkircyrillic;04A1 kabengali;0995 kacute;1E31 kacyrillic;043A kadescendercyrillic;049B kadeva;0915 kaf;05DB kafarabic;0643 kafdagesh;FB3B kafdageshhebrew;FB3B kaffinalarabic;FEDA kafhebrew;05DB kafinitialarabic;FEDB kafmedialarabic;FEDC kafrafehebrew;FB4D kagujarati;0A95 kagurmukhi;0A15 kahiragana;304B kahookcyrillic;04C4 kakatakana;30AB kakatakanahalfwidth;FF76 kappa;03BA kappasymbolgreek;03F0 kapyeounmieumkorean;3171 kapyeounphieuphkorean;3184 kapyeounpieupkorean;3178 kapyeounssangpieupkorean;3179 karoriisquare;330D kashidaautoarabic;0640 kashidaautonosidebearingarabic;0640 kasmallkatakana;30F5 kasquare;3384 kasraarabic;0650 kasratanarabic;064D kastrokecyrillic;049F katahiraprolongmarkhalfwidth;FF70 kaverticalstrokecyrillic;049D kbopomofo;310E kcalsquare;3389 kcaron;01E9 kcedilla;0137 kcircle;24DA kcommaaccent;0137 kdotbelow;1E33 keharmenian;0584 kehiragana;3051 kekatakana;30B1 kekatakanahalfwidth;FF79 kenarmenian;056F kesmallkatakana;30F6 kgreenlandic;0138 khabengali;0996 khacyrillic;0445 khadeva;0916 khagujarati;0A96 khagurmukhi;0A16 khaharabic;062E khahfinalarabic;FEA6 khahinitialarabic;FEA7 khahmedialarabic;FEA8 kheicoptic;03E7 khhadeva;0959 khhagurmukhi;0A59 khieukhacirclekorean;3278 khieukhaparenkorean;3218 khieukhcirclekorean;326A khieukhkorean;314B khieukhparenkorean;320A khokhaithai;0E02 khokhonthai;0E05 khokhuatthai;0E03 khokhwaithai;0E04 khomutthai;0E5B khook;0199 khorakhangthai;0E06 khzsquare;3391 kihiragana;304D kikatakana;30AD kikatakanahalfwidth;FF77 kiroguramusquare;3315 kiromeetorusquare;3316 kirosquare;3314 kiyeokacirclekorean;326E kiyeokaparenkorean;320E kiyeokcirclekorean;3260 kiyeokkorean;3131 kiyeokparenkorean;3200 kiyeoksioskorean;3133 kjecyrillic;045C klinebelow;1E35 klsquare;3398 kmcubedsquare;33A6 kmonospace;FF4B kmsquaredsquare;33A2 kohiragana;3053 kohmsquare;33C0 kokaithai;0E01 kokatakana;30B3 kokatakanahalfwidth;FF7A kooposquare;331E koppacyrillic;0481 koreanstandardsymbol;327F koroniscmb;0343 kparen;24A6 kpasquare;33AA ksicyrillic;046F ktsquare;33CF kturned;029E kuhiragana;304F kukatakana;30AF kukatakanahalfwidth;FF78 kvsquare;33B8 kwsquare;33BE l;006C labengali;09B2 lacute;013A ladeva;0932 lagujarati;0AB2 lagurmukhi;0A32 lakkhangyaothai;0E45 lamaleffinalarabic;FEFC lamalefhamzaabovefinalarabic;FEF8 lamalefhamzaaboveisolatedarabic;FEF7 lamalefhamzabelowfinalarabic;FEFA lamalefhamzabelowisolatedarabic;FEF9 lamalefisolatedarabic;FEFB lamalefmaddaabovefinalarabic;FEF6 lamalefmaddaaboveisolatedarabic;FEF5 lamarabic;0644 lambda;03BB lambdastroke;019B lamed;05DC lameddagesh;FB3C lameddageshhebrew;FB3C lamedhebrew;05DC lamedholam;05DC 05B9 lamedholamdagesh;05DC 05B9 05BC lamedholamdageshhebrew;05DC 05B9 05BC lamedholamhebrew;05DC 05B9 lamfinalarabic;FEDE lamhahinitialarabic;FCCA laminitialarabic;FEDF lamjeeminitialarabic;FCC9 lamkhahinitialarabic;FCCB lamlamhehisolatedarabic;FDF2 lammedialarabic;FEE0 lammeemhahinitialarabic;FD88 lammeeminitialarabic;FCCC lammeemjeeminitialarabic;FEDF FEE4 FEA0 lammeemkhahinitialarabic;FEDF FEE4 FEA8 largecircle;25EF lbar;019A lbelt;026C lbopomofo;310C lcaron;013E lcedilla;013C lcircle;24DB lcircumflexbelow;1E3D lcommaaccent;013C ldot;0140 ldotaccent;0140 ldotbelow;1E37 ldotbelowmacron;1E39 leftangleabovecmb;031A lefttackbelowcmb;0318 less;003C lessequal;2264 lessequalorgreater;22DA lessmonospace;FF1C lessorequivalent;2272 lessorgreater;2276 lessoverequal;2266 lesssmall;FE64 lezh;026E lfblock;258C lhookretroflex;026D lira;20A4 liwnarmenian;056C lj;01C9 ljecyrillic;0459 ll;F6C0 lladeva;0933 llagujarati;0AB3 llinebelow;1E3B llladeva;0934 llvocalicbengali;09E1 llvocalicdeva;0961 llvocalicvowelsignbengali;09E3 llvocalicvowelsigndeva;0963 lmiddletilde;026B lmonospace;FF4C lmsquare;33D0 lochulathai;0E2C logicaland;2227 logicalnot;00AC logicalnotreversed;2310 logicalor;2228 lolingthai;0E25 longs;017F lowlinecenterline;FE4E lowlinecmb;0332 lowlinedashed;FE4D lozenge;25CA lparen;24A7 lslash;0142 lsquare;2113 lsuperior;F6EE ltshade;2591 luthai;0E26 lvocalicbengali;098C lvocalicdeva;090C lvocalicvowelsignbengali;09E2 lvocalicvowelsigndeva;0962 lxsquare;33D3 m;006D mabengali;09AE macron;00AF macronbelowcmb;0331 macroncmb;0304 macronlowmod;02CD macronmonospace;FFE3 macute;1E3F madeva;092E magujarati;0AAE magurmukhi;0A2E mahapakhhebrew;05A4 mahapakhlefthebrew;05A4 mahiragana;307E maichattawalowleftthai;F895 maichattawalowrightthai;F894 maichattawathai;0E4B maichattawaupperleftthai;F893 maieklowleftthai;F88C maieklowrightthai;F88B maiekthai;0E48 maiekupperleftthai;F88A maihanakatleftthai;F884 maihanakatthai;0E31 maitaikhuleftthai;F889 maitaikhuthai;0E47 maitholowleftthai;F88F maitholowrightthai;F88E maithothai;0E49 maithoupperleftthai;F88D maitrilowleftthai;F892 maitrilowrightthai;F891 maitrithai;0E4A maitriupperleftthai;F890 maiyamokthai;0E46 makatakana;30DE makatakanahalfwidth;FF8F male;2642 mansyonsquare;3347 maqafhebrew;05BE mars;2642 masoracirclehebrew;05AF masquare;3383 mbopomofo;3107 mbsquare;33D4 mcircle;24DC mcubedsquare;33A5 mdotaccent;1E41 mdotbelow;1E43 meemarabic;0645 meemfinalarabic;FEE2 meeminitialarabic;FEE3 meemmedialarabic;FEE4 meemmeeminitialarabic;FCD1 meemmeemisolatedarabic;FC48 meetorusquare;334D mehiragana;3081 meizierasquare;337E mekatakana;30E1 mekatakanahalfwidth;FF92 mem;05DE memdagesh;FB3E memdageshhebrew;FB3E memhebrew;05DE menarmenian;0574 merkhahebrew;05A5 merkhakefulahebrew;05A6 merkhakefulalefthebrew;05A6 merkhalefthebrew;05A5 mhook;0271 mhzsquare;3392 middledotkatakanahalfwidth;FF65 middot;00B7 mieumacirclekorean;3272 mieumaparenkorean;3212 mieumcirclekorean;3264 mieumkorean;3141 mieumpansioskorean;3170 mieumparenkorean;3204 mieumpieupkorean;316E mieumsioskorean;316F mihiragana;307F mikatakana;30DF mikatakanahalfwidth;FF90 minus;2212 minusbelowcmb;0320 minuscircle;2296 minusmod;02D7 minusplus;2213 minute;2032 miribaarusquare;334A mirisquare;3349 mlonglegturned;0270 mlsquare;3396 mmcubedsquare;33A3 mmonospace;FF4D mmsquaredsquare;339F mohiragana;3082 mohmsquare;33C1 mokatakana;30E2 mokatakanahalfwidth;FF93 molsquare;33D6 momathai;0E21 moverssquare;33A7 moverssquaredsquare;33A8 mparen;24A8 mpasquare;33AB mssquare;33B3 msuperior;F6EF mturned;026F mu;00B5 mu1;00B5 muasquare;3382 muchgreater;226B muchless;226A mufsquare;338C mugreek;03BC mugsquare;338D muhiragana;3080 mukatakana;30E0 mukatakanahalfwidth;FF91 mulsquare;3395 multiply;00D7 mumsquare;339B munahhebrew;05A3 munahlefthebrew;05A3 musicalnote;266A musicalnotedbl;266B musicflatsign;266D musicsharpsign;266F mussquare;33B2 muvsquare;33B6 muwsquare;33BC mvmegasquare;33B9 mvsquare;33B7 mwmegasquare;33BF mwsquare;33BD n;006E nabengali;09A8 nabla;2207 nacute;0144 nadeva;0928 nagujarati;0AA8 nagurmukhi;0A28 nahiragana;306A nakatakana;30CA nakatakanahalfwidth;FF85 napostrophe;0149 nasquare;3381 nbopomofo;310B nbspace;00A0 ncaron;0148 ncedilla;0146 ncircle;24DD ncircumflexbelow;1E4B ncommaaccent;0146 ndotaccent;1E45 ndotbelow;1E47 nehiragana;306D nekatakana;30CD nekatakanahalfwidth;FF88 newsheqelsign;20AA nfsquare;338B ngabengali;0999 ngadeva;0919 ngagujarati;0A99 ngagurmukhi;0A19 ngonguthai;0E07 nhiragana;3093 nhookleft;0272 nhookretroflex;0273 nieunacirclekorean;326F nieunaparenkorean;320F nieuncieuckorean;3135 nieuncirclekorean;3261 nieunhieuhkorean;3136 nieunkorean;3134 nieunpansioskorean;3168 nieunparenkorean;3201 nieunsioskorean;3167 nieuntikeutkorean;3166 nihiragana;306B nikatakana;30CB nikatakanahalfwidth;FF86 nikhahitleftthai;F899 nikhahitthai;0E4D nine;0039 ninearabic;0669 ninebengali;09EF ninecircle;2468 ninecircleinversesansserif;2792 ninedeva;096F ninegujarati;0AEF ninegurmukhi;0A6F ninehackarabic;0669 ninehangzhou;3029 nineideographicparen;3228 nineinferior;2089 ninemonospace;FF19 nineoldstyle;F739 nineparen;247C nineperiod;2490 ninepersian;06F9 nineroman;2178 ninesuperior;2079 nineteencircle;2472 nineteenparen;2486 nineteenperiod;249A ninethai;0E59 nj;01CC njecyrillic;045A nkatakana;30F3 nkatakanahalfwidth;FF9D nlegrightlong;019E nlinebelow;1E49 nmonospace;FF4E nmsquare;339A nnabengali;09A3 nnadeva;0923 nnagujarati;0AA3 nnagurmukhi;0A23 nnnadeva;0929 nohiragana;306E nokatakana;30CE nokatakanahalfwidth;FF89 nonbreakingspace;00A0 nonenthai;0E13 nonuthai;0E19 noonarabic;0646 noonfinalarabic;FEE6 noonghunnaarabic;06BA noonghunnafinalarabic;FB9F noonhehinitialarabic;FEE7 FEEC nooninitialarabic;FEE7 noonjeeminitialarabic;FCD2 noonjeemisolatedarabic;FC4B noonmedialarabic;FEE8 noonmeeminitialarabic;FCD5 noonmeemisolatedarabic;FC4E noonnoonfinalarabic;FC8D notcontains;220C notelement;2209 notelementof;2209 notequal;2260 notgreater;226F notgreaternorequal;2271 notgreaternorless;2279 notidentical;2262 notless;226E notlessnorequal;2270 notparallel;2226 notprecedes;2280 notsubset;2284 notsucceeds;2281 notsuperset;2285 nowarmenian;0576 nparen;24A9 nssquare;33B1 nsuperior;207F ntilde;00F1 nu;03BD nuhiragana;306C nukatakana;30CC nukatakanahalfwidth;FF87 nuktabengali;09BC nuktadeva;093C nuktagujarati;0ABC nuktagurmukhi;0A3C numbersign;0023 numbersignmonospace;FF03 numbersignsmall;FE5F numeralsigngreek;0374 numeralsignlowergreek;0375 numero;2116 nun;05E0 nundagesh;FB40 nundageshhebrew;FB40 nunhebrew;05E0 nvsquare;33B5 nwsquare;33BB nyabengali;099E nyadeva;091E nyagujarati;0A9E nyagurmukhi;0A1E o;006F oacute;00F3 oangthai;0E2D obarred;0275 obarredcyrillic;04E9 obarreddieresiscyrillic;04EB obengali;0993 obopomofo;311B obreve;014F ocandradeva;0911 ocandragujarati;0A91 ocandravowelsigndeva;0949 ocandravowelsigngujarati;0AC9 ocaron;01D2 ocircle;24DE ocircumflex;00F4 ocircumflexacute;1ED1 ocircumflexdotbelow;1ED9 ocircumflexgrave;1ED3 ocircumflexhookabove;1ED5 ocircumflextilde;1ED7 ocyrillic;043E odblacute;0151 odblgrave;020D odeva;0913 odieresis;00F6 odieresiscyrillic;04E7 odotbelow;1ECD oe;0153 oekorean;315A ogonek;02DB ogonekcmb;0328 ograve;00F2 ogujarati;0A93 oharmenian;0585 ohiragana;304A ohookabove;1ECF ohorn;01A1 ohornacute;1EDB ohorndotbelow;1EE3 ohorngrave;1EDD ohornhookabove;1EDF ohorntilde;1EE1 ohungarumlaut;0151 oi;01A3 oinvertedbreve;020F okatakana;30AA okatakanahalfwidth;FF75 okorean;3157 olehebrew;05AB omacron;014D omacronacute;1E53 omacrongrave;1E51 omdeva;0950 omega;03C9 omega1;03D6 omegacyrillic;0461 omegalatinclosed;0277 omegaroundcyrillic;047B omegatitlocyrillic;047D omegatonos;03CE omgujarati;0AD0 omicron;03BF omicrontonos;03CC omonospace;FF4F one;0031 onearabic;0661 onebengali;09E7 onecircle;2460 onecircleinversesansserif;278A onedeva;0967 onedotenleader;2024 oneeighth;215B onefitted;F6DC onegujarati;0AE7 onegurmukhi;0A67 onehackarabic;0661 onehalf;00BD onehangzhou;3021 oneideographicparen;3220 oneinferior;2081 onemonospace;FF11 onenumeratorbengali;09F4 oneoldstyle;F731 oneparen;2474 oneperiod;2488 onepersian;06F1 onequarter;00BC oneroman;2170 onesuperior;00B9 onethai;0E51 onethird;2153 oogonek;01EB oogonekmacron;01ED oogurmukhi;0A13 oomatragurmukhi;0A4B oopen;0254 oparen;24AA openbullet;25E6 option;2325 ordfeminine;00AA ordmasculine;00BA orthogonal;221F oshortdeva;0912 oshortvowelsigndeva;094A oslash;00F8 oslashacute;01FF osmallhiragana;3049 osmallkatakana;30A9 osmallkatakanahalfwidth;FF6B ostrokeacute;01FF osuperior;F6F0 otcyrillic;047F otilde;00F5 otildeacute;1E4D otildedieresis;1E4F oubopomofo;3121 overline;203E overlinecenterline;FE4A overlinecmb;0305 overlinedashed;FE49 overlinedblwavy;FE4C overlinewavy;FE4B overscore;00AF ovowelsignbengali;09CB ovowelsigndeva;094B ovowelsigngujarati;0ACB p;0070 paampssquare;3380 paasentosquare;332B pabengali;09AA pacute;1E55 padeva;092A pagedown;21DF pageup;21DE pagujarati;0AAA pagurmukhi;0A2A pahiragana;3071 paiyannoithai;0E2F pakatakana;30D1 palatalizationcyrilliccmb;0484 palochkacyrillic;04C0 pansioskorean;317F paragraph;00B6 parallel;2225 parenleft;0028 parenleftaltonearabic;FD3E parenleftbt;F8ED parenleftex;F8EC parenleftinferior;208D parenleftmonospace;FF08 parenleftsmall;FE59 parenleftsuperior;207D parenlefttp;F8EB parenleftvertical;FE35 parenright;0029 parenrightaltonearabic;FD3F parenrightbt;F8F8 parenrightex;F8F7 parenrightinferior;208E parenrightmonospace;FF09 parenrightsmall;FE5A parenrightsuperior;207E parenrighttp;F8F6 parenrightvertical;FE36 partialdiff;2202 paseqhebrew;05C0 pashtahebrew;0599 pasquare;33A9 patah;05B7 patah11;05B7 patah1d;05B7 patah2a;05B7 patahhebrew;05B7 patahnarrowhebrew;05B7 patahquarterhebrew;05B7 patahwidehebrew;05B7 pazerhebrew;05A1 pbopomofo;3106 pcircle;24DF pdotaccent;1E57 pe;05E4 pecyrillic;043F pedagesh;FB44 pedageshhebrew;FB44 peezisquare;333B pefinaldageshhebrew;FB43 peharabic;067E peharmenian;057A pehebrew;05E4 pehfinalarabic;FB57 pehinitialarabic;FB58 pehiragana;307A pehmedialarabic;FB59 pekatakana;30DA pemiddlehookcyrillic;04A7 perafehebrew;FB4E percent;0025 percentarabic;066A percentmonospace;FF05 percentsmall;FE6A period;002E periodarmenian;0589 periodcentered;00B7 periodhalfwidth;FF61 periodinferior;F6E7 periodmonospace;FF0E periodsmall;FE52 periodsuperior;F6E8 perispomenigreekcmb;0342 perpendicular;22A5 perthousand;2030 peseta;20A7 pfsquare;338A phabengali;09AB phadeva;092B phagujarati;0AAB phagurmukhi;0A2B phi;03C6 phi1;03D5 phieuphacirclekorean;327A phieuphaparenkorean;321A phieuphcirclekorean;326C phieuphkorean;314D phieuphparenkorean;320C philatin;0278 phinthuthai;0E3A phisymbolgreek;03D5 phook;01A5 phophanthai;0E1E phophungthai;0E1C phosamphaothai;0E20 pi;03C0 pieupacirclekorean;3273 pieupaparenkorean;3213 pieupcieuckorean;3176 pieupcirclekorean;3265 pieupkiyeokkorean;3172 pieupkorean;3142 pieupparenkorean;3205 pieupsioskiyeokkorean;3174 pieupsioskorean;3144 pieupsiostikeutkorean;3175 pieupthieuthkorean;3177 pieuptikeutkorean;3173 pihiragana;3074 pikatakana;30D4 pisymbolgreek;03D6 piwrarmenian;0583 plus;002B plusbelowcmb;031F pluscircle;2295 plusminus;00B1 plusmod;02D6 plusmonospace;FF0B plussmall;FE62 plussuperior;207A pmonospace;FF50 pmsquare;33D8 pohiragana;307D pointingindexdownwhite;261F pointingindexleftwhite;261C pointingindexrightwhite;261E pointingindexupwhite;261D pokatakana;30DD poplathai;0E1B postalmark;3012 postalmarkface;3020 pparen;24AB precedes;227A prescription;211E primemod;02B9 primereversed;2035 product;220F projective;2305 prolongedkana;30FC propellor;2318 propersubset;2282 propersuperset;2283 proportion;2237 proportional;221D psi;03C8 psicyrillic;0471 psilipneumatacyrilliccmb;0486 pssquare;33B0 puhiragana;3077 pukatakana;30D7 pvsquare;33B4 pwsquare;33BA q;0071 qadeva;0958 qadmahebrew;05A8 qafarabic;0642 qaffinalarabic;FED6 qafinitialarabic;FED7 qafmedialarabic;FED8 qamats;05B8 qamats10;05B8 qamats1a;05B8 qamats1c;05B8 qamats27;05B8 qamats29;05B8 qamats33;05B8 qamatsde;05B8 qamatshebrew;05B8 qamatsnarrowhebrew;05B8 qamatsqatanhebrew;05B8 qamatsqatannarrowhebrew;05B8 qamatsqatanquarterhebrew;05B8 qamatsqatanwidehebrew;05B8 qamatsquarterhebrew;05B8 qamatswidehebrew;05B8 qarneyparahebrew;059F qbopomofo;3111 qcircle;24E0 qhook;02A0 qmonospace;FF51 qof;05E7 qofdagesh;FB47 qofdageshhebrew;FB47 qofhatafpatah;05E7 05B2 qofhatafpatahhebrew;05E7 05B2 qofhatafsegol;05E7 05B1 qofhatafsegolhebrew;05E7 05B1 qofhebrew;05E7 qofhiriq;05E7 05B4 qofhiriqhebrew;05E7 05B4 qofholam;05E7 05B9 qofholamhebrew;05E7 05B9 qofpatah;05E7 05B7 qofpatahhebrew;05E7 05B7 qofqamats;05E7 05B8 qofqamatshebrew;05E7 05B8 qofqubuts;05E7 05BB qofqubutshebrew;05E7 05BB qofsegol;05E7 05B6 qofsegolhebrew;05E7 05B6 qofsheva;05E7 05B0 qofshevahebrew;05E7 05B0 qoftsere;05E7 05B5 qoftserehebrew;05E7 05B5 qparen;24AC quarternote;2669 qubuts;05BB qubuts18;05BB qubuts25;05BB qubuts31;05BB qubutshebrew;05BB qubutsnarrowhebrew;05BB qubutsquarterhebrew;05BB qubutswidehebrew;05BB question;003F questionarabic;061F questionarmenian;055E questiondown;00BF questiondownsmall;F7BF questiongreek;037E questionmonospace;FF1F questionsmall;F73F quotedbl;0022 quotedblbase;201E quotedblleft;201C quotedblmonospace;FF02 quotedblprime;301E quotedblprimereversed;301D quotedblright;201D quoteleft;2018 quoteleftreversed;201B quotereversed;201B quoteright;2019 quoterightn;0149 quotesinglbase;201A quotesingle;0027 quotesinglemonospace;FF07 r;0072 raarmenian;057C rabengali;09B0 racute;0155 radeva;0930 radical;221A radicalex;F8E5 radoverssquare;33AE radoverssquaredsquare;33AF radsquare;33AD rafe;05BF rafehebrew;05BF ragujarati;0AB0 ragurmukhi;0A30 rahiragana;3089 rakatakana;30E9 rakatakanahalfwidth;FF97 ralowerdiagonalbengali;09F1 ramiddlediagonalbengali;09F0 ramshorn;0264 ratio;2236 rbopomofo;3116 rcaron;0159 rcedilla;0157 rcircle;24E1 rcommaaccent;0157 rdblgrave;0211 rdotaccent;1E59 rdotbelow;1E5B rdotbelowmacron;1E5D referencemark;203B reflexsubset;2286 reflexsuperset;2287 registered;00AE registersans;F8E8 registerserif;F6DA reharabic;0631 reharmenian;0580 rehfinalarabic;FEAE rehiragana;308C rehyehaleflamarabic;0631 FEF3 FE8E 0644 rekatakana;30EC rekatakanahalfwidth;FF9A resh;05E8 reshdageshhebrew;FB48 reshhatafpatah;05E8 05B2 reshhatafpatahhebrew;05E8 05B2 reshhatafsegol;05E8 05B1 reshhatafsegolhebrew;05E8 05B1 reshhebrew;05E8 reshhiriq;05E8 05B4 reshhiriqhebrew;05E8 05B4 reshholam;05E8 05B9 reshholamhebrew;05E8 05B9 reshpatah;05E8 05B7 reshpatahhebrew;05E8 05B7 reshqamats;05E8 05B8 reshqamatshebrew;05E8 05B8 reshqubuts;05E8 05BB reshqubutshebrew;05E8 05BB reshsegol;05E8 05B6 reshsegolhebrew;05E8 05B6 reshsheva;05E8 05B0 reshshevahebrew;05E8 05B0 reshtsere;05E8 05B5 reshtserehebrew;05E8 05B5 reversedtilde;223D reviahebrew;0597 reviamugrashhebrew;0597 revlogicalnot;2310 rfishhook;027E rfishhookreversed;027F rhabengali;09DD rhadeva;095D rho;03C1 rhook;027D rhookturned;027B rhookturnedsuperior;02B5 rhosymbolgreek;03F1 rhotichookmod;02DE rieulacirclekorean;3271 rieulaparenkorean;3211 rieulcirclekorean;3263 rieulhieuhkorean;3140 rieulkiyeokkorean;313A rieulkiyeoksioskorean;3169 rieulkorean;3139 rieulmieumkorean;313B rieulpansioskorean;316C rieulparenkorean;3203 rieulphieuphkorean;313F rieulpieupkorean;313C rieulpieupsioskorean;316B rieulsioskorean;313D rieulthieuthkorean;313E rieultikeutkorean;316A rieulyeorinhieuhkorean;316D rightangle;221F righttackbelowcmb;0319 righttriangle;22BF rihiragana;308A rikatakana;30EA rikatakanahalfwidth;FF98 ring;02DA ringbelowcmb;0325 ringcmb;030A ringhalfleft;02BF ringhalfleftarmenian;0559 ringhalfleftbelowcmb;031C ringhalfleftcentered;02D3 ringhalfright;02BE ringhalfrightbelowcmb;0339 ringhalfrightcentered;02D2 rinvertedbreve;0213 rittorusquare;3351 rlinebelow;1E5F rlongleg;027C rlonglegturned;027A rmonospace;FF52 rohiragana;308D rokatakana;30ED rokatakanahalfwidth;FF9B roruathai;0E23 rparen;24AD rrabengali;09DC rradeva;0931 rragurmukhi;0A5C rreharabic;0691 rrehfinalarabic;FB8D rrvocalicbengali;09E0 rrvocalicdeva;0960 rrvocalicgujarati;0AE0 rrvocalicvowelsignbengali;09C4 rrvocalicvowelsigndeva;0944 rrvocalicvowelsigngujarati;0AC4 rsuperior;F6F1 rtblock;2590 rturned;0279 rturnedsuperior;02B4 ruhiragana;308B rukatakana;30EB rukatakanahalfwidth;FF99 rupeemarkbengali;09F2 rupeesignbengali;09F3 rupiah;F6DD ruthai;0E24 rvocalicbengali;098B rvocalicdeva;090B rvocalicgujarati;0A8B rvocalicvowelsignbengali;09C3 rvocalicvowelsigndeva;0943 rvocalicvowelsigngujarati;0AC3 s;0073 sabengali;09B8 sacute;015B sacutedotaccent;1E65 sadarabic;0635 sadeva;0938 sadfinalarabic;FEBA sadinitialarabic;FEBB sadmedialarabic;FEBC sagujarati;0AB8 sagurmukhi;0A38 sahiragana;3055 sakatakana;30B5 sakatakanahalfwidth;FF7B sallallahoualayhewasallamarabic;FDFA samekh;05E1 samekhdagesh;FB41 samekhdageshhebrew;FB41 samekhhebrew;05E1 saraaathai;0E32 saraaethai;0E41 saraaimaimalaithai;0E44 saraaimaimuanthai;0E43 saraamthai;0E33 saraathai;0E30 saraethai;0E40 saraiileftthai;F886 saraiithai;0E35 saraileftthai;F885 saraithai;0E34 saraothai;0E42 saraueeleftthai;F888 saraueethai;0E37 saraueleftthai;F887 sarauethai;0E36 sarauthai;0E38 sarauuthai;0E39 sbopomofo;3119 scaron;0161 scarondotaccent;1E67 scedilla;015F schwa;0259 schwacyrillic;04D9 schwadieresiscyrillic;04DB schwahook;025A scircle;24E2 scircumflex;015D scommaaccent;0219 sdotaccent;1E61 sdotbelow;1E63 sdotbelowdotaccent;1E69 seagullbelowcmb;033C second;2033 secondtonechinese;02CA section;00A7 seenarabic;0633 seenfinalarabic;FEB2 seeninitialarabic;FEB3 seenmedialarabic;FEB4 segol;05B6 segol13;05B6 segol1f;05B6 segol2c;05B6 segolhebrew;05B6 segolnarrowhebrew;05B6 segolquarterhebrew;05B6 segoltahebrew;0592 segolwidehebrew;05B6 seharmenian;057D sehiragana;305B sekatakana;30BB sekatakanahalfwidth;FF7E semicolon;003B semicolonarabic;061B semicolonmonospace;FF1B semicolonsmall;FE54 semivoicedmarkkana;309C semivoicedmarkkanahalfwidth;FF9F sentisquare;3322 sentosquare;3323 seven;0037 sevenarabic;0667 sevenbengali;09ED sevencircle;2466 sevencircleinversesansserif;2790 sevendeva;096D seveneighths;215E sevengujarati;0AED sevengurmukhi;0A6D sevenhackarabic;0667 sevenhangzhou;3027 sevenideographicparen;3226 seveninferior;2087 sevenmonospace;FF17 sevenoldstyle;F737 sevenparen;247A sevenperiod;248E sevenpersian;06F7 sevenroman;2176 sevensuperior;2077 seventeencircle;2470 seventeenparen;2484 seventeenperiod;2498 seventhai;0E57 sfthyphen;00AD shaarmenian;0577 shabengali;09B6 shacyrillic;0448 shaddaarabic;0651 shaddadammaarabic;FC61 shaddadammatanarabic;FC5E shaddafathaarabic;FC60 shaddafathatanarabic;0651 064B shaddakasraarabic;FC62 shaddakasratanarabic;FC5F shade;2592 shadedark;2593 shadelight;2591 shademedium;2592 shadeva;0936 shagujarati;0AB6 shagurmukhi;0A36 shalshelethebrew;0593 shbopomofo;3115 shchacyrillic;0449 sheenarabic;0634 sheenfinalarabic;FEB6 sheeninitialarabic;FEB7 sheenmedialarabic;FEB8 sheicoptic;03E3 sheqel;20AA sheqelhebrew;20AA sheva;05B0 sheva115;05B0 sheva15;05B0 sheva22;05B0 sheva2e;05B0 shevahebrew;05B0 shevanarrowhebrew;05B0 shevaquarterhebrew;05B0 shevawidehebrew;05B0 shhacyrillic;04BB shimacoptic;03ED shin;05E9 shindagesh;FB49 shindageshhebrew;FB49 shindageshshindot;FB2C shindageshshindothebrew;FB2C shindageshsindot;FB2D shindageshsindothebrew;FB2D shindothebrew;05C1 shinhebrew;05E9 shinshindot;FB2A shinshindothebrew;FB2A shinsindot;FB2B shinsindothebrew;FB2B shook;0282 sigma;03C3 sigma1;03C2 sigmafinal;03C2 sigmalunatesymbolgreek;03F2 sihiragana;3057 sikatakana;30B7 sikatakanahalfwidth;FF7C siluqhebrew;05BD siluqlefthebrew;05BD similar;223C sindothebrew;05C2 siosacirclekorean;3274 siosaparenkorean;3214 sioscieuckorean;317E sioscirclekorean;3266 sioskiyeokkorean;317A sioskorean;3145 siosnieunkorean;317B siosparenkorean;3206 siospieupkorean;317D siostikeutkorean;317C six;0036 sixarabic;0666 sixbengali;09EC sixcircle;2465 sixcircleinversesansserif;278F sixdeva;096C sixgujarati;0AEC sixgurmukhi;0A6C sixhackarabic;0666 sixhangzhou;3026 sixideographicparen;3225 sixinferior;2086 sixmonospace;FF16 sixoldstyle;F736 sixparen;2479 sixperiod;248D sixpersian;06F6 sixroman;2175 sixsuperior;2076 sixteencircle;246F sixteencurrencydenominatorbengali;09F9 sixteenparen;2483 sixteenperiod;2497 sixthai;0E56 slash;002F slashmonospace;FF0F slong;017F slongdotaccent;1E9B smileface;263A smonospace;FF53 sofpasuqhebrew;05C3 softhyphen;00AD softsigncyrillic;044C sohiragana;305D sokatakana;30BD sokatakanahalfwidth;FF7F soliduslongoverlaycmb;0338 solidusshortoverlaycmb;0337 sorusithai;0E29 sosalathai;0E28 sosothai;0E0B sosuathai;0E2A space;0020 spacehackarabic;0020 spade;2660 spadesuitblack;2660 spadesuitwhite;2664 sparen;24AE squarebelowcmb;033B squarecc;33C4 squarecm;339D squarediagonalcrosshatchfill;25A9 squarehorizontalfill;25A4 squarekg;338F squarekm;339E squarekmcapital;33CE squareln;33D1 squarelog;33D2 squaremg;338E squaremil;33D5 squaremm;339C squaremsquared;33A1 squareorthogonalcrosshatchfill;25A6 squareupperlefttolowerrightfill;25A7 squareupperrighttolowerleftfill;25A8 squareverticalfill;25A5 squarewhitewithsmallblack;25A3 srsquare;33DB ssabengali;09B7 ssadeva;0937 ssagujarati;0AB7 ssangcieuckorean;3149 ssanghieuhkorean;3185 ssangieungkorean;3180 ssangkiyeokkorean;3132 ssangnieunkorean;3165 ssangpieupkorean;3143 ssangsioskorean;3146 ssangtikeutkorean;3138 ssuperior;F6F2 sterling;00A3 sterlingmonospace;FFE1 strokelongoverlaycmb;0336 strokeshortoverlaycmb;0335 subset;2282 subsetnotequal;228A subsetorequal;2286 succeeds;227B suchthat;220B suhiragana;3059 sukatakana;30B9 sukatakanahalfwidth;FF7D sukunarabic;0652 summation;2211 sun;263C superset;2283 supersetnotequal;228B supersetorequal;2287 svsquare;33DC syouwaerasquare;337C t;0074 tabengali;09A4 tackdown;22A4 tackleft;22A3 tadeva;0924 tagujarati;0AA4 tagurmukhi;0A24 taharabic;0637 tahfinalarabic;FEC2 tahinitialarabic;FEC3 tahiragana;305F tahmedialarabic;FEC4 taisyouerasquare;337D takatakana;30BF takatakanahalfwidth;FF80 tatweelarabic;0640 tau;03C4 tav;05EA tavdages;FB4A tavdagesh;FB4A tavdageshhebrew;FB4A tavhebrew;05EA tbar;0167 tbopomofo;310A tcaron;0165 tccurl;02A8 tcedilla;0163 tcheharabic;0686 tchehfinalarabic;FB7B tchehinitialarabic;FB7C tchehmedialarabic;FB7D tchehmeeminitialarabic;FB7C FEE4 tcircle;24E3 tcircumflexbelow;1E71 tcommaaccent;0163 tdieresis;1E97 tdotaccent;1E6B tdotbelow;1E6D tecyrillic;0442 tedescendercyrillic;04AD teharabic;062A tehfinalarabic;FE96 tehhahinitialarabic;FCA2 tehhahisolatedarabic;FC0C tehinitialarabic;FE97 tehiragana;3066 tehjeeminitialarabic;FCA1 tehjeemisolatedarabic;FC0B tehmarbutaarabic;0629 tehmarbutafinalarabic;FE94 tehmedialarabic;FE98 tehmeeminitialarabic;FCA4 tehmeemisolatedarabic;FC0E tehnoonfinalarabic;FC73 tekatakana;30C6 tekatakanahalfwidth;FF83 telephone;2121 telephoneblack;260E telishagedolahebrew;05A0 telishaqetanahebrew;05A9 tencircle;2469 tenideographicparen;3229 tenparen;247D tenperiod;2491 tenroman;2179 tesh;02A7 tet;05D8 tetdagesh;FB38 tetdageshhebrew;FB38 tethebrew;05D8 tetsecyrillic;04B5 tevirhebrew;059B tevirlefthebrew;059B thabengali;09A5 thadeva;0925 thagujarati;0AA5 thagurmukhi;0A25 thalarabic;0630 thalfinalarabic;FEAC thanthakhatlowleftthai;F898 thanthakhatlowrightthai;F897 thanthakhatthai;0E4C thanthakhatupperleftthai;F896 theharabic;062B thehfinalarabic;FE9A thehinitialarabic;FE9B thehmedialarabic;FE9C thereexists;2203 therefore;2234 theta;03B8 theta1;03D1 thetasymbolgreek;03D1 thieuthacirclekorean;3279 thieuthaparenkorean;3219 thieuthcirclekorean;326B thieuthkorean;314C thieuthparenkorean;320B thirteencircle;246C thirteenparen;2480 thirteenperiod;2494 thonangmonthothai;0E11 thook;01AD thophuthaothai;0E12 thorn;00FE thothahanthai;0E17 thothanthai;0E10 thothongthai;0E18 thothungthai;0E16 thousandcyrillic;0482 thousandsseparatorarabic;066C thousandsseparatorpersian;066C three;0033 threearabic;0663 threebengali;09E9 threecircle;2462 threecircleinversesansserif;278C threedeva;0969 threeeighths;215C threegujarati;0AE9 threegurmukhi;0A69 threehackarabic;0663 threehangzhou;3023 threeideographicparen;3222 threeinferior;2083 threemonospace;FF13 threenumeratorbengali;09F6 threeoldstyle;F733 threeparen;2476 threeperiod;248A threepersian;06F3 threequarters;00BE threequartersemdash;F6DE threeroman;2172 threesuperior;00B3 threethai;0E53 thzsquare;3394 tihiragana;3061 tikatakana;30C1 tikatakanahalfwidth;FF81 tikeutacirclekorean;3270 tikeutaparenkorean;3210 tikeutcirclekorean;3262 tikeutkorean;3137 tikeutparenkorean;3202 tilde;02DC tildebelowcmb;0330 tildecmb;0303 tildecomb;0303 tildedoublecmb;0360 tildeoperator;223C tildeoverlaycmb;0334 tildeverticalcmb;033E timescircle;2297 tipehahebrew;0596 tipehalefthebrew;0596 tippigurmukhi;0A70 titlocyrilliccmb;0483 tiwnarmenian;057F tlinebelow;1E6F tmonospace;FF54 toarmenian;0569 tohiragana;3068 tokatakana;30C8 tokatakanahalfwidth;FF84 tonebarextrahighmod;02E5 tonebarextralowmod;02E9 tonebarhighmod;02E6 tonebarlowmod;02E8 tonebarmidmod;02E7 tonefive;01BD tonesix;0185 tonetwo;01A8 tonos;0384 tonsquare;3327 topatakthai;0E0F tortoiseshellbracketleft;3014 tortoiseshellbracketleftsmall;FE5D tortoiseshellbracketleftvertical;FE39 tortoiseshellbracketright;3015 tortoiseshellbracketrightsmall;FE5E tortoiseshellbracketrightvertical;FE3A totaothai;0E15 tpalatalhook;01AB tparen;24AF trademark;2122 trademarksans;F8EA trademarkserif;F6DB tretroflexhook;0288 triagdn;25BC triaglf;25C4 triagrt;25BA triagup;25B2 ts;02A6 tsadi;05E6 tsadidagesh;FB46 tsadidageshhebrew;FB46 tsadihebrew;05E6 tsecyrillic;0446 tsere;05B5 tsere12;05B5 tsere1e;05B5 tsere2b;05B5 tserehebrew;05B5 tserenarrowhebrew;05B5 tserequarterhebrew;05B5 tserewidehebrew;05B5 tshecyrillic;045B tsuperior;F6F3 ttabengali;099F ttadeva;091F ttagujarati;0A9F ttagurmukhi;0A1F tteharabic;0679 ttehfinalarabic;FB67 ttehinitialarabic;FB68 ttehmedialarabic;FB69 tthabengali;09A0 tthadeva;0920 tthagujarati;0AA0 tthagurmukhi;0A20 tturned;0287 tuhiragana;3064 tukatakana;30C4 tukatakanahalfwidth;FF82 tusmallhiragana;3063 tusmallkatakana;30C3 tusmallkatakanahalfwidth;FF6F twelvecircle;246B twelveparen;247F twelveperiod;2493 twelveroman;217B twentycircle;2473 twentyhangzhou;5344 twentyparen;2487 twentyperiod;249B two;0032 twoarabic;0662 twobengali;09E8 twocircle;2461 twocircleinversesansserif;278B twodeva;0968 twodotenleader;2025 twodotleader;2025 twodotleadervertical;FE30 twogujarati;0AE8 twogurmukhi;0A68 twohackarabic;0662 twohangzhou;3022 twoideographicparen;3221 twoinferior;2082 twomonospace;FF12 twonumeratorbengali;09F5 twooldstyle;F732 twoparen;2475 twoperiod;2489 twopersian;06F2 tworoman;2171 twostroke;01BB twosuperior;00B2 twothai;0E52 twothirds;2154 u;0075 uacute;00FA ubar;0289 ubengali;0989 ubopomofo;3128 ubreve;016D ucaron;01D4 ucircle;24E4 ucircumflex;00FB ucircumflexbelow;1E77 ucyrillic;0443 udattadeva;0951 udblacute;0171 udblgrave;0215 udeva;0909 udieresis;00FC udieresisacute;01D8 udieresisbelow;1E73 udieresiscaron;01DA udieresiscyrillic;04F1 udieresisgrave;01DC udieresismacron;01D6 udotbelow;1EE5 ugrave;00F9 ugujarati;0A89 ugurmukhi;0A09 uhiragana;3046 uhookabove;1EE7 uhorn;01B0 uhornacute;1EE9 uhorndotbelow;1EF1 uhorngrave;1EEB uhornhookabove;1EED uhorntilde;1EEF uhungarumlaut;0171 uhungarumlautcyrillic;04F3 uinvertedbreve;0217 ukatakana;30A6 ukatakanahalfwidth;FF73 ukcyrillic;0479 ukorean;315C umacron;016B umacroncyrillic;04EF umacrondieresis;1E7B umatragurmukhi;0A41 umonospace;FF55 underscore;005F underscoredbl;2017 underscoremonospace;FF3F underscorevertical;FE33 underscorewavy;FE4F union;222A universal;2200 uogonek;0173 uparen;24B0 upblock;2580 upperdothebrew;05C4 upsilon;03C5 upsilondieresis;03CB upsilondieresistonos;03B0 upsilonlatin;028A upsilontonos;03CD uptackbelowcmb;031D uptackmod;02D4 uragurmukhi;0A73 uring;016F ushortcyrillic;045E usmallhiragana;3045 usmallkatakana;30A5 usmallkatakanahalfwidth;FF69 ustraightcyrillic;04AF ustraightstrokecyrillic;04B1 utilde;0169 utildeacute;1E79 utildebelow;1E75 uubengali;098A uudeva;090A uugujarati;0A8A uugurmukhi;0A0A uumatragurmukhi;0A42 uuvowelsignbengali;09C2 uuvowelsigndeva;0942 uuvowelsigngujarati;0AC2 uvowelsignbengali;09C1 uvowelsigndeva;0941 uvowelsigngujarati;0AC1 v;0076 vadeva;0935 vagujarati;0AB5 vagurmukhi;0A35 vakatakana;30F7 vav;05D5 vavdagesh;FB35 vavdagesh65;FB35 vavdageshhebrew;FB35 vavhebrew;05D5 vavholam;FB4B vavholamhebrew;FB4B vavvavhebrew;05F0 vavyodhebrew;05F1 vcircle;24E5 vdotbelow;1E7F vecyrillic;0432 veharabic;06A4 vehfinalarabic;FB6B vehinitialarabic;FB6C vehmedialarabic;FB6D vekatakana;30F9 venus;2640 verticalbar;007C verticallineabovecmb;030D verticallinebelowcmb;0329 verticallinelowmod;02CC verticallinemod;02C8 vewarmenian;057E vhook;028B vikatakana;30F8 viramabengali;09CD viramadeva;094D viramagujarati;0ACD visargabengali;0983 visargadeva;0903 visargagujarati;0A83 vmonospace;FF56 voarmenian;0578 voicediterationhiragana;309E voicediterationkatakana;30FE voicedmarkkana;309B voicedmarkkanahalfwidth;FF9E vokatakana;30FA vparen;24B1 vtilde;1E7D vturned;028C vuhiragana;3094 vukatakana;30F4 w;0077 wacute;1E83 waekorean;3159 wahiragana;308F wakatakana;30EF wakatakanahalfwidth;FF9C wakorean;3158 wasmallhiragana;308E wasmallkatakana;30EE wattosquare;3357 wavedash;301C wavyunderscorevertical;FE34 wawarabic;0648 wawfinalarabic;FEEE wawhamzaabovearabic;0624 wawhamzaabovefinalarabic;FE86 wbsquare;33DD wcircle;24E6 wcircumflex;0175 wdieresis;1E85 wdotaccent;1E87 wdotbelow;1E89 wehiragana;3091 weierstrass;2118 wekatakana;30F1 wekorean;315E weokorean;315D wgrave;1E81 whitebullet;25E6 whitecircle;25CB whitecircleinverse;25D9 whitecornerbracketleft;300E whitecornerbracketleftvertical;FE43 whitecornerbracketright;300F whitecornerbracketrightvertical;FE44 whitediamond;25C7 whitediamondcontainingblacksmalldiamond;25C8 whitedownpointingsmalltriangle;25BF whitedownpointingtriangle;25BD whiteleftpointingsmalltriangle;25C3 whiteleftpointingtriangle;25C1 whitelenticularbracketleft;3016 whitelenticularbracketright;3017 whiterightpointingsmalltriangle;25B9 whiterightpointingtriangle;25B7 whitesmallsquare;25AB whitesmilingface;263A whitesquare;25A1 whitestar;2606 whitetelephone;260F whitetortoiseshellbracketleft;3018 whitetortoiseshellbracketright;3019 whiteuppointingsmalltriangle;25B5 whiteuppointingtriangle;25B3 wihiragana;3090 wikatakana;30F0 wikorean;315F wmonospace;FF57 wohiragana;3092 wokatakana;30F2 wokatakanahalfwidth;FF66 won;20A9 wonmonospace;FFE6 wowaenthai;0E27 wparen;24B2 wring;1E98 wsuperior;02B7 wturned;028D wynn;01BF x;0078 xabovecmb;033D xbopomofo;3112 xcircle;24E7 xdieresis;1E8D xdotaccent;1E8B xeharmenian;056D xi;03BE xmonospace;FF58 xparen;24B3 xsuperior;02E3 y;0079 yaadosquare;334E yabengali;09AF yacute;00FD yadeva;092F yaekorean;3152 yagujarati;0AAF yagurmukhi;0A2F yahiragana;3084 yakatakana;30E4 yakatakanahalfwidth;FF94 yakorean;3151 yamakkanthai;0E4E yasmallhiragana;3083 yasmallkatakana;30E3 yasmallkatakanahalfwidth;FF6C yatcyrillic;0463 ycircle;24E8 ycircumflex;0177 ydieresis;00FF ydotaccent;1E8F ydotbelow;1EF5 yeharabic;064A yehbarreearabic;06D2 yehbarreefinalarabic;FBAF yehfinalarabic;FEF2 yehhamzaabovearabic;0626 yehhamzaabovefinalarabic;FE8A yehhamzaaboveinitialarabic;FE8B yehhamzaabovemedialarabic;FE8C yehinitialarabic;FEF3 yehmedialarabic;FEF4 yehmeeminitialarabic;FCDD yehmeemisolatedarabic;FC58 yehnoonfinalarabic;FC94 yehthreedotsbelowarabic;06D1 yekorean;3156 yen;00A5 yenmonospace;FFE5 yeokorean;3155 yeorinhieuhkorean;3186 yerahbenyomohebrew;05AA yerahbenyomolefthebrew;05AA yericyrillic;044B yerudieresiscyrillic;04F9 yesieungkorean;3181 yesieungpansioskorean;3183 yesieungsioskorean;3182 yetivhebrew;059A ygrave;1EF3 yhook;01B4 yhookabove;1EF7 yiarmenian;0575 yicyrillic;0457 yikorean;3162 yinyang;262F yiwnarmenian;0582 ymonospace;FF59 yod;05D9 yoddagesh;FB39 yoddageshhebrew;FB39 yodhebrew;05D9 yodyodhebrew;05F2 yodyodpatahhebrew;FB1F yohiragana;3088 yoikorean;3189 yokatakana;30E8 yokatakanahalfwidth;FF96 yokorean;315B yosmallhiragana;3087 yosmallkatakana;30E7 yosmallkatakanahalfwidth;FF6E yotgreek;03F3 yoyaekorean;3188 yoyakorean;3187 yoyakthai;0E22 yoyingthai;0E0D yparen;24B4 ypogegrammeni;037A ypogegrammenigreekcmb;0345 yr;01A6 yring;1E99 ysuperior;02B8 ytilde;1EF9 yturned;028E yuhiragana;3086 yuikorean;318C yukatakana;30E6 yukatakanahalfwidth;FF95 yukorean;3160 yusbigcyrillic;046B yusbigiotifiedcyrillic;046D yuslittlecyrillic;0467 yuslittleiotifiedcyrillic;0469 yusmallhiragana;3085 yusmallkatakana;30E5 yusmallkatakanahalfwidth;FF6D yuyekorean;318B yuyeokorean;318A yyabengali;09DF yyadeva;095F z;007A zaarmenian;0566 zacute;017A zadeva;095B zagurmukhi;0A5B zaharabic;0638 zahfinalarabic;FEC6 zahinitialarabic;FEC7 zahiragana;3056 zahmedialarabic;FEC8 zainarabic;0632 zainfinalarabic;FEB0 zakatakana;30B6 zaqefgadolhebrew;0595 zaqefqatanhebrew;0594 zarqahebrew;0598 zayin;05D6 zayindagesh;FB36 zayindageshhebrew;FB36 zayinhebrew;05D6 zbopomofo;3117 zcaron;017E zcircle;24E9 zcircumflex;1E91 zcurl;0291 zdot;017C zdotaccent;017C zdotbelow;1E93 zecyrillic;0437 zedescendercyrillic;0499 zedieresiscyrillic;04DF zehiragana;305C zekatakana;30BC zero;0030 zeroarabic;0660 zerobengali;09E6 zerodeva;0966 zerogujarati;0AE6 zerogurmukhi;0A66 zerohackarabic;0660 zeroinferior;2080 zeromonospace;FF10 zerooldstyle;F730 zeropersian;06F0 zerosuperior;2070 zerothai;0E50 zerowidthjoiner;FEFF zerowidthnonjoiner;200C zerowidthspace;200B zeta;03B6 zhbopomofo;3113 zhearmenian;056A zhebrevecyrillic;04C2 zhecyrillic;0436 zhedescendercyrillic;0497 zhedieresiscyrillic;04DD zihiragana;3058 zikatakana;30B8 zinorhebrew;05AE zlinebelow;1E95 zmonospace;FF5A zohiragana;305E zokatakana;30BE zparen;24B5 zretroflexhook;0290 zstroke;01B6 zuhiragana;305A zukatakana;30BA a100;275E a101;2761 a102;2762 a103;2763 a104;2764 a105;2710 a106;2765 a107;2766 a108;2767 a109;2660 a10;2721 a110;2665 a111;2666 a112;2663 a117;2709 a118;2708 a119;2707 a11;261B a120;2460 a121;2461 a122;2462 a123;2463 a124;2464 a125;2465 a126;2466 a127;2467 a128;2468 a129;2469 a12;261E a130;2776 a131;2777 a132;2778 a133;2779 a134;277A a135;277B a136;277C a137;277D a138;277E a139;277F a13;270C a140;2780 a141;2781 a142;2782 a143;2783 a144;2784 a145;2785 a146;2786 a147;2787 a148;2788 a149;2789 a14;270D a150;278A a151;278B a152;278C a153;278D a154;278E a155;278F a156;2790 a157;2791 a158;2792 a159;2793 a15;270E a160;2794 a161;2192 a162;27A3 a163;2194 a164;2195 a165;2799 a166;279B a167;279C a168;279D a169;279E a16;270F a170;279F a171;27A0 a172;27A1 a173;27A2 a174;27A4 a175;27A5 a176;27A6 a177;27A7 a178;27A8 a179;27A9 a17;2711 a180;27AB a181;27AD a182;27AF a183;27B2 a184;27B3 a185;27B5 a186;27B8 a187;27BA a188;27BB a189;27BC a18;2712 a190;27BD a191;27BE a192;279A a193;27AA a194;27B6 a195;27B9 a196;2798 a197;27B4 a198;27B7 a199;27AC a19;2713 a1;2701 a200;27AE a201;27B1 a202;2703 a203;2750 a204;2752 a205;276E a206;2770 a20;2714 a21;2715 a22;2716 a23;2717 a24;2718 a25;2719 a26;271A a27;271B a28;271C a29;2722 a2;2702 a30;2723 a31;2724 a32;2725 a33;2726 a34;2727 a35;2605 a36;2729 a37;272A a38;272B a39;272C a3;2704 a40;272D a41;272E a42;272F a43;2730 a44;2731 a45;2732 a46;2733 a47;2734 a48;2735 a49;2736 a4;260E a50;2737 a51;2738 a52;2739 a53;273A a54;273B a55;273C a56;273D a57;273E a58;273F a59;2740 a5;2706 a60;2741 a61;2742 a62;2743 a63;2744 a64;2745 a65;2746 a66;2747 a67;2748 a68;2749 a69;274A a6;271D a70;274B a71;25CF a72;274D a73;25A0 a74;274F a75;2751 a76;25B2 a77;25BC a78;25C6 a79;2756 a7;271E a81;25D7 a82;2758 a83;2759 a84;275A a85;276F a86;2771 a87;2772 a88;2773 a89;2768 a8;271F a90;2769 a91;276C a92;276D a93;276A a94;276B a95;2774 a96;2775 a97;275B a98;275C a99;275D a9;2720 """ # string table management # class StringTable: def __init__( self, name_list, master_table_name ): self.names = name_list self.master_table = master_table_name self.indices = {} index = 0 for name in name_list: self.indices[name] = index index += len( name ) + 1 self.total = index def dump( self, file ): write = file.write write( " static const char " + self.master_table + "[" + repr( self.total ) + "] =\n" ) write( " {\n" ) line = "" for name in self.names: line += " '" line += string.join( ( re.findall( ".", name ) ), "','" ) line += "', 0,\n" write( line + " };\n\n\n" ) def dump_sublist( self, file, table_name, macro_name, sublist ): write = file.write write( "#define " + macro_name + " " + repr( len( sublist ) ) + "\n\n" ) write( " /* Values are offsets into the `" + self.master_table + "' table */\n\n" ) write( " static const short " + table_name + "[" + macro_name + "] =\n" ) write( " {\n" ) line = " " comma = "" col = 0 for name in sublist: line += comma line += "%4d" % self.indices[name] col += 1 comma = "," if col == 14: col = 0 comma = ",\n " write( line + "\n };\n\n\n" ) # We now store the Adobe Glyph List in compressed form. The list is put # into a data structure called `trie' (because it has a tree-like # appearance). Consider, for example, that you want to store the # following name mapping: # # A => 1 # Aacute => 6 # Abalon => 2 # Abstract => 4 # # It is possible to store the entries as follows. # # A => 1 # | # +-acute => 6 # | # +-b # | # +-alon => 2 # | # +-stract => 4 # # We see that each node in the trie has: # # - one or more `letters' # - an optional value # - zero or more child nodes # # The first step is to call # # root = StringNode( "", 0 ) # for word in map.values(): # root.add( word, map[word] ) # # which creates a large trie where each node has only one children. # # Executing # # root = root.optimize() # # optimizes the trie by merging the letters of successive nodes whenever # possible. # # Each node of the trie is stored as follows. # # - First the node's letter, according to the following scheme. We # use the fact that in the AGL no name contains character codes > 127. # # name bitsize description # ---------------------------------------------------------------- # notlast 1 Set to 1 if this is not the last letter # in the word. # ascii 7 The letter's ASCII value. # # - The letter is followed by a children count and the value of the # current key (if any). Again we can do some optimization because all # AGL entries are from the BMP; this means that 16 bits are sufficient # to store its Unicode values. Additionally, no node has more than # 127 children. # # name bitsize description # ----------------------------------------- # hasvalue 1 Set to 1 if a 16-bit Unicode value follows. # num_children 7 Number of children. Can be 0 only if # `hasvalue' is set to 1. # value 16 Optional Unicode value. # # - A node is finished by a list of 16bit absolute offsets to the # children, which must be sorted in increasing order of their first # letter. # # For simplicity, all 16bit quantities are stored in big-endian order. # # The root node has first letter = 0, and no value. # class StringNode: def __init__( self, letter, value ): self.letter = letter self.value = value self.children = {} def __cmp__( self, other ): return ord( self.letter[0] ) - ord( other.letter[0] ) def add( self, word, value ): if len( word ) == 0: self.value = value return letter = word[0] word = word[1:] if self.children.has_key( letter ): child = self.children[letter] else: child = StringNode( letter, 0 ) self.children[letter] = child child.add( word, value ) def optimize( self ): # optimize all children first children = self.children.values() self.children = {} for child in children: self.children[child.letter[0]] = child.optimize() # don't optimize if there's a value, # if we don't have any child or if we # have more than one child if ( self.value != 0 ) or ( not children ) or len( children ) > 1: return self child = children[0] self.letter += child.letter self.value = child.value self.children = child.children return self def dump_debug( self, write, margin ): # this is used during debugging line = margin + "+-" if len( self.letter ) == 0: line += "<NOLETTER>" else: line += self.letter if self.value: line += " => " + repr( self.value ) write( line + "\n" ) if self.children: margin += "| " for child in self.children.values(): child.dump_debug( write, margin ) def locate( self, index ): self.index = index if len( self.letter ) > 0: index += len( self.letter ) + 1 else: index += 2 if self.value != 0: index += 2 children = self.children.values() children.sort() index += 2 * len( children ) for child in children: index = child.locate( index ) return index def store( self, storage ): # write the letters l = len( self.letter ) if l == 0: storage += struct.pack( "B", 0 ) else: for n in range( l ): val = ord( self.letter[n] ) if n < l - 1: val += 128 storage += struct.pack( "B", val ) # write the count children = self.children.values() children.sort() count = len( children ) if self.value != 0: storage += struct.pack( "!BH", count + 128, self.value ) else: storage += struct.pack( "B", count ) for child in children: storage += struct.pack( "!H", child.index ) for child in children: storage = child.store( storage ) return storage def adobe_glyph_values(): """return the list of glyph names and their unicode values""" lines = string.split( adobe_glyph_list, '\n' ) glyphs = [] values = [] for line in lines: if line: fields = string.split( line, ';' ) # print fields[1] + ' - ' + fields[0] subfields = string.split( fields[1], ' ' ) if len( subfields ) == 1: glyphs.append( fields[0] ) values.append( fields[1] ) return glyphs, values def filter_glyph_names( alist, filter ): """filter `alist' by taking _out_ all glyph names that are in `filter'""" count = 0 extras = [] for name in alist: try: filtered_index = filter.index( name ) except: extras.append( name ) return extras def dump_encoding( file, encoding_name, encoding_list ): """dump a given encoding""" write = file.write write( " /* the following are indices into the SID name table */\n" ) write( " static const unsigned short " + encoding_name + "[" + repr( len( encoding_list ) ) + "] =\n" ) write( " {\n" ) line = " " comma = "" col = 0 for value in encoding_list: line += comma line += "%3d" % value comma = "," col += 1 if col == 16: col = 0 comma = ",\n " write( line + "\n };\n\n\n" ) def dump_array( the_array, write, array_name ): """dumps a given encoding""" write( " static const unsigned char " + array_name + "[" + repr( len( the_array ) ) + "L] =\n" ) write( " {\n" ) line = "" comma = " " col = 0 for value in the_array: line += comma line += "%3d" % ord( value ) comma = "," col += 1 if col == 16: col = 0 comma = ",\n " if len( line ) > 1024: write( line ) line = "" write( line + "\n };\n\n\n" ) def main(): """main program body""" if len( sys.argv ) != 2: print __doc__ % sys.argv[0] sys.exit( 1 ) file = open( sys.argv[1], "w\n" ) write = file.write count_sid = len( sid_standard_names ) # `mac_extras' contains the list of glyph names in the Macintosh standard # encoding which are not in the SID Standard Names. # mac_extras = filter_glyph_names( mac_standard_names, sid_standard_names ) # `base_list' contains the names of our final glyph names table. # It consists of the `mac_extras' glyph names, followed by the SID # standard names. # mac_extras_count = len( mac_extras ) base_list = mac_extras + sid_standard_names write( "/***************************************************************************/\n" ) write( "/* */\n" ) write( "/* %-71s*/\n" % os.path.basename( sys.argv[1] ) ) write( "/* */\n" ) write( "/* PostScript glyph names. */\n" ) write( "/* */\n" ) write( "/* Copyright 2005, 2008, 2011 by */\n" ) write( "/* David Turner, Robert Wilhelm, and Werner Lemberg. */\n" ) write( "/* */\n" ) write( "/* This file is part of the FreeType project, and may only be used, */\n" ) write( "/* modified, and distributed under the terms of the FreeType project */\n" ) write( "/* license, LICENSE.TXT. By continuing to use, modify, or distribute */\n" ) write( "/* this file you indicate that you have read the license and */\n" ) write( "/* understand and accept it fully. */\n" ) write( "/* */\n" ) write( "/***************************************************************************/\n" ) write( "\n" ) write( "\n" ) write( " /* This file has been generated automatically -- do not edit! */\n" ) write( "\n" ) write( "\n" ) # dump final glyph list (mac extras + sid standard names) # st = StringTable( base_list, "ft_standard_glyph_names" ) st.dump( file ) st.dump_sublist( file, "ft_mac_names", "FT_NUM_MAC_NAMES", mac_standard_names ) st.dump_sublist( file, "ft_sid_names", "FT_NUM_SID_NAMES", sid_standard_names ) dump_encoding( file, "t1_standard_encoding", t1_standard_encoding ) dump_encoding( file, "t1_expert_encoding", t1_expert_encoding ) # dump the AGL in its compressed form # agl_glyphs, agl_values = adobe_glyph_values() dict = StringNode( "", 0 ) for g in range( len( agl_glyphs ) ): dict.add( agl_glyphs[g], eval( "0x" + agl_values[g] ) ) dict = dict.optimize() dict_len = dict.locate( 0 ) dict_array = dict.store( "" ) write( """\ /* * This table is a compressed version of the Adobe Glyph List (AGL), * optimized for efficient searching. It has been generated by the * `glnames.py' python script located in the `src/tools' directory. * * The lookup function to get the Unicode value for a given string * is defined below the table. */ #ifdef FT_CONFIG_OPTION_ADOBE_GLYPH_LIST """ ) dump_array( dict_array, write, "ft_adobe_glyph_list" ) # write the lookup routine now # write( """\ /* * This function searches the compressed table efficiently. */ static unsigned long ft_get_adobe_glyph_index( const char* name, const char* limit ) { int c = 0; int count, min, max; const unsigned char* p = ft_adobe_glyph_list; if ( name == 0 || name >= limit ) goto NotFound; c = *name++; count = p[1]; p += 2; min = 0; max = count; while ( min < max ) { int mid = ( min + max ) >> 1; const unsigned char* q = p + mid * 2; int c2; q = ft_adobe_glyph_list + ( ( (int)q[0] << 8 ) | q[1] ); c2 = q[0] & 127; if ( c2 == c ) { p = q; goto Found; } if ( c2 < c ) min = mid + 1; else max = mid; } goto NotFound; Found: for (;;) { /* assert (*p & 127) == c */ if ( name >= limit ) { if ( (p[0] & 128) == 0 && (p[1] & 128) != 0 ) return (unsigned long)( ( (int)p[2] << 8 ) | p[3] ); goto NotFound; } c = *name++; if ( p[0] & 128 ) { p++; if ( c != (p[0] & 127) ) goto NotFound; continue; } p++; count = p[0] & 127; if ( p[0] & 128 ) p += 2; p++; for ( ; count > 0; count--, p += 2 ) { int offset = ( (int)p[0] << 8 ) | p[1]; const unsigned char* q = ft_adobe_glyph_list + offset; if ( c == ( q[0] & 127 ) ) { p = q; goto NextIter; } } goto NotFound; NextIter: ; } NotFound: return 0; } #endif /* FT_CONFIG_OPTION_ADOBE_GLYPH_LIST */ """ ) if 0: # generate unit test, or don't # # now write the unit test to check that everything works OK # write( "#ifdef TEST\n\n" ) write( "static const char* const the_names[] = {\n" ) for name in agl_glyphs: write( ' "' + name + '",\n' ) write( " 0\n};\n" ) write( "static const unsigned long the_values[] = {\n" ) for val in agl_values: write( ' 0x' + val + ',\n' ) write( " 0\n};\n" ) write( """ #include <stdlib.h> #include <stdio.h> int main( void ) { int result = 0; const char* const* names = the_names; const unsigned long* values = the_values; for ( ; *names; names++, values++ ) { const char* name = *names; unsigned long reference = *values; unsigned long value; value = ft_get_adobe_glyph_index( name, name + strlen( name ) ); if ( value != reference ) { result = 1; fprintf( stderr, "name '%s' => %04x instead of %04x\\n", name, value, reference ); } } return result; } """ ) write( "#endif /* TEST */\n" ) write("\n/* END */\n") # Now run the main routine # main() # END
ezeeyahoo/android_kernel_motorola_msm8916
refs/heads/cm-12.1
scripts/rt-tester/rt-tester.py
11005
#!/usr/bin/python # # rt-mutex tester # # (C) 2006 Thomas Gleixner <tglx@linutronix.de> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # import os import sys import getopt import shutil import string # Globals quiet = 0 test = 0 comments = 0 sysfsprefix = "/sys/devices/system/rttest/rttest" statusfile = "/status" commandfile = "/command" # Command opcodes cmd_opcodes = { "schedother" : "1", "schedfifo" : "2", "lock" : "3", "locknowait" : "4", "lockint" : "5", "lockintnowait" : "6", "lockcont" : "7", "unlock" : "8", "signal" : "11", "resetevent" : "98", "reset" : "99", } test_opcodes = { "prioeq" : ["P" , "eq" , None], "priolt" : ["P" , "lt" , None], "priogt" : ["P" , "gt" , None], "nprioeq" : ["N" , "eq" , None], "npriolt" : ["N" , "lt" , None], "npriogt" : ["N" , "gt" , None], "unlocked" : ["M" , "eq" , 0], "trylock" : ["M" , "eq" , 1], "blocked" : ["M" , "eq" , 2], "blockedwake" : ["M" , "eq" , 3], "locked" : ["M" , "eq" , 4], "opcodeeq" : ["O" , "eq" , None], "opcodelt" : ["O" , "lt" , None], "opcodegt" : ["O" , "gt" , None], "eventeq" : ["E" , "eq" , None], "eventlt" : ["E" , "lt" , None], "eventgt" : ["E" , "gt" , None], } # Print usage information def usage(): print "rt-tester.py <-c -h -q -t> <testfile>" print " -c display comments after first command" print " -h help" print " -q quiet mode" print " -t test mode (syntax check)" print " testfile: read test specification from testfile" print " otherwise from stdin" return # Print progress when not in quiet mode def progress(str): if not quiet: print str # Analyse a status value def analyse(val, top, arg): intval = int(val) if top[0] == "M": intval = intval / (10 ** int(arg)) intval = intval % 10 argval = top[2] elif top[0] == "O": argval = int(cmd_opcodes.get(arg, arg)) else: argval = int(arg) # progress("%d %s %d" %(intval, top[1], argval)) if top[1] == "eq" and intval == argval: return 1 if top[1] == "lt" and intval < argval: return 1 if top[1] == "gt" and intval > argval: return 1 return 0 # Parse the commandline try: (options, arguments) = getopt.getopt(sys.argv[1:],'chqt') except getopt.GetoptError, ex: usage() sys.exit(1) # Parse commandline options for option, value in options: if option == "-c": comments = 1 elif option == "-q": quiet = 1 elif option == "-t": test = 1 elif option == '-h': usage() sys.exit(0) # Select the input source if arguments: try: fd = open(arguments[0]) except Exception,ex: sys.stderr.write("File not found %s\n" %(arguments[0])) sys.exit(1) else: fd = sys.stdin linenr = 0 # Read the test patterns while 1: linenr = linenr + 1 line = fd.readline() if not len(line): break line = line.strip() parts = line.split(":") if not parts or len(parts) < 1: continue if len(parts[0]) == 0: continue if parts[0].startswith("#"): if comments > 1: progress(line) continue if comments == 1: comments = 2 progress(line) cmd = parts[0].strip().lower() opc = parts[1].strip().lower() tid = parts[2].strip() dat = parts[3].strip() try: # Test or wait for a status value if cmd == "t" or cmd == "w": testop = test_opcodes[opc] fname = "%s%s%s" %(sysfsprefix, tid, statusfile) if test: print fname continue while 1: query = 1 fsta = open(fname, 'r') status = fsta.readline().strip() fsta.close() stat = status.split(",") for s in stat: s = s.strip() if s.startswith(testop[0]): # Separate status value val = s[2:].strip() query = analyse(val, testop, dat) break if query or cmd == "t": break progress(" " + status) if not query: sys.stderr.write("Test failed in line %d\n" %(linenr)) sys.exit(1) # Issue a command to the tester elif cmd == "c": cmdnr = cmd_opcodes[opc] # Build command string and sys filename cmdstr = "%s:%s" %(cmdnr, dat) fname = "%s%s%s" %(sysfsprefix, tid, commandfile) if test: print fname continue fcmd = open(fname, 'w') fcmd.write(cmdstr) fcmd.close() except Exception,ex: sys.stderr.write(str(ex)) sys.stderr.write("\nSyntax error in line %d\n" %(linenr)) if not test: fd.close() sys.exit(1) # Normal exit pass print "Pass" sys.exit(0)
vizual54/MissionPlanner
refs/heads/master
Lib/sunau.py
53
"""Stuff to parse Sun and NeXT audio files. An audio file consists of a header followed by the data. The structure of the header is as follows. +---------------+ | magic word | +---------------+ | header size | +---------------+ | data size | +---------------+ | encoding | +---------------+ | sample rate | +---------------+ | # of channels | +---------------+ | info | | | +---------------+ The magic word consists of the 4 characters '.snd'. Apart from the info field, all header fields are 4 bytes in size. They are all 32-bit unsigned integers encoded in big-endian byte order. The header size really gives the start of the data. The data size is the physical size of the data. From the other parameters the number of frames can be calculated. The encoding gives the way in which audio samples are encoded. Possible values are listed below. The info field currently consists of an ASCII string giving a human-readable description of the audio file. The info field is padded with NUL bytes to the header size. Usage. Reading audio files: f = sunau.open(file, 'r') where file is either the name of a file or an open file pointer. The open file pointer must have methods read(), seek(), and close(). When the setpos() and rewind() methods are not used, the seek() method is not necessary. This returns an instance of a class with the following public methods: getnchannels() -- returns number of audio channels (1 for mono, 2 for stereo) getsampwidth() -- returns sample width in bytes getframerate() -- returns sampling frequency getnframes() -- returns number of audio frames getcomptype() -- returns compression type ('NONE' or 'ULAW') getcompname() -- returns human-readable version of compression type ('not compressed' matches 'NONE') getparams() -- returns a tuple consisting of all of the above in the above order getmarkers() -- returns None (for compatibility with the aifc module) getmark(id) -- raises an error since the mark does not exist (for compatibility with the aifc module) readframes(n) -- returns at most n frames of audio rewind() -- rewind to the beginning of the audio stream setpos(pos) -- seek to the specified position tell() -- return the current position close() -- close the instance (make it unusable) The position returned by tell() and the position given to setpos() are compatible and have nothing to do with the actual position in the file. The close() method is called automatically when the class instance is destroyed. Writing audio files: f = sunau.open(file, 'w') where file is either the name of a file or an open file pointer. The open file pointer must have methods write(), tell(), seek(), and close(). This returns an instance of a class with the following public methods: setnchannels(n) -- set the number of channels setsampwidth(n) -- set the sample width setframerate(n) -- set the frame rate setnframes(n) -- set the number of frames setcomptype(type, name) -- set the compression type and the human-readable compression type setparams(tuple)-- set all parameters at once tell() -- return current position in output file writeframesraw(data) -- write audio frames without pathing up the file header writeframes(data) -- write audio frames and patch up the file header close() -- patch up the file header and close the output file You should set the parameters before the first writeframesraw or writeframes. The total number of frames does not need to be set, but when it is set to the correct value, the header does not have to be patched up. It is best to first set all parameters, perhaps possibly the compression type, and then write audio frames using writeframesraw. When all frames have been written, either call writeframes('') or close() to patch up the sizes in the header. The close() method is called automatically when the class instance is destroyed. """ # from <multimedia/audio_filehdr.h> AUDIO_FILE_MAGIC = 0x2e736e64 AUDIO_FILE_ENCODING_MULAW_8 = 1 AUDIO_FILE_ENCODING_LINEAR_8 = 2 AUDIO_FILE_ENCODING_LINEAR_16 = 3 AUDIO_FILE_ENCODING_LINEAR_24 = 4 AUDIO_FILE_ENCODING_LINEAR_32 = 5 AUDIO_FILE_ENCODING_FLOAT = 6 AUDIO_FILE_ENCODING_DOUBLE = 7 AUDIO_FILE_ENCODING_ADPCM_G721 = 23 AUDIO_FILE_ENCODING_ADPCM_G722 = 24 AUDIO_FILE_ENCODING_ADPCM_G723_3 = 25 AUDIO_FILE_ENCODING_ADPCM_G723_5 = 26 AUDIO_FILE_ENCODING_ALAW_8 = 27 # from <multimedia/audio_hdr.h> AUDIO_UNKNOWN_SIZE = 0xFFFFFFFFL # ((unsigned)(~0)) _simple_encodings = [AUDIO_FILE_ENCODING_MULAW_8, AUDIO_FILE_ENCODING_LINEAR_8, AUDIO_FILE_ENCODING_LINEAR_16, AUDIO_FILE_ENCODING_LINEAR_24, AUDIO_FILE_ENCODING_LINEAR_32, AUDIO_FILE_ENCODING_ALAW_8] class Error(Exception): pass def _read_u32(file): x = 0L for i in range(4): byte = file.read(1) if byte == '': raise EOFError x = x*256 + ord(byte) return x def _write_u32(file, x): data = [] for i in range(4): d, m = divmod(x, 256) data.insert(0, m) x = d for i in range(4): file.write(chr(int(data[i]))) class Au_read: def __init__(self, f): if type(f) == type(''): import __builtin__ f = __builtin__.open(f, 'rb') self.initfp(f) def __del__(self): if self._file: self.close() def initfp(self, file): self._file = file self._soundpos = 0 magic = int(_read_u32(file)) if magic != AUDIO_FILE_MAGIC: raise Error, 'bad magic number' self._hdr_size = int(_read_u32(file)) if self._hdr_size < 24: raise Error, 'header size too small' if self._hdr_size > 100: raise Error, 'header size ridiculously large' self._data_size = _read_u32(file) if self._data_size != AUDIO_UNKNOWN_SIZE: self._data_size = int(self._data_size) self._encoding = int(_read_u32(file)) if self._encoding not in _simple_encodings: raise Error, 'encoding not (yet) supported' if self._encoding in (AUDIO_FILE_ENCODING_MULAW_8, AUDIO_FILE_ENCODING_ALAW_8): self._sampwidth = 2 self._framesize = 1 elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_8: self._framesize = self._sampwidth = 1 elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_16: self._framesize = self._sampwidth = 2 elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_24: self._framesize = self._sampwidth = 3 elif self._encoding == AUDIO_FILE_ENCODING_LINEAR_32: self._framesize = self._sampwidth = 4 else: raise Error, 'unknown encoding' self._framerate = int(_read_u32(file)) self._nchannels = int(_read_u32(file)) self._framesize = self._framesize * self._nchannels if self._hdr_size > 24: self._info = file.read(self._hdr_size - 24) for i in range(len(self._info)): if self._info[i] == '\0': self._info = self._info[:i] break else: self._info = '' def getfp(self): return self._file def getnchannels(self): return self._nchannels def getsampwidth(self): return self._sampwidth def getframerate(self): return self._framerate def getnframes(self): if self._data_size == AUDIO_UNKNOWN_SIZE: return AUDIO_UNKNOWN_SIZE if self._encoding in _simple_encodings: return self._data_size / self._framesize return 0 # XXX--must do some arithmetic here def getcomptype(self): if self._encoding == AUDIO_FILE_ENCODING_MULAW_8: return 'ULAW' elif self._encoding == AUDIO_FILE_ENCODING_ALAW_8: return 'ALAW' else: return 'NONE' def getcompname(self): if self._encoding == AUDIO_FILE_ENCODING_MULAW_8: return 'CCITT G.711 u-law' elif self._encoding == AUDIO_FILE_ENCODING_ALAW_8: return 'CCITT G.711 A-law' else: return 'not compressed' def getparams(self): return self.getnchannels(), self.getsampwidth(), \ self.getframerate(), self.getnframes(), \ self.getcomptype(), self.getcompname() def getmarkers(self): return None def getmark(self, id): raise Error, 'no marks' def readframes(self, nframes): if self._encoding in _simple_encodings: if nframes == AUDIO_UNKNOWN_SIZE: data = self._file.read() else: data = self._file.read(nframes * self._framesize * self._nchannels) if self._encoding == AUDIO_FILE_ENCODING_MULAW_8: import audioop data = audioop.ulaw2lin(data, self._sampwidth) return data return None # XXX--not implemented yet def rewind(self): self._soundpos = 0 self._file.seek(self._hdr_size) def tell(self): return self._soundpos def setpos(self, pos): if pos < 0 or pos > self.getnframes(): raise Error, 'position not in range' self._file.seek(pos * self._framesize + self._hdr_size) self._soundpos = pos def close(self): self._file = None class Au_write: def __init__(self, f): if type(f) == type(''): import __builtin__ f = __builtin__.open(f, 'wb') self.initfp(f) def __del__(self): if self._file: self.close() def initfp(self, file): self._file = file self._framerate = 0 self._nchannels = 0 self._sampwidth = 0 self._framesize = 0 self._nframes = AUDIO_UNKNOWN_SIZE self._nframeswritten = 0 self._datawritten = 0 self._datalength = 0 self._info = '' self._comptype = 'ULAW' # default is U-law def setnchannels(self, nchannels): if self._nframeswritten: raise Error, 'cannot change parameters after starting to write' if nchannels not in (1, 2, 4): raise Error, 'only 1, 2, or 4 channels supported' self._nchannels = nchannels def getnchannels(self): if not self._nchannels: raise Error, 'number of channels not set' return self._nchannels def setsampwidth(self, sampwidth): if self._nframeswritten: raise Error, 'cannot change parameters after starting to write' if sampwidth not in (1, 2, 4): raise Error, 'bad sample width' self._sampwidth = sampwidth def getsampwidth(self): if not self._framerate: raise Error, 'sample width not specified' return self._sampwidth def setframerate(self, framerate): if self._nframeswritten: raise Error, 'cannot change parameters after starting to write' self._framerate = framerate def getframerate(self): if not self._framerate: raise Error, 'frame rate not set' return self._framerate def setnframes(self, nframes): if self._nframeswritten: raise Error, 'cannot change parameters after starting to write' if nframes < 0: raise Error, '# of frames cannot be negative' self._nframes = nframes def getnframes(self): return self._nframeswritten def setcomptype(self, type, name): if type in ('NONE', 'ULAW'): self._comptype = type else: raise Error, 'unknown compression type' def getcomptype(self): return self._comptype def getcompname(self): if self._comptype == 'ULAW': return 'CCITT G.711 u-law' elif self._comptype == 'ALAW': return 'CCITT G.711 A-law' else: return 'not compressed' def setparams(self, params): nchannels, sampwidth, framerate, nframes, comptype, compname = params self.setnchannels(nchannels) self.setsampwidth(sampwidth) self.setframerate(framerate) self.setnframes(nframes) self.setcomptype(comptype, compname) def getparams(self): return self.getnchannels(), self.getsampwidth(), \ self.getframerate(), self.getnframes(), \ self.getcomptype(), self.getcompname() def tell(self): return self._nframeswritten def writeframesraw(self, data): self._ensure_header_written() nframes = len(data) / self._framesize if self._comptype == 'ULAW': import audioop data = audioop.lin2ulaw(data, self._sampwidth) self._file.write(data) self._nframeswritten = self._nframeswritten + nframes self._datawritten = self._datawritten + len(data) def writeframes(self, data): self.writeframesraw(data) if self._nframeswritten != self._nframes or \ self._datalength != self._datawritten: self._patchheader() def close(self): self._ensure_header_written() if self._nframeswritten != self._nframes or \ self._datalength != self._datawritten: self._patchheader() self._file.flush() self._file = None # # private methods # def _ensure_header_written(self): if not self._nframeswritten: if not self._nchannels: raise Error, '# of channels not specified' if not self._sampwidth: raise Error, 'sample width not specified' if not self._framerate: raise Error, 'frame rate not specified' self._write_header() def _write_header(self): if self._comptype == 'NONE': if self._sampwidth == 1: encoding = AUDIO_FILE_ENCODING_LINEAR_8 self._framesize = 1 elif self._sampwidth == 2: encoding = AUDIO_FILE_ENCODING_LINEAR_16 self._framesize = 2 elif self._sampwidth == 4: encoding = AUDIO_FILE_ENCODING_LINEAR_32 self._framesize = 4 else: raise Error, 'internal error' elif self._comptype == 'ULAW': encoding = AUDIO_FILE_ENCODING_MULAW_8 self._framesize = 1 else: raise Error, 'internal error' self._framesize = self._framesize * self._nchannels _write_u32(self._file, AUDIO_FILE_MAGIC) header_size = 25 + len(self._info) header_size = (header_size + 7) & ~7 _write_u32(self._file, header_size) if self._nframes == AUDIO_UNKNOWN_SIZE: length = AUDIO_UNKNOWN_SIZE else: length = self._nframes * self._framesize _write_u32(self._file, length) self._datalength = length _write_u32(self._file, encoding) _write_u32(self._file, self._framerate) _write_u32(self._file, self._nchannels) self._file.write(self._info) self._file.write('\0'*(header_size - len(self._info) - 24)) def _patchheader(self): self._file.seek(8) _write_u32(self._file, self._datawritten) self._datalength = self._datawritten self._file.seek(0, 2) def open(f, mode=None): if mode is None: if hasattr(f, 'mode'): mode = f.mode else: mode = 'rb' if mode in ('r', 'rb'): return Au_read(f) elif mode in ('w', 'wb'): return Au_write(f) else: raise Error, "mode must be 'r', 'rb', 'w', or 'wb'" openfp = open
jhgoebbert/cvl-fabric-launcher
refs/heads/master
pyinstaller-2.1/PyInstaller/hooks/hook-matplotlib.backends.py
10
#----------------------------------------------------------------------------- # Copyright (c) 2013, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- from PyInstaller.hooks.hookutils import matplotlib_backends # Include only available matplotlib backends. hiddenimports = matplotlib_backends()
kenwmitchell/ansible-modules-core
refs/heads/devel
system/__init__.py
12133432
kyuridenamida/ToolsForAtCoder
refs/heads/master
atcodertools/fileutils/__init__.py
12133432
grow/pygrow
refs/heads/master
grow/translators/__init__.py
12133432
htzy/bigfour
refs/heads/master
common/djangoapps/embargo/tests/test_middleware.py
36
""" Tests for EmbargoMiddleware with CountryAccessRules """ import unittest from mock import patch import ddt from django.core.urlresolvers import reverse from django.conf import settings from django.core.cache import cache as django_cache from util.testing import UrlResetMixin from student.tests.factories import UserFactory from xmodule.modulestore.tests.factories import CourseFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from config_models.models import cache as config_cache from embargo.models import RestrictedCourse, IPFilter from embargo.test_utils import restrict_course @ddt.ddt @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') class EmbargoMiddlewareAccessTests(UrlResetMixin, ModuleStoreTestCase): """Tests of embargo middleware country access rules. There are detailed unit tests for the rule logic in `test_api.py`; here, we're mainly testing the integration with middleware """ USERNAME = 'fred' PASSWORD = 'secret' @patch.dict(settings.FEATURES, {'EMBARGO': True}) def setUp(self): super(EmbargoMiddlewareAccessTests, self).setUp('embargo') self.user = UserFactory(username=self.USERNAME, password=self.PASSWORD) self.course = CourseFactory.create() self.client.login(username=self.USERNAME, password=self.PASSWORD) self.courseware_url = reverse( 'course_root', kwargs={'course_id': unicode(self.course.id)} ) self.non_courseware_url = reverse('dashboard') # Clear the cache to avoid interference between tests django_cache.clear() config_cache.clear() @patch.dict(settings.FEATURES, {'EMBARGO': True}) @ddt.data(True, False) def test_blocked(self, disable_access_check): with restrict_course(self.course.id, access_point='courseware', disable_access_check=disable_access_check) as redirect_url: # pylint: disable=line-too-long response = self.client.get(self.courseware_url) if disable_access_check: self.assertEqual(response.status_code, 200) else: self.assertRedirects(response, redirect_url) @patch.dict(settings.FEATURES, {'EMBARGO': True}) def test_allowed(self): # Add the course to the list of restricted courses # but don't create any access rules RestrictedCourse.objects.create(course_key=self.course.id) # Expect that we can access courseware response = self.client.get(self.courseware_url) self.assertEqual(response.status_code, 200) @patch.dict(settings.FEATURES, {'EMBARGO': True}) def test_non_courseware_url(self): with restrict_course(self.course.id): response = self.client.get(self.non_courseware_url) self.assertEqual(response.status_code, 200) @patch.dict(settings.FEATURES, {'EMBARGO': True}) @ddt.data( # request_ip, blacklist, whitelist, is_enabled, allow_access ('173.194.123.35', ['173.194.123.35'], [], True, False), ('173.194.123.35', ['173.194.0.0/16'], [], True, False), ('173.194.123.35', ['127.0.0.0/32', '173.194.0.0/16'], [], True, False), ('173.195.10.20', ['173.194.0.0/16'], [], True, True), ('173.194.123.35', ['173.194.0.0/16'], ['173.194.0.0/16'], True, False), ('173.194.123.35', [], ['173.194.0.0/16'], True, True), ('192.178.2.3', [], ['173.194.0.0/16'], True, True), ('173.194.123.35', ['173.194.123.35'], [], False, True), ) @ddt.unpack def test_ip_access_rules(self, request_ip, blacklist, whitelist, is_enabled, allow_access): # Ensure that IP blocking works for anonymous users self.client.logout() # Set up the IP rules IPFilter.objects.create( blacklist=", ".join(blacklist), whitelist=", ".join(whitelist), enabled=is_enabled ) # Check that access is enforced response = self.client.get( "/", HTTP_X_FORWARDED_FOR=request_ip, REMOTE_ADDR=request_ip ) if allow_access: self.assertEqual(response.status_code, 200) else: redirect_url = reverse( 'embargo_blocked_message', kwargs={ 'access_point': 'courseware', 'message_key': 'embargo' } ) self.assertRedirects(response, redirect_url) @patch.dict(settings.FEATURES, {'EMBARGO': True}) @ddt.data( ('courseware', 'default'), ('courseware', 'embargo'), ('enrollment', 'default'), ('enrollment', 'embargo') ) @ddt.unpack def test_always_allow_access_to_embargo_messages(self, access_point, msg_key): # Blacklist an IP address IPFilter.objects.create( blacklist="192.168.10.20", enabled=True ) url = reverse( 'embargo_blocked_message', kwargs={ 'access_point': access_point, 'message_key': msg_key } ) response = self.client.get( url, HTTP_X_FORWARDED_FOR="192.168.10.20", REMOTE_ADDR="192.168.10.20" ) self.assertEqual(response.status_code, 200) @patch.dict(settings.FEATURES, {'EMBARGO': True}) def test_whitelist_ip_skips_country_access_checks(self): # Whitelist an IP address IPFilter.objects.create( whitelist="192.168.10.20", enabled=True ) # Set up country access rules so the user would # be restricted from the course. with restrict_course(self.course.id): # Make a request from the whitelisted IP address response = self.client.get( self.courseware_url, HTTP_X_FORWARDED_FOR="192.168.10.20", REMOTE_ADDR="192.168.10.20" ) # Expect that we were still able to access the page, # even though we would have been blocked by country # access rules. self.assertEqual(response.status_code, 200)
silenci/neutron
refs/heads/master
neutron/plugins/ml2/drivers/linuxbridge/agent/common/constants.py
18
# Copyright 2012 Cisco Systems, 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. FLAT_VLAN_ID = -1 LOCAL_VLAN_ID = -2 # Supported VXLAN features VXLAN_NONE = 'not_supported' VXLAN_MCAST = 'multicast_flooding' VXLAN_UCAST = 'unicast_flooding'
timmygee/investorservitude
refs/heads/master
investorservitude/core/management/commands/poll.py
1
import requests import re from decimal import Decimal from datetime import datetime from bs4 import BeautifulSoup from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.db import models from django.db.utils import IntegrityError from core.models import Holding heading_regex = re.compile(r'^\W*([\w ]+)\W*$') def convert_heading(heading): """ Convert the table heading string to the appropriate holding field name """ if not heading: return None match = heading_regex.match(heading) if match: return '_'.join(match.groups()[0].lower().split()) return None def strip_unwanted(data_str): """ Strip out any unwanted characters from the table data string """ # Right now, this just requires stripping out commas return data_str.replace(',', '') class PollCommandError(CommandError): pass class Command(BaseCommand): help = 'Polls InvestorServe for your latest holding data' def handle(self, *args, **options): response = requests.get(settings.INVESTORSERVE_URL) if response.status_code != 200: raise PollCommandError( 'Received HTTP error code {} when accessing {}'.format( response.status_code, settings.INVESTORSERVE_URL)) soup = BeautifulSoup(response.content, 'html.parser') post_data = {} for input_name in ('SessionId', 'SessionKey'): post_data[input_name] = soup.find('input', attrs={'name': input_name})['value'] post_data.update({ 'Username': settings.INVESTORSERVE_USERNAME, 'Password': settings.INVESTORSERVE_PASSWORD, 'Command': 'login', }) # print(post_data) response = requests.post(settings.INVESTORSERVE_URL, data=post_data) if response.status_code != 200: raise PollCommandError( 'Received HTTP error code {} when posting to {}'.format( response.status_code, settings.INVESTORSERVE_URL)) soup = BeautifulSoup(response.content, 'html.parser') # soup = BeautifulSoup( # open('../www.investorserve.com.au.html', 'r'), 'html.parser') data_table = soup.find('table', class_='datatable') headers = [convert_heading(th.string) for th in data_table.contents[0].children] for tr in data_table.contents[1:]: holding_data = {} for i, td in enumerate(tr.children): field_name = headers[i] if field_name: for field in Holding._meta.fields: if field.name == field_name: break else: raise PollCommandError('Unexpected field {}'.format(field_name)) clean_data_str = strip_unwanted(td.string) if isinstance(field, models.DecimalField): holding_data[field_name] = Decimal(clean_data_str) elif isinstance(field, models.DateField): holding_data[field_name] = datetime.strptime( clean_data_str, '%d/%m/%Y').date() elif any([ isinstance(field, models.CharField), isinstance(field, models.IntegerField) ]): holding_data[field_name] = clean_data_str # print(holding_data) try: holding, created = Holding.objects.update_or_create( security=holding_data['security'], close_price_date=holding_data['close_price_date'], defaults=holding_data) if created: self.stdout.write( self.style.SUCCESS('Created holding entry {}'.format(holding))) else: self.stdout.write( self.style.SUCCESS('Updated holding entry {}'.format(holding))) except IntegrityError as e: self.stdout.write(self.style.ERROR( 'Integrity error when trying to create new holding entry. Most likely this is ' 'because a holding entry for the security/date combination already exists. ' 'Error recieved: {}'.format(e)))
peterjanes/dosage
refs/heads/master
tests/test_rss.py
1
# -*- coding: utf-8 -*- # Copyright (C) 2019 Tobias Gruetzmacher from __future__ import absolute_import, division, print_function import time from dosagelib.rss import parseFeed class TestFeed(object): """ Tests for rss.py """ def test_parseFeed(self): testTime = time.localtime(1560000000.0) feed = parseFeed('./tests/mocks/dailydose.rss', testTime) xmlBlob = feed.getXML() assert u'PlumedDotage - 4034.png'.encode() in xmlBlob assert u'PachinkoParlor - 20190626.jpg'.encode() not in xmlBlob
travislbrundage/geonode
refs/heads/master
geonode/contrib/api_basemaps/osm.py
13
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ######################################################################### from geonode.settings import MAP_BASELAYERS OSM = { 'maps': { 'de': { 'enabled': True, 'name': 'OSM DE', 'visibility': False, 'url': ('http://a.tile.openstreetmap.de/tiles/osmde/${z}/${x}/${y}' '.png'), 'attribution': ('&copy; <a href="http://www.openstreetmap.org/copy' 'right">OpenStreetMap</a>') }, 'france': { 'enabled': True, 'name': 'OSM France', 'visibility': False, 'url': ('http://a.tile.openstreetmap.fr/osmfr/${z}/${x}/${y}.png'), 'attribution': ('&copy; Openstreetmap France | &copy; <a href="htt' 'p://www.openstreetmap.org/copyright">OpenStreetMa' 'p</a>') }, 'hot': { 'enabled': True, 'name': 'OSM HOT', 'visibility': False, 'url': ('http://a.tile.openstreetmap.fr/hot/${z}/${x}/${y}.png'), 'attribution': ('&copy; <a href="http://www.openstreetmap.org/copy' 'right">OpenStreetMap</a>, Tiles courtesy of <a hr' 'ef="http://hot.openstreetmap.org/" target="_blank' '">Humanitarian OpenStreetMap Team</a>') } } } for k, v in OSM['maps'].items(): if v['enabled']: BASEMAP = { 'source': { 'ptype': 'gxp_olsource' }, 'type': 'OpenLayers.Layer.XYZ', "args": [ '%s' % v['name'], [v['url']], { 'transitionEffect': 'resize', 'attribution': '%s' % v['attribution'], } ], 'fixed': True, 'visibility': v['visibility'], 'group': 'background' } MAP_BASELAYERS.append(BASEMAP)
aljim/deploymentmanager-samples
refs/heads/master
community/cloud-foundation/tests/unit/test_deployment.py
2
from six import PY2 from apitools.base.py.exceptions import HttpNotFoundError import jinja2 import pytest from ruamel.yaml import YAML from cloud_foundation_toolkit.deployment import Config from cloud_foundation_toolkit.deployment import ConfigGraph from cloud_foundation_toolkit.deployment import Deployment if PY2: import mock else: import unittest.mock as mock class Message(): def __init__(self, **kwargs): [setattr(self, k, v) for k, v in kwargs.items()] @pytest.fixture def args(): return Args() def test_config(configs): c = Config(configs.files['my-networks.yaml'].path) assert c.as_string == configs.files['my-networks.yaml'].jinja def test_config_list(configs): config_paths = [v.path for k, v in configs.files.items()] config_list = ConfigGraph(config_paths) for level in config_list: assert isinstance(level, list) for c in level: assert isinstance(c, Config) def test_deployment_object(configs): config = Config(configs.files['my-networks.yaml'].path) deployment = Deployment(config) assert deployment.config['name'] == 'my-networks' def test_deployment_get(configs): config = Config(configs.files['my-networks.yaml'].path) deployment = Deployment(config) with mock.patch.object(deployment.client.deployments, 'Get') as m: m.return_value = Message( name='my-networks', fingerprint='abcdefgh' ) d = deployment.get() assert d is not None assert deployment.current == d def test_deployment_get_doesnt_exist(configs): config = Config(configs.files['my-networks.yaml'].path) deployment = Deployment(config) with mock.patch('cloud_foundation_toolkit.deployment.get_deployment') as m: m.return_value = None d = deployment.get() assert d is None assert deployment.current == d def test_deployment_create(configs): config = Config(configs.files['my-networks.yaml'].path) patches = { 'client': mock.DEFAULT, 'wait': mock.DEFAULT, 'get': mock.DEFAULT, 'print_resources_and_outputs': mock.DEFAULT } with mock.patch.multiple(Deployment, **patches) as mocks: deployment = Deployment(config) mocks['client'].deployments.Insert.return_value = Message( name='my-network-prod', fingerprint='abcdefgh' ) mocks['client'].deployments.Get.return_value = Message( name='my-network-prod', fingerprint='abcdefgh' ) d = deployment.create() assert deployment.current == d
ftick/pyNES
refs/heads/0.1.x
pynes/tests/commandline_test.py
28
# -*- coding: utf-8 -*- from pynes import main from pynes.tests import FileTestCase from mock import patch class CommandLineTest(FileTestCase): @patch('pynes.compiler.compile_file') def test_asm(self, compiler): main("pynes asm fixtures/movingsprite/movingsprite.asm".split()) compiler.assert_called_once_with( 'fixtures/movingsprite/movingsprite.asm', output=None, path=None) @patch('pynes.compiler.compile_file') def test_asm_with_output(self, compiler): main("pynes asm fixtures/movingsprite/movingsprite.asm --output" " /tmp/movingsprite.nes".split()) compiler.assert_called_once_with( 'fixtures/movingsprite/movingsprite.asm', output='/tmp/movingsprite.nes', path=None) @patch('pynes.compiler.compile_file') def test_asm_with_path(self, compiler): main("pynes asm fixtures/movingsprite/movingsprite.asm --path " "fixtures/movingsprite".split()) compiler.assert_called_once_with( 'fixtures/movingsprite/movingsprite.asm', output=None, path='fixtures/movingsprite') @patch('pynes.composer.compose_file') def test_py(self, composer): main("pynes py pynes/examples/movingsprite.py".split()) composer.assert_called_once_with( 'pynes/examples/movingsprite.py', output=None, asm=False, path=None) @patch('pynes.composer.compose_file') def test_py_with_asm(self, composer): main("pynes py pynes/examples/movingsprite.py --asm".split()) composer.assert_called_once_with( 'pynes/examples/movingsprite.py', output=None, asm=True, path=None) @patch('pynes.composer.compose_file') def test_py_with_output(self, composer): main("pynes py pynes/examples/movingsprite.py --output " "output.nes".split()) composer.assert_called_once_with( 'pynes/examples/movingsprite.py', output='output.nes', asm=False, path=None) @patch('pynes.composer.compose_file') def test_py_with_path(self, composer): main("pynes py pynes/examples/movingsprite.py --path " "fixtures/movingsprite".split()) composer.assert_called_once_with( 'pynes/examples/movingsprite.py', output=None, path='fixtures/movingsprite', asm=False) def test_py_real_build_movingsprite(self): args = ( "pynes py pynes/examples/movingsprite.py " "--path fixtures/movingsprite " "--output pynes/examples/movingsprite.nes" ).split() main(args) def test_py_real_build_mario(self): args = ( "pynes py pynes/examples/mario.py " "--path fixtures/nerdynights/scrolling " "--output pynes/examples/mario.nes" ).split() main(args) def test_py_real_build_helloworld(self): args = ( "pynes py pynes/examples/helloworld.py " "--path fixtures/nerdynights/scrolling " "--output pynes/examples/helloworld.nes" ).split() main(args) def test_py_real_build_slides(self): args = ( "pynes py pynes/examples/slides.py " "--path fixtures/nerdynights/scrolling " "--output pynes/examples/slides.nes --asm" ).split() main(args)
jgeskens/django
refs/heads/master
tests/bug8245/__init__.py
12133432
yongshengwang/hue
refs/heads/master
desktop/core/ext-py/django-extensions-1.5.0/build/lib/django_extensions/db/__init__.py
12133432
leopardPrint/ipythonNotebookModules
refs/heads/master
src/__init__.py
12133432
Arundhatii/erpnext
refs/heads/develop
erpnext/schools/doctype/assessment_criteria_group/__init__.py
12133432
rtoal/polyglot
refs/heads/master
python/animals.py
1
class Animal: def __init__(self, name): self.name = name def speak(self): return '{} says {}'.format(self.name, self.sound()) class Cow(Animal): def sound(self): return 'moooo' class Horse(Animal): def sound(self): return 'neigh' class Sheep(Animal): def sound(self): return 'baaaa' if __name__ == '__main__': s = Horse('CJ') assert s.speak() == 'CJ says neigh' c = Cow('Bessie') assert c.speak() == 'Bessie says moooo' assert Sheep('Little Lamb').speak() == 'Little Lamb says baaaa'
nekulin/arangodb
refs/heads/devel
3rdParty/V8-4.3.61/third_party/python_26/Lib/sqlite3/dump.py
247
# Mimic the sqlite3 console shell's .dump command # Author: Paul Kippes <kippesp@gmail.com> def _iterdump(connection): """ Returns an iterator to the dump of the database in an SQL text format. Used to produce an SQL dump of the database. Useful to save an in-memory database for later restoration. This function should not be called directly but instead called from the Connection method, iterdump(). """ cu = connection.cursor() yield('BEGIN TRANSACTION;') # sqlite_master table contains the SQL CREATE statements for the database. q = """ SELECT name, type, sql FROM sqlite_master WHERE sql NOT NULL AND type == 'table' """ schema_res = cu.execute(q) for table_name, type, sql in schema_res.fetchall(): if table_name == 'sqlite_sequence': yield('DELETE FROM sqlite_sequence;') elif table_name == 'sqlite_stat1': yield('ANALYZE sqlite_master;') elif table_name.startswith('sqlite_'): continue # NOTE: Virtual table support not implemented #elif sql.startswith('CREATE VIRTUAL TABLE'): # qtable = table_name.replace("'", "''") # yield("INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"\ # "VALUES('table','%s','%s',0,'%s');" % # qtable, # qtable, # sql.replace("''")) else: yield('%s;' % sql) # Build the insert statement for each row of the current table res = cu.execute("PRAGMA table_info('%s')" % table_name) column_names = [str(table_info[1]) for table_info in res.fetchall()] q = "SELECT 'INSERT INTO \"%(tbl_name)s\" VALUES(" q += ",".join(["'||quote(" + col + ")||'" for col in column_names]) q += ")' FROM '%(tbl_name)s'" query_res = cu.execute(q % {'tbl_name': table_name}) for row in query_res: yield("%s;" % row[0]) # Now when the type is 'index', 'trigger', or 'view' q = """ SELECT name, type, sql FROM sqlite_master WHERE sql NOT NULL AND type IN ('index', 'trigger', 'view') """ schema_res = cu.execute(q) for name, type, sql in schema_res.fetchall(): yield('%s;' % sql) yield('COMMIT;')
mubix/pth-toolkit
refs/heads/master
lib/python2.7/site-packages/samba/tests/samba3.py
5
# Unix SMB/CIFS implementation. # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """Tests for samba.samba3.""" from samba.samba3 import ( Registry, WinsDatabase, IdmapDatabase, ) from samba.samba3 import passdb from samba.samba3 import param as s3param from samba.tests import TestCase, TestCaseInTempDir from samba.dcerpc.security import dom_sid import os for p in [ "../../../../../testdata/samba3", "../../../../testdata/samba3" ]: DATADIR = os.path.join(os.path.dirname(__file__), p) if os.path.exists(DATADIR): break class RegistryTestCase(TestCase): def setUp(self): super(RegistryTestCase, self).setUp() self.registry = Registry(os.path.join(DATADIR, "registry.tdb")) def tearDown(self): self.registry.close() super(RegistryTestCase, self).tearDown() def test_length(self): self.assertEquals(28, len(self.registry)) def test_keys(self): self.assertTrue("HKLM" in self.registry.keys()) def test_subkeys(self): self.assertEquals(["SOFTWARE", "SYSTEM"], self.registry.subkeys("HKLM")) def test_values(self): self.assertEquals({'DisplayName': (1L, 'E\x00v\x00e\x00n\x00t\x00 \x00L\x00o\x00g\x00\x00\x00'), 'ErrorControl': (4L, '\x01\x00\x00\x00')}, self.registry.values("HKLM/SYSTEM/CURRENTCONTROLSET/SERVICES/EVENTLOG")) class PassdbTestCase(TestCaseInTempDir): def setUp(self): super (PassdbTestCase, self).setUp() os.system("cp -r %s %s" % (DATADIR, self.tempdir)) datadir = os.path.join(self.tempdir, "samba3") self.lp = s3param.get_context() self.lp.load(os.path.join(datadir, "smb.conf")) self.lp.set("private dir", datadir) self.lp.set("state directory", datadir) self.lp.set("lock directory", datadir) passdb.set_secrets_dir(datadir) self.pdb = passdb.PDB("tdbsam") def tearDown(self): self.lp = [] self.pdb = [] os.system("rm -rf %s" % os.path.join(self.tempdir, "samba3")) super(PassdbTestCase, self).tearDown() def test_param(self): self.assertEquals("BEDWYR", self.lp.get("netbios name")) self.assertEquals("SAMBA", self.lp.get("workgroup")) self.assertEquals("USER", self.lp.get("security")) def test_policy(self): policy = self.pdb.get_account_policy() self.assertEquals(0, policy['bad lockout attempt']) self.assertEquals(-1, policy['disconnect time']) self.assertEquals(0, policy['lockout duration']) self.assertEquals(999999999, policy['maximum password age']) self.assertEquals(0, policy['minimum password age']) self.assertEquals(5, policy['min password length']) self.assertEquals(0, policy['password history']) self.assertEquals(0, policy['refuse machine password change']) self.assertEquals(0, policy['reset count minutes']) self.assertEquals(0, policy['user must logon to change password']) def test_get_sid(self): domain_sid = passdb.get_global_sam_sid() self.assertEquals(dom_sid("S-1-5-21-2470180966-3899876309-2637894779"), domain_sid) def test_usernames(self): userlist = self.pdb.search_users(0) self.assertEquals(3, len(userlist)) def test_getuser(self): user = self.pdb.getsampwnam("root") self.assertEquals(16, user.acct_ctrl) self.assertEquals("", user.acct_desc) self.assertEquals(0, user.bad_password_count) self.assertEquals(0, user.bad_password_time) self.assertEquals(0, user.code_page) self.assertEquals(0, user.country_code) self.assertEquals("", user.dir_drive) self.assertEquals("BEDWYR", user.domain) self.assertEquals("root", user.full_name) self.assertEquals(dom_sid('S-1-5-21-2470180966-3899876309-2637894779-513'), user.group_sid) self.assertEquals("\\\\BEDWYR\\root", user.home_dir) self.assertEquals([-1 for i in range(21)], user.hours) self.assertEquals(21, user.hours_len) self.assertEquals(9223372036854775807, user.kickoff_time) self.assertEquals(None, user.lanman_passwd) self.assertEquals(9223372036854775807, user.logoff_time) self.assertEquals(0, user.logon_count) self.assertEquals(168, user.logon_divs) self.assertEquals("", user.logon_script) self.assertEquals(0, user.logon_time) self.assertEquals("", user.munged_dial) self.assertEquals('\x87\x8d\x80\x14`l\xda)gzD\xef\xa15?\xc7', user.nt_passwd) self.assertEquals("", user.nt_username) self.assertEquals(1125418267, user.pass_can_change_time) self.assertEquals(1125418267, user.pass_last_set_time) self.assertEquals(2125418266, user.pass_must_change_time) self.assertEquals(None, user.plaintext_passwd) self.assertEquals("\\\\BEDWYR\\root\\profile", user.profile_path) self.assertEquals(None, user.pw_history) self.assertEquals(dom_sid("S-1-5-21-2470180966-3899876309-2637894779-1000"), user.user_sid) self.assertEquals("root", user.username) self.assertEquals("", user.workstations) def test_group_length(self): grouplist = self.pdb.enum_group_mapping() self.assertEquals(13, len(grouplist)) def test_get_group(self): group = self.pdb.getgrsid(dom_sid("S-1-5-32-544")) self.assertEquals("Administrators", group.nt_name) self.assertEquals(-1, group.gid) self.assertEquals(5, group.sid_name_use) def test_groupsids(self): grouplist = self.pdb.enum_group_mapping() sids = [] for g in grouplist: sids.append(str(g.sid)) self.assertTrue("S-1-5-32-544" in sids) self.assertTrue("S-1-5-32-545" in sids) self.assertTrue("S-1-5-32-546" in sids) self.assertTrue("S-1-5-32-548" in sids) self.assertTrue("S-1-5-32-549" in sids) self.assertTrue("S-1-5-32-550" in sids) self.assertTrue("S-1-5-32-551" in sids) def test_alias_length(self): aliaslist = self.pdb.search_aliases() self.assertEquals(1, len(aliaslist)) self.assertEquals("Jelmers NT Group", aliaslist[0]['account_name']) class WinsDatabaseTestCase(TestCase): def setUp(self): super(WinsDatabaseTestCase, self).setUp() self.winsdb = WinsDatabase(os.path.join(DATADIR, "wins.dat")) def test_length(self): self.assertEquals(22, len(self.winsdb)) def test_first_entry(self): self.assertEqual((1124185120, ["192.168.1.5"], 0x64), self.winsdb["ADMINISTRATOR#03"]) def tearDown(self): self.winsdb.close() super(WinsDatabaseTestCase, self).tearDown() class IdmapDbTestCase(TestCase): def setUp(self): super(IdmapDbTestCase, self).setUp() self.idmapdb = IdmapDatabase(os.path.join(DATADIR, "winbindd_idmap.tdb")) def test_user_hwm(self): self.assertEquals(10000, self.idmapdb.get_user_hwm()) def test_group_hwm(self): self.assertEquals(10002, self.idmapdb.get_group_hwm()) def test_uids(self): self.assertEquals(1, len(list(self.idmapdb.uids()))) def test_gids(self): self.assertEquals(3, len(list(self.idmapdb.gids()))) def test_get_user_sid(self): self.assertEquals("S-1-5-21-58189338-3053988021-627566699-501", self.idmapdb.get_user_sid(65534)) def test_get_group_sid(self): self.assertEquals("S-1-5-21-2447931902-1787058256-3961074038-3007", self.idmapdb.get_group_sid(10001)) def tearDown(self): self.idmapdb.close() super(IdmapDbTestCase, self).tearDown()
espadrine/opera
refs/heads/master
chromium/src/tools/grit/grit/node/base.py
7
#!/usr/bin/env python # 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. '''Base types for nodes in a GRIT resource tree. ''' import collections import os import sys import types from xml.sax import saxutils from grit import clique from grit import exception from grit import util class Node(object): '''An item in the tree that has children.''' # Valid content types that can be returned by _ContentType() _CONTENT_TYPE_NONE = 0 # No CDATA content but may have children _CONTENT_TYPE_CDATA = 1 # Only CDATA, no children. _CONTENT_TYPE_MIXED = 2 # CDATA and children, possibly intermingled # Default nodes to not whitelist skipped _whitelist_marked_as_skip = False # A class-static cache to memoize EvaluateExpression(). # It has a 2 level nested dict structure. The outer dict has keys # of tuples which define the environment in which the expression # will be evaluated. The inner dict is map of expr->result. eval_expr_cache = collections.defaultdict(dict) def __init__(self): self.children = [] # A list of child elements self.mixed_content = [] # A list of u'' and/or child elements (this # duplicates 'children' but # is needed to preserve markup-type content). self.name = u'' # The name of this element self.attrs = {} # The set of attributes (keys to values) self.parent = None # Our parent unless we are the root element. self.uberclique = None # Allows overriding uberclique for parts of tree # This context handler allows you to write "with node:" and get a # line identifying the offending node if an exception escapes from the body # of the with statement. def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): if exc_type is not None: print u'Error processing node %s' % unicode(self) def __iter__(self): '''A preorder iteration through the tree that this node is the root of.''' return self.Preorder() def Preorder(self): '''Generator that generates first this node, then the same generator for any child nodes.''' yield self for child in self.children: for iterchild in child.Preorder(): yield iterchild def ActiveChildren(self): '''Returns the children of this node that should be included in the current configuration. Overridden by <if>.''' return [node for node in self.children if not node.WhitelistMarkedAsSkip()] def ActiveDescendants(self): '''Yields the current node and all descendants that should be included in the current configuration, in preorder.''' yield self for child in self.ActiveChildren(): for descendant in child.ActiveDescendants(): yield descendant def GetRoot(self): '''Returns the root Node in the tree this Node belongs to.''' curr = self while curr.parent: curr = curr.parent return curr # TODO(joi) Use this (currently untested) optimization?: #if hasattr(self, '_root'): # return self._root #curr = self #while curr.parent and not hasattr(curr, '_root'): # curr = curr.parent #if curr.parent: # self._root = curr._root #else: # self._root = curr #return self._root def StartParsing(self, name, parent): '''Called at the start of parsing. Args: name: u'elementname' parent: grit.node.base.Node or subclass or None ''' assert isinstance(name, types.StringTypes) assert not parent or isinstance(parent, Node) self.name = name self.parent = parent def AddChild(self, child): '''Adds a child to the list of children of this node, if it is a valid child for the node.''' assert isinstance(child, Node) if (not self._IsValidChild(child) or self._ContentType() == self._CONTENT_TYPE_CDATA): explanation = 'invalid child %s for parent %s' % (str(child), self.name) raise exception.UnexpectedChild(explanation) self.children.append(child) self.mixed_content.append(child) def RemoveChild(self, child_id): '''Removes the first node that has a "name" attribute which matches "child_id" in the list of immediate children of this node. Args: child_id: String identifying the child to be removed ''' index = 0 # Safe not to copy since we only remove the first element found for child in self.children: name_attr = child.attrs['name'] if name_attr == child_id: self.children.pop(index) self.mixed_content.pop(index) break index += 1 def AppendContent(self, content): '''Appends a chunk of text as content of this node. Args: content: u'hello' Return: None ''' assert isinstance(content, types.StringTypes) if self._ContentType() != self._CONTENT_TYPE_NONE: self.mixed_content.append(content) elif content.strip() != '': raise exception.UnexpectedContent() def HandleAttribute(self, attrib, value): '''Informs the node of an attribute that was parsed out of the GRD file for it. Args: attrib: 'name' value: 'fooblat' Return: None ''' assert isinstance(attrib, types.StringTypes) assert isinstance(value, types.StringTypes) if self._IsValidAttribute(attrib, value): self.attrs[attrib] = value else: raise exception.UnexpectedAttribute(attrib) def EndParsing(self): '''Called at the end of parsing.''' # TODO(joi) Rewrite this, it's extremely ugly! if len(self.mixed_content): if isinstance(self.mixed_content[0], types.StringTypes): # Remove leading and trailing chunks of pure whitespace. while (len(self.mixed_content) and isinstance(self.mixed_content[0], types.StringTypes) and self.mixed_content[0].strip() == ''): self.mixed_content = self.mixed_content[1:] # Strip leading and trailing whitespace from mixed content chunks # at front and back. if (len(self.mixed_content) and isinstance(self.mixed_content[0], types.StringTypes)): self.mixed_content[0] = self.mixed_content[0].lstrip() # Remove leading and trailing ''' (used to demarcate whitespace) if (len(self.mixed_content) and isinstance(self.mixed_content[0], types.StringTypes)): if self.mixed_content[0].startswith("'''"): self.mixed_content[0] = self.mixed_content[0][3:] if len(self.mixed_content): if isinstance(self.mixed_content[-1], types.StringTypes): # Same stuff all over again for the tail end. while (len(self.mixed_content) and isinstance(self.mixed_content[-1], types.StringTypes) and self.mixed_content[-1].strip() == ''): self.mixed_content = self.mixed_content[:-1] if (len(self.mixed_content) and isinstance(self.mixed_content[-1], types.StringTypes)): self.mixed_content[-1] = self.mixed_content[-1].rstrip() if (len(self.mixed_content) and isinstance(self.mixed_content[-1], types.StringTypes)): if self.mixed_content[-1].endswith("'''"): self.mixed_content[-1] = self.mixed_content[-1][:-3] # Check that all mandatory attributes are there. for node_mandatt in self.MandatoryAttributes(): mandatt_list = [] if node_mandatt.find('|') >= 0: mandatt_list = node_mandatt.split('|') else: mandatt_list.append(node_mandatt) mandatt_option_found = False for mandatt in mandatt_list: assert mandatt not in self.DefaultAttributes().keys() if mandatt in self.attrs: if not mandatt_option_found: mandatt_option_found = True else: raise exception.MutuallyExclusiveMandatoryAttribute(mandatt) if not mandatt_option_found: raise exception.MissingMandatoryAttribute(mandatt) # Add default attributes if not specified in input file. for defattr in self.DefaultAttributes(): if not defattr in self.attrs: self.attrs[defattr] = self.DefaultAttributes()[defattr] def GetCdata(self): '''Returns all CDATA of this element, concatenated into a single string. Note that this ignores any elements embedded in CDATA.''' return ''.join([c for c in self.mixed_content if isinstance(c, types.StringTypes)]) def __unicode__(self): '''Returns this node and all nodes below it as an XML document in a Unicode string.''' header = u'<?xml version="1.0" encoding="UTF-8"?>\n' return header + self.FormatXml() def FormatXml(self, indent = u'', one_line = False): '''Returns this node and all nodes below it as an XML element in a Unicode string. This differs from __unicode__ in that it does not include the <?xml> stuff at the top of the string. If one_line is true, children and CDATA are layed out in a way that preserves internal whitespace. ''' assert isinstance(indent, types.StringTypes) content_one_line = (one_line or self._ContentType() == self._CONTENT_TYPE_MIXED) inside_content = self.ContentsAsXml(indent, content_one_line) # Then the attributes for this node. attribs = u'' default_attribs = self.DefaultAttributes() for attrib, value in sorted(self.attrs.items()): # Only print an attribute if it is other than the default value. if attrib not in default_attribs or value != default_attribs[attrib]: attribs += u' %s=%s' % (attrib, saxutils.quoteattr(value)) # Finally build the XML for our node and return it if len(inside_content) > 0: if one_line: return u'<%s%s>%s</%s>' % (self.name, attribs, inside_content, self.name) elif content_one_line: return u'%s<%s%s>\n%s %s\n%s</%s>' % ( indent, self.name, attribs, indent, inside_content, indent, self.name) else: return u'%s<%s%s>\n%s\n%s</%s>' % ( indent, self.name, attribs, inside_content, indent, self.name) else: return u'%s<%s%s />' % (indent, self.name, attribs) def ContentsAsXml(self, indent, one_line): '''Returns the contents of this node (CDATA and child elements) in XML format. If 'one_line' is true, the content will be laid out on one line.''' assert isinstance(indent, types.StringTypes) # Build the contents of the element. inside_parts = [] last_item = None for mixed_item in self.mixed_content: if isinstance(mixed_item, Node): inside_parts.append(mixed_item.FormatXml(indent + u' ', one_line)) if not one_line: inside_parts.append(u'\n') else: message = mixed_item # If this is the first item and it starts with whitespace, we add # the ''' delimiter. if not last_item and message.lstrip() != message: message = u"'''" + message inside_parts.append(util.EncodeCdata(message)) last_item = mixed_item # If there are only child nodes and no cdata, there will be a spurious # trailing \n if len(inside_parts) and inside_parts[-1] == '\n': inside_parts = inside_parts[:-1] # If the last item is a string (not a node) and ends with whitespace, # we need to add the ''' delimiter. if (isinstance(last_item, types.StringTypes) and last_item.rstrip() != last_item): inside_parts[-1] = inside_parts[-1] + u"'''" return u''.join(inside_parts) def SubstituteMessages(self, substituter): '''Applies substitutions to all messages in the tree. Called as a final step of RunGatherers. Args: substituter: a grit.util.Substituter object. ''' for child in self.children: child.SubstituteMessages(substituter) def _IsValidChild(self, child): '''Returns true if 'child' is a valid child of this node. Overridden by subclasses.''' return False def _IsValidAttribute(self, name, value): '''Returns true if 'name' is the name of a valid attribute of this element and 'value' is a valid value for that attribute. Overriden by subclasses unless they have only mandatory attributes.''' return (name in self.MandatoryAttributes() or name in self.DefaultAttributes()) def _ContentType(self): '''Returns the type of content this element can have. Overridden by subclasses. The content type can be one of the _CONTENT_TYPE_XXX constants above.''' return self._CONTENT_TYPE_NONE def MandatoryAttributes(self): '''Returns a list of attribute names that are mandatory (non-optional) on the current element. One can specify a list of "mutually exclusive mandatory" attributes by specifying them as one element in the list, separated by a "|" character. ''' return [] def DefaultAttributes(self): '''Returns a dictionary of attribute names that have defaults, mapped to the default value. Overridden by subclasses.''' return {} def GetCliques(self): '''Returns all MessageClique objects belonging to this node. Overridden by subclasses. Return: [clique1, clique2] or [] ''' return [] def ToRealPath(self, path_from_basedir): '''Returns a real path (which can be absolute or relative to the current working directory), given a path that is relative to the base directory set for the GRIT input file. Args: path_from_basedir: '..' Return: 'resource' ''' return util.normpath(os.path.join(self.GetRoot().GetBaseDir(), os.path.expandvars(path_from_basedir))) def GetInputPath(self): '''Returns a path, relative to the base directory set for the grd file, that points to the file the node refers to. ''' # This implementation works for most nodes that have an input file. return self.attrs['file'] def UberClique(self): '''Returns the uberclique that should be used for messages originating in a given node. If the node itself has its uberclique set, that is what we use, otherwise we search upwards until we find one. If we do not find one even at the root node, we set the root node's uberclique to a new uberclique instance. ''' node = self while not node.uberclique and node.parent: node = node.parent if not node.uberclique: node.uberclique = clique.UberClique() return node.uberclique def IsTranslateable(self): '''Returns false if the node has contents that should not be translated, otherwise returns false (even if the node has no contents). ''' if not 'translateable' in self.attrs: return True else: return self.attrs['translateable'] == 'true' def GetNodeById(self, id): '''Returns the node in the subtree parented by this node that has a 'name' attribute matching 'id'. Returns None if no such node is found. ''' for node in self: if 'name' in node.attrs and node.attrs['name'] == id: return node return None def GetChildrenOfType(self, type): '''Returns a list of all subnodes (recursing to all leaves) of this node that are of the indicated type (or tuple of types). Args: type: A type you could use with isinstance(). Return: A list, possibly empty. ''' return [child for child in self if isinstance(child, type)] def GetTextualIds(self): '''Returns a list of the textual ids of this node. ''' if 'name' in self.attrs: return [self.attrs['name']] return [] @classmethod def EvaluateExpression(cls, expr, defs, target_platform, extra_variables=None): '''Worker for EvaluateCondition (below) and conditions in XTB files.''' cache_dict = cls.eval_expr_cache[ (tuple(defs.iteritems()), target_platform, extra_variables)] if expr in cache_dict: return cache_dict[expr] def pp_ifdef(symbol): return symbol in defs def pp_if(symbol): return defs.get(symbol, False) variable_map = { 'defs' : defs, 'os': target_platform, 'is_linux': target_platform.startswith('linux'), 'is_macosx': target_platform == 'darwin', 'is_win': target_platform in ('cygwin', 'win32'), 'is_android': target_platform == 'android', 'is_ios': target_platform == 'ios', 'is_posix': (target_platform in ('darwin', 'linux2', 'linux3', 'sunos5', 'android', 'ios') or 'bsd' in target_platform), 'pp_ifdef' : pp_ifdef, 'pp_if' : pp_if, } if extra_variables: variable_map.update(extra_variables) eval_result = cache_dict[expr] = eval(expr, {}, variable_map) return eval_result def EvaluateCondition(self, expr): '''Returns true if and only if the Python expression 'expr' evaluates to true. The expression is given a few local variables: - 'lang' is the language currently being output (the 'lang' attribute of the <output> element). - 'context' is the current output context (the 'context' attribute of the <output> element). - 'defs' is a map of C preprocessor-style symbol names to their values. - 'os' is the current platform (likely 'linux2', 'win32' or 'darwin'). - 'pp_ifdef(symbol)' is a shorthand for "symbol in defs". - 'pp_if(symbol)' is a shorthand for "symbol in defs and defs[symbol]". - 'is_linux', 'is_macosx', 'is_win', 'is_posix' are true if 'os' matches the given platform. ''' root = self.GetRoot() lang = getattr(root, 'output_language', '') context = getattr(root, 'output_context', '') defs = getattr(root, 'defines', {}) target_platform = getattr(root, 'target_platform', '') extra_variables = ( ('lang', lang), ('context', context), ) return Node.EvaluateExpression( expr, defs, target_platform, extra_variables) def OnlyTheseTranslations(self, languages): '''Turns off loading of translations for languages not in the provided list. Attrs: languages: ['fr', 'zh_cn'] ''' for node in self: if (hasattr(node, 'IsTranslation') and node.IsTranslation() and node.GetLang() not in languages): node.DisableLoading() def FindBooleanAttribute(self, attr, default, skip_self): '''Searches all ancestors of the current node for the nearest enclosing definition of the given boolean attribute. Args: attr: 'fallback_to_english' default: What to return if no node defines the attribute. skip_self: Don't check the current node, only its parents. ''' p = self.parent if skip_self else self while p: value = p.attrs.get(attr, 'default').lower() if value != 'default': return (value == 'true') p = p.parent return default def PseudoIsAllowed(self): '''Returns true if this node is allowed to use pseudo-translations. This is true by default, unless this node is within a <release> node that has the allow_pseudo attribute set to false. ''' return self.FindBooleanAttribute('allow_pseudo', default=True, skip_self=True) def ShouldFallbackToEnglish(self): '''Returns true iff this node should fall back to English when pseudotranslations are disabled and no translation is available for a given message. ''' return self.FindBooleanAttribute('fallback_to_english', default=False, skip_self=True) def WhitelistMarkedAsSkip(self): '''Returns true if the node is marked to be skipped in the output by a whitelist. ''' return self._whitelist_marked_as_skip def SetWhitelistMarkedAsSkip(self, mark_skipped): '''Sets WhitelistMarkedAsSkip. ''' self._whitelist_marked_as_skip = mark_skipped def ExpandVariables(self): '''Whether we need to expand variables on a given node.''' return False class ContentNode(Node): '''Convenience baseclass for nodes that can have content.''' def _ContentType(self): return self._CONTENT_TYPE_MIXED
jakirkham/ilastik
refs/heads/master
bin/downsample_pointcloud.py
3
import sys import os import csv import numpy import logging logger = logging.getLogger(__name__) # NOTE: This file depends on numpy.add.at(), which requires numpy v1.8.0 def downsample_pointcloud( pointcloud_csv_filepath, output_filepath, scale_xyz=None, offset_xyz=None, volume_shape_xyz=None, method='by_count', smoothing_sigma_xyz=None, normalize_with_max=None, output_dtype=None ): """ Generate an intensity image volume from the given pointcloud file as described in density_volume_from_pointcloud(), below. Write the resulting volume to either hdf5 or tiff. Optionally, perform gaussian smoothing on the downsampled volume before it is saved to disk. pointcloud_csv_filepath: The input pointcloud csv file. output_filepath: The path to store the output image volume. Either .h5 or .tif smoothing_sigma_xyz: A float or tuple to use with vigra.filters.gaussianSmoothing, in XYZ order. normalize_with_max: If provided, renormalize the intensities with the given max value output_dtype: If provided, convert the image to the given dtype before export other parameters: See density_volume_from_pointcloud(), below. """ density_volume_zyx = density_volume_from_pointcloud( pointcloud_csv_filepath, scale_xyz, offset_xyz, volume_shape_xyz, method ) if smoothing_sigma_xyz: logger.debug("Smoothing with sigma: {}".format( smoothing_sigma_xyz )) import vigra smoothing_sigma_zyx = smoothing_sigma_xyz[::-1] density_volume_zyx = numpy.asarray( density_volume_zyx, numpy.float32 ) density_volume_zyx = vigra.taggedView(density_volume_zyx, 'zyx') vigra.filters.gaussianSmoothing( density_volume_zyx, smoothing_sigma_zyx, out=density_volume_zyx ) if normalize_with_max: logger.debug("Normalizing with max: {}".format( normalize_with_max )) max_px = density_volume_zyx.max() if max_px > 0: density_volume_zyx[:] *= normalize_with_max / max_px if output_dtype: logger.debug("Converting to dtype: {}".format( str(output_dtype().dtype) )) density_volume_zyx = numpy.asarray( density_volume_zyx, dtype=output_dtype ) # Now write the volume to the output file output_ext = os.path.splitext(output_filepath)[1] if output_ext == '.h5': export_hdf5( density_volume_zyx, output_filepath, 'downsampled_density' ) elif output_ext == '.tif' or output_ext == '.tiff': export_tiff( density_volume_zyx, output_filepath ) logger.debug("FINISHED downsampling pointcloud.") def density_volume_from_pointcloud( pointcloud_csv_filepath, scale_xyz=None, offset_xyz=None, volume_shape_xyz=None, method='by_count' ): """ Read the given pointcloud file and generate a downsampled intensity volume according to how many points fall within each downsampled pixel. Optionally, also weight the intensity of each downsampled pixel according to the size of each point. NOTE: This function depends on numpy.add.at(), which requires numpy v1.8.0 pointcloud_csv_filepath: The input pointcloud file. Must include scale_xyz: (optional) The downsampling factor, specified as a tuple in XYZ order, e.g. (10,10,1). If not provided, (1,1,1) is assumed. offset_xyz: (optional) Will be subtracted from all coordinates before downsampling. If not provided, the output will be shifted according to the bounding box of the pointcloud data. volume_shape_xyz: (optional) Sets the size of the output volume. If not provided, the output shape will be set according to the bounding box of the pointcloud data. method: One of the following: - 'binary': Produce a binary image. No scaling for downsampled voxels containing more than one detection. - 'by_count': Each downsampled voxel represents the count of points contained within it. - 'by_size': Weight the intensity of each downsampled voxel according to the size of each point (via the size_px column). """ # Load csv data pointcloud_data = array_from_csv( pointcloud_csv_filepath, DEFAULT_CSV_FORMAT, numpy.uint32 ) POINTCLOUD_COLUMNS = ["x_px", "y_px", "z_px", "size_px", "min_x_px", "min_y_px", "min_z_px", "max_x_px", "max_y_px", "max_z_px"] expected_columns = set(POINTCLOUD_COLUMNS) data_columns = set(pointcloud_data.dtype.fields.keys()) assert expected_columns.issubset( data_columns ), \ "Your pointcloud data file does not contain all expected columns.\n"\ "Expected columns: {},\n"\ "Your file's columns: {}"\ .format( POINTCLOUD_COLUMNS, pointcloud_data.dtype.fields.keys() ) # Determine offset if not provided. if not offset_xyz: offset_xyz = ( pointcloud_data['x_px'].min(), pointcloud_data['y_px'].min(), pointcloud_data['z_px'].min() ) # Apply offset logger.debug("Subtracting offset: {}".format( offset_xyz )) for axis, axis_offset in zip('xyz', offset_xyz): fields = [ '{}_px'.format(axis), 'min_{}_px'.format(axis), 'max_{}_px'.format(axis) ] for field in fields: pointcloud_data[field] -= axis_offset # Determine volume shape if not provided. if not volume_shape_xyz: volume_shape_xyz = ( pointcloud_data['x_px'].max(), pointcloud_data['y_px'].max(), pointcloud_data['z_px'].max() ) volume_shape_xyz = 1 + numpy.array(volume_shape_xyz) volume_shape_xyz = tuple(volume_shape_xyz) logger.debug("Assuming original volume shape: {}".format(volume_shape_xyz)) # Apply scale if not scale_xyz: logger.debug("No scale provided. Rendering at full scale.") scaled_volume_shape_xyz = volume_shape_xyz else: logger.debug("Dividing by scale: {}".format( scale_xyz )) scaled_volume_shape_xyz = (numpy.array(volume_shape_xyz) + scale_xyz-1) / scale_xyz # Scale coordinates, too. for axis, axis_scale in zip('xyz', scale_xyz): fields = [ '{}_px'.format(axis), 'min_{}_px'.format(axis), 'max_{}_px'.format(axis) ] for field in fields: pointcloud_data[field] /= axis_scale # All coords coordinates_zyx = ( pointcloud_data['z_px'], pointcloud_data['y_px'], pointcloud_data['x_px'] ) if method == 'binary': scaled_volume_shape_zyx = tuple(scaled_volume_shape_xyz[::-1]) logger.debug("Initializing binary volume of zyx shape: {}".format( scaled_volume_shape_zyx )) density_volume_zyx = numpy.zeros( scaled_volume_shape_zyx, dtype=numpy.uint8 ) density_volume_zyx[coordinates_zyx] = 1 else: # Prepare weights if method == 'by_size': weights = pointcloud_data['size_px'] elif method == 'by_count': weights = 1 else: assert False, "Unknown method: {}".format( method ) # Initialize volume scaled_volume_shape_zyx = tuple(scaled_volume_shape_xyz[::-1]) logger.debug("Initializing volume of zyx shape: {}".format( scaled_volume_shape_zyx )) density_volume_zyx = numpy.zeros( scaled_volume_shape_zyx, dtype=numpy.float32 ) # We can't just use the following: # density_volume_zyx[coordinates_zyx] = weights # Because that wouldn't correctly handle multiple rows with identical coordinates # (the multiple rows wouldn't both be counted). # Instead, we must use an "unbuffered" (accumulated) operation: logger.debug("Accumulating densities...") numpy.add.at( density_volume_zyx, coordinates_zyx, weights ) return density_volume_zyx DEFAULT_CSV_FORMAT = { 'delimiter' : '\t', 'lineterminator' : '\n' } def array_from_csv( pointcloud_csv_filepath, csv_format=DEFAULT_CSV_FORMAT, column_dtypes=None, weight_by_size=False, use_cache=True): """ Read the given csv file and return a corresponding numpy structured array of all its values. The CSV file must include a header row. pointcloud_csv_filepath: The input file csv_format: A dict of formatting parameters for the csv module column_dtypes: Either: - a dtype object to use for all columns, or - a dict of {column_name : dtype} to use for each column weight_by_size: If True, weight the intensity of each downsampled pixel according to the size_px of the objects that it represents. use_cache: If True, attempt to use a cached copy of the imported csv data, already in .npy format. Provide a string instead of a bool to specify the location of the cache file. If the cache file can't be found, it will be created after csv import is complete. """ cache_path = pointcloud_csv_filepath + ".cache.npy" if use_cache: if isinstance(use_cache, (str, unicode)): cache_path = use_cache if os.path.exists(cache_path): if os.path.getmtime(cache_path) > os.path.getmtime(pointcloud_csv_filepath): logger.info("Loading data from cache file: {}".format( cache_path )) return numpy.load(cache_path) # Quick first pass to get the number of points # (-1 for header) num_points = countlines(pointcloud_csv_filepath) - 1 logger.debug("Loading data from csv file: {}".format( pointcloud_csv_filepath )) with open(pointcloud_csv_filepath, 'r') as f_in: csv_reader = csv.reader(f_in, **csv_format) column_names = csv_reader.next() # If user provided only a single dtype, it is the default type. if isinstance(column_dtypes, dict): default_column_dtype = numpy.float32 else: if column_dtypes is not None: default_column_dtype = column_dtypes column_dtypes = {} if not column_dtypes: column_dtypes = {} for column_name in column_names: if column_name not in column_dtypes: column_dtypes[column_name] = default_column_dtype dtype_list = [column_dtypes[column_name] for column_name in column_names] row_dtype = zip( column_names, dtype_list ) csv_array_data = numpy.ndarray( shape=(num_points,), dtype=row_dtype ) for row_index, row_data in enumerate(csv_reader): csv_array_data[row_index] = tuple(int(x) for x in row_data) if use_cache: logger.info("Saving data to cache file: {}".format( cache_path )) numpy.save(cache_path, csv_array_data) return csv_array_data def countlines(file_path): """ Return the number of lines in the given file. """ line_count = 0 with open(file_path, 'r') as f: for _ in f: line_count += 1 return line_count def export_hdf5( density_volume_zyx, output_filepath, dset_name ): """ Export the given 3D zyx volume to HDF5. density_volume_zyx: The volume to export. Must be in ZYX order. output_filepath: The file to (over)write. dset_name: The HDF5 dataset name to use. """ import h5py logger.debug("Writing output to: {}/{}".format( output_filepath, dset_name )) with h5py.File(output_filepath, 'w') as f_out: dset = f_out.create_dataset( dset_name, density_volume_zyx.shape, density_volume_zyx.dtype, chunks=True ) dset[:] = density_volume_zyx # Try to provide axistags on the volume if possible. try: import vigra dset.attrs["axistags"] = vigra.defaultAxistags( "zyx" ).toJSON() except ImportError: pass def export_tiff( density_volume_zyx, output_filepath ): """ Export the given 3D zyx volume as a multipage TIFF. density_volume_zyx: The volume to export. Must be in ZYX order. output_filepath: The name of the .tiff file to write. """ assert os.path.splitext(output_filepath)[1] in ['.tif', '.tiff'], \ "Wrong extension for TIFF export: {}".format( output_filepath ) import vigra density_volume_zyx = vigra.taggedView(density_volume_zyx, "zyx") logger.debug( "Writing output to multipage tiff: {}".format(output_filepath) ) if os.path.exists( output_filepath ): os.remove( output_filepath ) for z_slice in density_volume_zyx: vigra.impex.writeImage( z_slice, output_filepath, dtype='', compression='', mode='a' ) if __name__ == "__main__": # When executing from cmdline, print all logging output logger.addHandler( logging.StreamHandler(sys.stdout) ) logger.setLevel(logging.DEBUG) # Define cmd-line API import argparse parser = argparse.ArgumentParser() parser.add_argument("--method", choices=['binary', 'by_count', 'by_size'], default='by_count', help="The method by which points will be accumulated into the downsampled volume.") parser.add_argument("--smooth_with_sigma_xyz", required=False) parser.add_argument("--normalize_with_max", required=False) parser.add_argument("--output_dtype", required=False) parser.add_argument("pointcloud_csv_filepath") parser.add_argument("output_filepath", help="Path to .h5 or .tiff file to (over)write.") parser.add_argument("scale_xyz", nargs='?', default=None, help="Scale to divide all coordinates by (after offset), e.g. 1000.0 or [100, 100, 1.1]") # These parameters aren't usually needed... parser.add_argument("offset_xyz", nargs='?', default=None, help="Offset to remove from all point coordinates before processing, e.g. 10.0 or [7.1, 8, 0]") parser.add_argument("volume_shape_xyz", nargs='?', default=None, help="Full shape of the original volume. If not provided, use bounding box of the pointcloud.") # Here's some default cmd-line args for debugging... DEBUG = False if DEBUG: sys.argv += ["--method=binary", #"--smooth_with_sigma_xyz=(3.0, 3.0, 3.0)", "--normalize_with_max=255", "--output_dtype=uint8", "../pointclouds/bock-863-pointcloud-20141203.csv", "../pointclouds/bock-863-pointcloud-20141203.tif", "(100, 100, 10)"] # Parse! parsed_args = parser.parse_args() # Evaluate tuple args if provided volume_shape_xyz = parsed_args.volume_shape_xyz and eval(parsed_args.volume_shape_xyz) offset_xyz = parsed_args.offset_xyz and eval(parsed_args.offset_xyz) scale_xyz = parsed_args.scale_xyz and eval(parsed_args.scale_xyz) smoothing_sigma_xyz = parsed_args.smooth_with_sigma_xyz and eval(parsed_args.smooth_with_sigma_xyz) # Evaluate other optional args output_dtype = None if parsed_args.output_dtype: assert parsed_args.output_dtype in \ [ 'uint8', 'int8', 'uint16', 'int16', 'uint32', 'int32', 'uint64', 'int64', 'float32', 'float64' ], \ "Unknown dtype: {}".format( parsed_args.output_dtype ) output_dtype = eval( "numpy." + parsed_args.output_dtype ) normalize_with_max = parsed_args.normalize_with_max and eval(parsed_args.normalize_with_max) # Main func. sys.exit( downsample_pointcloud( parsed_args.pointcloud_csv_filepath, parsed_args.output_filepath, scale_xyz, offset_xyz, volume_shape_xyz, parsed_args.method, smoothing_sigma_xyz, normalize_with_max, output_dtype ) )
franosincic/edx-platform
refs/heads/master
common/djangoapps/track/views/segmentio.py
40
"""Handle events that were forwarded from the Segment webhook integration""" import datetime import json import logging from django.conf import settings from django.contrib.auth.models import User from django.http import HttpResponse from django.views.decorators.http import require_POST from django.views.decorators.csrf import csrf_exempt from eventtracking import tracker from opaque_keys.edx.keys import CourseKey from opaque_keys import InvalidKeyError from util.json_request import expect_json log = logging.getLogger(__name__) ERROR_UNAUTHORIZED = 'Unauthorized' WARNING_IGNORED_SOURCE = 'Source ignored' WARNING_IGNORED_TYPE = 'Type ignored' ERROR_MISSING_USER_ID = 'Required user_id missing from context' ERROR_USER_NOT_EXIST = 'Specified user does not exist' ERROR_INVALID_USER_ID = 'Unable to parse userId as an integer' ERROR_MISSING_DATA = 'The data field must be specified in the properties dictionary' ERROR_MISSING_NAME = 'The name field must be specified in the properties dictionary' ERROR_MISSING_TIMESTAMP = 'Required timestamp field not found' ERROR_MISSING_RECEIVED_AT = 'Required receivedAt field not found' @require_POST @expect_json @csrf_exempt def segmentio_event(request): """ An endpoint for logging events using Segment's webhook integration. Segment provides a custom integration mechanism that initiates a request to a configurable URL every time an event is received by their system. This endpoint is designed to receive those requests and convert the events into standard tracking log entries. For now we limit the scope of handled events to track and screen events from mobile devices. In the future we could enable logging of other types of events, however, there is significant overlap with our non-Segment based event tracking. Given that Segment is closed third party solution we are limiting its required usage to just collecting events from mobile devices for the time being. Many of the root fields of a standard edX tracking event are read out of the "properties" dictionary provided by the Segment event, which is, in turn, provided by the client that emitted the event. In order for an event to be accepted and logged the "key" query string parameter must exactly match the django setting TRACKING_SEGMENTIO_WEBHOOK_SECRET. While the endpoint is public, we want to limit access to it to the Segment servers only. """ # Validate the security token. We must use a query string parameter for this since we cannot customize the POST body # in the Segment webhook configuration, we can only change the URL that they call, so we force this token to be # included in the URL and reject any requests that do not include it. This also assumes HTTPS is used to make the # connection between their server and ours. expected_secret = getattr(settings, 'TRACKING_SEGMENTIO_WEBHOOK_SECRET', None) provided_secret = request.GET.get('key') if not expected_secret or provided_secret != expected_secret: return HttpResponse(status=401) try: track_segmentio_event(request) except EventValidationError as err: log.warning( 'Unable to process event received from Segment: message="%s" event="%s"', str(err), request.body ) # Do not let the requestor know why the event wasn't saved. If the secret key is compromised this diagnostic # information could be used to scrape useful information from the system. return HttpResponse(status=200) class EventValidationError(Exception): """Raised when an invalid event is received.""" pass def track_segmentio_event(request): # pylint: disable=too-many-statements """ Record an event received from Segment to the tracking logs. This method assumes that the event has come from a trusted source. The received event must meet the following conditions in order to be logged: * The value of the "type" field of the event must be included in the list specified by the django setting TRACKING_SEGMENTIO_ALLOWED_TYPES. In order to make use of *all* of the features Segment offers we would have to implement some sort of persistent storage of information contained in some actions (like identify). For now, we defer support of those actions and just support a limited set that can be handled without storing information in external state. * The value of the standard "userId" field of the event must be an integer that can be used to look up the user using the primary key of the User model. * Include a "name" field in the properties dictionary that indicates the edX event name. Note this can differ from the "event" field found in the root of a Segment event. The "event" field at the root of the structure is intended to be human readable, the "name" field is expected to conform to the standard for naming events found in the edX data documentation. * Have originated from a known and trusted Segment client library. The django setting TRACKING_SEGMENTIO_SOURCE_MAP maps the known library names to internal "event_source" strings. In order to be logged the event must have a library name that is a valid key in that map. Additionally the event can optionally: * Provide a "context" dictionary in the properties dictionary. This dictionary will be applied to the existing context on the server overriding any existing keys. This context dictionary should include a "course_id" field when the event is scoped to a particular course. The value of this field should be a valid course key. The context may contain other arbitrary data that will be logged with the event, for example: identification information for the device that emitted the event. """ # The POST body will contain the JSON encoded event full_segment_event = request.json # We mostly care about the properties segment_properties = full_segment_event.get('properties', {}) # Start with the context provided by Segment in the "client" field if it exists # We should tightly control which fields actually get included in the event emitted. segment_context = full_segment_event.get('context') # Build up the event context by parsing fields out of the event received from Segment context = {} library_name = segment_context.get('library', {}).get('name') source_map = getattr(settings, 'TRACKING_SEGMENTIO_SOURCE_MAP', {}) event_source = source_map.get(library_name) if not event_source: raise EventValidationError(WARNING_IGNORED_SOURCE) else: context['event_source'] = event_source if 'name' not in segment_properties: raise EventValidationError(ERROR_MISSING_NAME) if 'data' not in segment_properties: raise EventValidationError(ERROR_MISSING_DATA) # Ignore event types and names that are unsupported segment_event_type = full_segment_event.get('type') segment_event_name = segment_properties['name'] allowed_types = [a.lower() for a in getattr(settings, 'TRACKING_SEGMENTIO_ALLOWED_TYPES', [])] disallowed_substring_names = [ a.lower() for a in getattr(settings, 'TRACKING_SEGMENTIO_DISALLOWED_SUBSTRING_NAMES', []) ] if ( not segment_event_type or (segment_event_type.lower() not in allowed_types) or any(disallowed_subs_name in segment_event_name.lower() for disallowed_subs_name in disallowed_substring_names) ): raise EventValidationError(WARNING_IGNORED_TYPE) # create and populate application field if it doesn't exist app_context = segment_properties.get('context', {}) if 'application' not in app_context: context['application'] = { 'name': app_context.get('app_name', ''), 'version': '' if not segment_context else segment_context.get('app', {}).get('version', '') } app_context.pop('app_name', None) if segment_context: # copy the entire segment's context dict as a sub-field of our custom context dict context['client'] = dict(segment_context) context['agent'] = segment_context.get('userAgent', '') # remove duplicate and unnecessary fields from our copy for field in ('traits', 'integrations', 'userAgent'): if field in context['client']: del context['client'][field] # Overlay any context provided in the properties context.update(app_context) user_id = full_segment_event.get('userId') if not user_id: raise EventValidationError(ERROR_MISSING_USER_ID) # userId is assumed to be the primary key of the django User model try: user = User.objects.get(pk=user_id) except User.DoesNotExist: raise EventValidationError(ERROR_USER_NOT_EXIST) except ValueError: raise EventValidationError(ERROR_INVALID_USER_ID) else: context['user_id'] = user.id context['username'] = user.username # course_id is expected to be provided in the context when applicable course_id = context.get('course_id') if course_id: try: course_key = CourseKey.from_string(course_id) context['org_id'] = course_key.org except InvalidKeyError: log.warning( 'unable to parse course_id "{course_id}" from event: {event}'.format( course_id=course_id, event=json.dumps(full_segment_event), ), exc_info=True ) if 'timestamp' in full_segment_event: context['timestamp'] = parse_iso8601_timestamp(full_segment_event['timestamp']) else: raise EventValidationError(ERROR_MISSING_TIMESTAMP) if 'receivedAt' in full_segment_event: context['received_at'] = parse_iso8601_timestamp(full_segment_event['receivedAt']) else: raise EventValidationError(ERROR_MISSING_RECEIVED_AT) context['ip'] = segment_properties.get('context', {}).get('ip', '') with tracker.get_tracker().context('edx.segmentio', context): tracker.emit(segment_event_name, segment_properties.get('data', {})) def parse_iso8601_timestamp(timestamp): """Parse a particular type of ISO8601 formatted timestamp""" return datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%fZ")
MortimerGoro/servo
refs/heads/master
tests/wpt/css-tests/tools/gitignore/tests/__init__.py
12133432
dhoffman34/django
refs/heads/master
tests/admin_validation/__init__.py
12133432
DiptoDas8/Biponi
refs/heads/master
lib/python2.7/site-packages/django/contrib/humanize/templatetags/__init__.py
12133432
rrrene/django
refs/heads/master
tests/select_related_regress/__init__.py
12133432
gwiedeman/eadmachine
refs/heads/master
source/EADtoSpreadsheet/__init__.py
12133432
elysium001/zamboni
refs/heads/master
mkt/users/tests/__init__.py
12133432
ic-labs/django-icekit
refs/heads/develop
icekit/utils/__init__.py
12133432
ruslanloman/nova
refs/heads/master
nova/tests/unit/api/openstack/compute/contrib/__init__.py
12133432
okwow123/djangol2
refs/heads/master
allauth/socialaccount/providers/persona/models.py
12133432