repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
masterandrey/masterandrey.com
refs/heads/master
_includes/src/asyncio_multiprocessing.py
1
import asyncio import subprocess import random semaphore = asyncio.Queue(maxsize=3-1) # Max 3 processes async def worker(id): """ We could use more straightforward consumer-producer pattern: * producer puts tasks into the queue * worker waits for tasks in the queue But for this tiny code sniped that would produce too much boilerplates. """ delay = random.random() print('>'*5, f'task {id} starts with delay {delay:.1} seconds') process = await asyncio.create_subprocess_exec( 'sleep', str(delay), stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) (output, err) = await process.communicate() status = await process.wait() print('<'*5, f'task {id} finished with status {status}') print(f'Stdout: {output}, Stderr: {err}') await semaphore.get() async def main(loop): for task_id in range(6): await semaphore.put(task_id) # It does'n matter what we put in the queue. We use it as semaphore. loop.create_task(worker(task_id)) # all the tasks are scheduled at the moment but not all done loop = asyncio.get_event_loop() loop.run_until_complete(main(loop)) loop.run_until_complete(asyncio.gather(*asyncio.Task.all_tasks())) # Wait for all tasks in the loop.
zdszxp/gamesrc
refs/heads/master
Trdlib/src/boost_1_60_0/libs/mpl/doc/src/refmanual/refmanual.py
59
# Copyright (c) Aleksey Gurtovoy 2001-2009 # # 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 fnmatch import os import sys import re import string underlines = ['+', '/'] special_cases = [ 'inserter', '_1,_2,..._n' ] def __section_header(section): parts = section.split('/') underline = underlines[len(parts) - 1] * len(parts[-1]) if len(parts) > 0: hidden_target = '.. _`label-%s`:' % '-'.join( parts ) return '\n%s\n%s\n%s\n\n' % (parts[-1], underline, hidden_target ) else: return '\n%s\n%s\n\n' % (parts[-1], underline ) def __section_intro(section): parts = section.split('/') return '%s.rst' % '-'.join( [x.split(' ')[0] for x in parts] ) def __include_page( output, src_dir, page, name = None ): output.write( '.. include:: %s\n' % os.path.join( src_dir, page ) ) # output.write( '.. raw:: LaTeX\n\n' ) # output.write( ' \\newpage\n\n') if name and name not in special_cases: ref = name else: ref = '/'.join( page.split('.')[0].split('-') ) if ref.upper() == ref or ref.lower() == ref: output.write( ( '.. |%(ref)s| replace:: `%(ref)s`_\n' ) % { 'ref': ref } ) else: if ref.find( '/' ) == -1: ref = ' '.join( filter( lambda x: len( x.strip() ) > 0, re.split( '([A-Z][a-z]+)', ref ) ) ) output.write( '.. |%(ref)s| replace:: `%(ref)s`_\n' % { 'ref': ref } ) output.write( '\n' ) def __write_index( filename, index ): index_file = open( filename, 'w' ) index.sort() for x in index: index_file.write( '* |%s|\n' % x ) index_file.close() def main( filename, src_dir, build_dir ): sources = filter( lambda x: fnmatch.fnmatch(x,"*.rst") and x != filename , os.listdir( src_dir ) ) toc = [ t.strip() for t in open( os.path.join( src_dir, '%s.toc' % filename) ).readlines() ] topics = {} for t in toc: topics[t] = [] concept_index = [] index = [] output = open( os.path.join( build_dir, '%s.gen' % filename ), 'w') output.writelines( open( os.path.join( src_dir, '%s.rst' % filename ), 'r' ).readlines() ) re_topic = re.compile(r'^..\s+(.+?)//(.+?)(\s*\|\s*(\d+))?\s*$') for src in sources: placement_spec = open( os.path.join( src_dir, src ), 'r' ).readline() topic = 'Unclassified' name = None order = -1 match = re_topic.match(placement_spec) if match: topic = match.group(1) name = match.group(2) if match.group(3): order = int(match.group(4)) if not topics.has_key(topic): topics[topic] = [] topics[topic].append((src, order, name)) if name: if topic.find( '/Concepts' ) == -1: index.append( name ) else: concept_index.append( name ) for t in toc: content = topics[t] content.sort( lambda x,y: x[1] - y[1] ) output.write( __section_header(t) ) intro = __section_intro( t ) if os.path.exists( os.path.join( src_dir, intro ) ): __include_page( output, src_dir, intro ) for src in content: __include_page( output, src_dir, src[0], src[2] ) output.close() __write_index( os.path.join( build_dir, 'concepts.gen' ), concept_index ) __write_index( os.path.join( build_dir, 'index.gen' ), index ) main( 'refmanual', os.path.dirname( __file__ ), sys.argv[1] )
rovanleeuwen/informant
refs/heads/master
informant/__init__.py
1
import gettext #: Version information (major, minor, revision[, 'dev']). version_info = (0, 0, 2) #: Version string 'major.minor.revision'. version = __version__ = ".".join(map(str, version_info)) gettext.install('informant')
Sazzadmasud/Keystone_hash_token
refs/heads/master
keystone/openstack/common/processutils.py
7
# Copyright 2011 OpenStack Foundation. # 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. """ System-level utilities and helper functions. """ import logging as stdlib_logging import os import random import shlex import signal from eventlet.green import subprocess from eventlet import greenthread from keystone.openstack.common.gettextutils import _ # noqa from keystone.openstack.common import log as logging LOG = logging.getLogger(__name__) class InvalidArgumentError(Exception): def __init__(self, message=None): super(InvalidArgumentError, self).__init__(message) class UnknownArgumentError(Exception): def __init__(self, message=None): super(UnknownArgumentError, self).__init__(message) class ProcessExecutionError(Exception): def __init__(self, stdout=None, stderr=None, exit_code=None, cmd=None, description=None): self.exit_code = exit_code self.stderr = stderr self.stdout = stdout self.cmd = cmd self.description = description if description is None: description = "Unexpected error while running command." if exit_code is None: exit_code = '-' message = ("%s\nCommand: %s\nExit code: %s\nStdout: %r\nStderr: %r" % (description, cmd, exit_code, stdout, stderr)) super(ProcessExecutionError, self).__init__(message) class NoRootWrapSpecified(Exception): def __init__(self, message=None): super(NoRootWrapSpecified, self).__init__(message) def _subprocess_setup(): # Python installs a SIGPIPE handler by default. This is usually not what # non-Python subprocesses expect. signal.signal(signal.SIGPIPE, signal.SIG_DFL) def execute(*cmd, **kwargs): """Helper method to shell out and execute a command through subprocess. Allows optional retry. :param cmd: Passed to subprocess.Popen. :type cmd: string :param process_input: Send to opened process. :type proces_input: string :param check_exit_code: Single bool, int, or list of allowed exit codes. Defaults to [0]. Raise :class:`ProcessExecutionError` unless program exits with one of these code. :type check_exit_code: boolean, int, or [int] :param delay_on_retry: True | False. Defaults to True. If set to True, wait a short amount of time before retrying. :type delay_on_retry: boolean :param attempts: How many times to retry cmd. :type attempts: int :param run_as_root: True | False. Defaults to False. If set to True, the command is prefixed by the command specified in the root_helper kwarg. :type run_as_root: boolean :param root_helper: command to prefix to commands called with run_as_root=True :type root_helper: string :param shell: whether or not there should be a shell used to execute this command. Defaults to false. :type shell: boolean :param loglevel: log level for execute commands. :type loglevel: int. (Should be stdlib_logging.DEBUG or stdlib_logging.INFO) :returns: (stdout, stderr) from process execution :raises: :class:`UnknownArgumentError` on receiving unknown arguments :raises: :class:`ProcessExecutionError` """ process_input = kwargs.pop('process_input', None) check_exit_code = kwargs.pop('check_exit_code', [0]) ignore_exit_code = False delay_on_retry = kwargs.pop('delay_on_retry', True) attempts = kwargs.pop('attempts', 1) run_as_root = kwargs.pop('run_as_root', False) root_helper = kwargs.pop('root_helper', '') shell = kwargs.pop('shell', False) loglevel = kwargs.pop('loglevel', stdlib_logging.DEBUG) if isinstance(check_exit_code, bool): ignore_exit_code = not check_exit_code check_exit_code = [0] elif isinstance(check_exit_code, int): check_exit_code = [check_exit_code] if kwargs: raise UnknownArgumentError(_('Got unknown keyword args ' 'to utils.execute: %r') % kwargs) if run_as_root and hasattr(os, 'geteuid') and os.geteuid() != 0: if not root_helper: raise NoRootWrapSpecified( message=('Command requested root, but did not specify a root ' 'helper.')) cmd = shlex.split(root_helper) + list(cmd) cmd = map(str, cmd) while attempts > 0: attempts -= 1 try: LOG.log(loglevel, _('Running cmd (subprocess): %s'), ' '.join(cmd)) _PIPE = subprocess.PIPE # pylint: disable=E1101 if os.name == 'nt': preexec_fn = None close_fds = False else: preexec_fn = _subprocess_setup close_fds = True obj = subprocess.Popen(cmd, stdin=_PIPE, stdout=_PIPE, stderr=_PIPE, close_fds=close_fds, preexec_fn=preexec_fn, shell=shell) result = None if process_input is not None: result = obj.communicate(process_input) else: result = obj.communicate() obj.stdin.close() # pylint: disable=E1101 _returncode = obj.returncode # pylint: disable=E1101 LOG.log(loglevel, _('Result was %s') % _returncode) if not ignore_exit_code and _returncode not in check_exit_code: (stdout, stderr) = result raise ProcessExecutionError(exit_code=_returncode, stdout=stdout, stderr=stderr, cmd=' '.join(cmd)) return result except ProcessExecutionError: if not attempts: raise else: LOG.log(loglevel, _('%r failed. Retrying.'), cmd) if delay_on_retry: greenthread.sleep(random.randint(20, 200) / 100.0) finally: # NOTE(termie): this appears to be necessary to let the subprocess # call clean something up in between calls, without # it two execute calls in a row hangs the second one greenthread.sleep(0) def trycmd(*args, **kwargs): """A wrapper around execute() to more easily handle warnings and errors. Returns an (out, err) tuple of strings containing the output of the command's stdout and stderr. If 'err' is not empty then the command can be considered to have failed. :discard_warnings True | False. Defaults to False. If set to True, then for succeeding commands, stderr is cleared """ discard_warnings = kwargs.pop('discard_warnings', False) try: out, err = execute(*args, **kwargs) failed = False except ProcessExecutionError as exn: out, err = '', str(exn) failed = True if not failed and discard_warnings and err: # Handle commands that output to stderr but otherwise succeed err = '' return out, err def ssh_execute(ssh, cmd, process_input=None, addl_env=None, check_exit_code=True): LOG.debug(_('Running cmd (SSH): %s'), cmd) if addl_env: raise InvalidArgumentError(_('Environment not supported over SSH')) if process_input: # This is (probably) fixable if we need it... raise InvalidArgumentError(_('process_input not supported over SSH')) stdin_stream, stdout_stream, stderr_stream = ssh.exec_command(cmd) channel = stdout_stream.channel # NOTE(justinsb): This seems suspicious... # ...other SSH clients have buffering issues with this approach stdout = stdout_stream.read() stderr = stderr_stream.read() stdin_stream.close() exit_status = channel.recv_exit_status() # exit_status == -1 if no exit code was returned if exit_status != -1: LOG.debug(_('Result was %s') % exit_status) if check_exit_code and exit_status != 0: raise ProcessExecutionError(exit_code=exit_status, stdout=stdout, stderr=stderr, cmd=cmd) return (stdout, stderr)
josepedro/palabos_acoustic
refs/heads/master
scons/scons-local-2.1.0/SCons/Tool/aixc++.py
21
"""SCons.Tool.aixc++ Tool-specific initialization for IBM xlC / Visual Age C++ compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 The SCons Foundation # # 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. # __revision__ = "src/engine/SCons/Tool/aixc++.py 5357 2011/09/09 21:31:03 bdeegan" import os.path import SCons.Platform.aix cplusplus = __import__('c++', globals(), locals(), []) packages = ['vacpp.cmp.core', 'vacpp.cmp.batch', 'vacpp.cmp.C', 'ibmcxx.cmp'] def get_xlc(env): xlc = env.get('CXX', 'xlC') xlc_r = env.get('SHCXX', 'xlC_r') return SCons.Platform.aix.get_xlc(env, xlc, xlc_r, packages) def smart_cxxflags(source, target, env, for_signature): build_dir = env.GetBuildPath() if build_dir: return '-qtempinc=' + os.path.join(build_dir, 'tempinc') return '' def generate(env): """Add Builders and construction variables for xlC / Visual Age suite to an Environment.""" path, _cxx, _shcxx, version = get_xlc(env) if path: _cxx = os.path.join(path, _cxx) _shcxx = os.path.join(path, _shcxx) cplusplus.generate(env) env['CXX'] = _cxx env['SHCXX'] = _shcxx env['CXXVERSION'] = version env['SHOBJSUFFIX'] = '.pic.o' def exists(env): path, _cxx, _shcxx, version = get_xlc(env) if path and _cxx: xlc = os.path.join(path, _cxx) if os.path.exists(xlc): return xlc return None # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
brianmhunt/SIWorldMap
refs/heads/master
jinja2/testsuite/lexnparse.py
82
# -*- coding: utf-8 -*- """ jinja2.testsuite.lexnparse ~~~~~~~~~~~~~~~~~~~~~~~~~~ All the unittests regarding lexing, parsing and syntax. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ import sys import unittest from jinja2.testsuite import JinjaTestCase from jinja2 import Environment, Template, TemplateSyntaxError, \ UndefinedError, nodes env = Environment() # how does a string look like in jinja syntax? if sys.version_info < (3, 0): def jinja_string_repr(string): return repr(string)[1:] else: jinja_string_repr = repr class LexerTestCase(JinjaTestCase): def test_raw1(self): tmpl = env.from_string('{% raw %}foo{% endraw %}|' '{%raw%}{{ bar }}|{% baz %}{% endraw %}') assert tmpl.render() == 'foo|{{ bar }}|{% baz %}' def test_raw2(self): tmpl = env.from_string('1 {%- raw -%} 2 {%- endraw -%} 3') assert tmpl.render() == '123' def test_balancing(self): env = Environment('{%', '%}', '${', '}') tmpl = env.from_string('''{% for item in seq %}${{'foo': item}|upper}{% endfor %}''') assert tmpl.render(seq=range(3)) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}" def test_comments(self): env = Environment('<!--', '-->', '{', '}') tmpl = env.from_string('''\ <ul> <!--- for item in seq --> <li>{item}</li> <!--- endfor --> </ul>''') assert tmpl.render(seq=range(3)) == ("<ul>\n <li>0</li>\n " "<li>1</li>\n <li>2</li>\n</ul>") def test_string_escapes(self): for char in u'\0', u'\u2668', u'\xe4', u'\t', u'\r', u'\n': tmpl = env.from_string('{{ %s }}' % jinja_string_repr(char)) assert tmpl.render() == char assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == u'\u2668' def test_bytefallback(self): from pprint import pformat tmpl = env.from_string(u'''{{ 'foo'|pprint }}|{{ 'bär'|pprint }}''') assert tmpl.render() == pformat('foo') + '|' + pformat(u'bär') def test_operators(self): from jinja2.lexer import operators for test, expect in operators.iteritems(): if test in '([{}])': continue stream = env.lexer.tokenize('{{ %s }}' % test) stream.next() assert stream.current.type == expect def test_normalizing(self): for seq in '\r', '\r\n', '\n': env = Environment(newline_sequence=seq) tmpl = env.from_string('1\n2\r\n3\n4\n') result = tmpl.render() assert result.replace(seq, 'X') == '1X2X3X4' class ParserTestCase(JinjaTestCase): def test_php_syntax(self): env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->') tmpl = env.from_string('''\ <!-- I'm a comment, I'm not interesting -->\ <? for item in seq -?> <?= item ?> <?- endfor ?>''') assert tmpl.render(seq=range(5)) == '01234' def test_erb_syntax(self): env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>') tmpl = env.from_string('''\ <%# I'm a comment, I'm not interesting %>\ <% for item in seq -%> <%= item %> <%- endfor %>''') assert tmpl.render(seq=range(5)) == '01234' def test_comment_syntax(self): env = Environment('<!--', '-->', '${', '}', '<!--#', '-->') tmpl = env.from_string('''\ <!--# I'm a comment, I'm not interesting -->\ <!-- for item in seq ---> ${item} <!--- endfor -->''') assert tmpl.render(seq=range(5)) == '01234' def test_balancing(self): tmpl = env.from_string('''{{{'foo':'bar'}.foo}}''') assert tmpl.render() == 'bar' def test_start_comment(self): tmpl = env.from_string('''{# foo comment and bar comment #} {% macro blub() %}foo{% endmacro %} {{ blub() }}''') assert tmpl.render().strip() == 'foo' def test_line_syntax(self): env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%') tmpl = env.from_string('''\ <%# regular comment %> % for item in seq: ${item} % endfor''') assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \ range(5) env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##') tmpl = env.from_string('''\ <%# regular comment %> % for item in seq: ${item} ## the rest of the stuff % endfor''') assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \ range(5) def test_line_syntax_priority(self): # XXX: why is the whitespace there in front of the newline? env = Environment('{%', '%}', '${', '}', '/*', '*/', '##', '#') tmpl = env.from_string('''\ /* ignore me. I'm a multiline comment */ ## for item in seq: * ${item} # this is just extra stuff ## endfor''') assert tmpl.render(seq=[1, 2]).strip() == '* 1\n* 2' env = Environment('{%', '%}', '${', '}', '/*', '*/', '#', '##') tmpl = env.from_string('''\ /* ignore me. I'm a multiline comment */ # for item in seq: * ${item} ## this is just extra stuff ## extra stuff i just want to ignore # endfor''') assert tmpl.render(seq=[1, 2]).strip() == '* 1\n\n* 2' def test_error_messages(self): def assert_error(code, expected): try: Template(code) except TemplateSyntaxError, e: assert str(e) == expected, 'unexpected error message' else: assert False, 'that was suposed to be an error' assert_error('{% for item in seq %}...{% endif %}', "Encountered unknown tag 'endif'. Jinja was looking " "for the following tags: 'endfor' or 'else'. The " "innermost block that needs to be closed is 'for'.") assert_error('{% if foo %}{% for item in seq %}...{% endfor %}{% endfor %}', "Encountered unknown tag 'endfor'. Jinja was looking for " "the following tags: 'elif' or 'else' or 'endif'. The " "innermost block that needs to be closed is 'if'.") assert_error('{% if foo %}', "Unexpected end of template. Jinja was looking for the " "following tags: 'elif' or 'else' or 'endif'. The " "innermost block that needs to be closed is 'if'.") assert_error('{% for item in seq %}', "Unexpected end of template. Jinja was looking for the " "following tags: 'endfor' or 'else'. The innermost block " "that needs to be closed is 'for'.") assert_error('{% block foo-bar-baz %}', "Block names in Jinja have to be valid Python identifiers " "and may not contain hypens, use an underscore instead.") assert_error('{% unknown_tag %}', "Encountered unknown tag 'unknown_tag'.") class SyntaxTestCase(JinjaTestCase): def test_call(self): env = Environment() env.globals['foo'] = lambda a, b, c, e, g: a + b + c + e + g tmpl = env.from_string("{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}") assert tmpl.render() == 'abdfh' def test_slicing(self): tmpl = env.from_string('{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}') assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]' def test_attr(self): tmpl = env.from_string("{{ foo.bar }}|{{ foo['bar'] }}") assert tmpl.render(foo={'bar': 42}) == '42|42' def test_subscript(self): tmpl = env.from_string("{{ foo[0] }}|{{ foo[-1] }}") assert tmpl.render(foo=[0, 1, 2]) == '0|2' def test_tuple(self): tmpl = env.from_string('{{ () }}|{{ (1,) }}|{{ (1, 2) }}') assert tmpl.render() == '()|(1,)|(1, 2)' def test_math(self): tmpl = env.from_string('{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}') assert tmpl.render() == '1.5|8' def test_div(self): tmpl = env.from_string('{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}') assert tmpl.render() == '1|1.5|1' def test_unary(self): tmpl = env.from_string('{{ +3 }}|{{ -3 }}') assert tmpl.render() == '3|-3' def test_concat(self): tmpl = env.from_string("{{ [1, 2] ~ 'foo' }}") assert tmpl.render() == '[1, 2]foo' def test_compare(self): tmpl = env.from_string('{{ 1 > 0 }}|{{ 1 >= 1 }}|{{ 2 < 3 }}|' '{{ 2 == 2 }}|{{ 1 <= 1 }}') assert tmpl.render() == 'True|True|True|True|True' def test_inop(self): tmpl = env.from_string('{{ 1 in [1, 2, 3] }}|{{ 1 not in [1, 2, 3] }}') assert tmpl.render() == 'True|False' def test_literals(self): tmpl = env.from_string('{{ [] }}|{{ {} }}|{{ () }}') assert tmpl.render().lower() == '[]|{}|()' def test_bool(self): tmpl = env.from_string('{{ true and false }}|{{ false ' 'or true }}|{{ not false }}') assert tmpl.render() == 'False|True|True' def test_grouping(self): tmpl = env.from_string('{{ (true and false) or (false and true) and not false }}') assert tmpl.render() == 'False' def test_django_attr(self): tmpl = env.from_string('{{ [1, 2, 3].0 }}|{{ [[1]].0.0 }}') assert tmpl.render() == '1|1' def test_conditional_expression(self): tmpl = env.from_string('''{{ 0 if true else 1 }}''') assert tmpl.render() == '0' def test_short_conditional_expression(self): tmpl = env.from_string('<{{ 1 if false }}>') assert tmpl.render() == '<>' tmpl = env.from_string('<{{ (1 if false).bar }}>') self.assert_raises(UndefinedError, tmpl.render) def test_filter_priority(self): tmpl = env.from_string('{{ "foo"|upper + "bar"|upper }}') assert tmpl.render() == 'FOOBAR' def test_function_calls(self): tests = [ (True, '*foo, bar'), (True, '*foo, *bar'), (True, '*foo, bar=42'), (True, '**foo, *bar'), (True, '**foo, bar'), (False, 'foo, bar'), (False, 'foo, bar=42'), (False, 'foo, bar=23, *args'), (False, 'a, b=c, *d, **e'), (False, '*foo, **bar') ] for should_fail, sig in tests: if should_fail: self.assert_raises(TemplateSyntaxError, env.from_string, '{{ foo(%s) }}' % sig) else: env.from_string('foo(%s)' % sig) def test_tuple_expr(self): for tmpl in [ '{{ () }}', '{{ (1, 2) }}', '{{ (1, 2,) }}', '{{ 1, }}', '{{ 1, 2 }}', '{% for foo, bar in seq %}...{% endfor %}', '{% for x in foo, bar %}...{% endfor %}', '{% for x in foo, %}...{% endfor %}' ]: assert env.from_string(tmpl) def test_trailing_comma(self): tmpl = env.from_string('{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}') assert tmpl.render().lower() == '(1, 2)|[1, 2]|{1: 2}' def test_block_end_name(self): env.from_string('{% block foo %}...{% endblock foo %}') self.assert_raises(TemplateSyntaxError, env.from_string, '{% block x %}{% endblock y %}') def test_contant_casing(self): for const in True, False, None: tmpl = env.from_string('{{ %s }}|{{ %s }}|{{ %s }}' % ( str(const), str(const).lower(), str(const).upper() )) assert tmpl.render() == '%s|%s|' % (const, const) def test_test_chaining(self): self.assert_raises(TemplateSyntaxError, env.from_string, '{{ foo is string is sequence }}') env.from_string('{{ 42 is string or 42 is number }}' ).render() == 'True' def test_string_concatenation(self): tmpl = env.from_string('{{ "foo" "bar" "baz" }}') assert tmpl.render() == 'foobarbaz' def test_notin(self): bar = xrange(100) tmpl = env.from_string('''{{ not 42 in bar }}''') assert tmpl.render(bar=bar) == unicode(not 42 in bar) def test_implicit_subscribed_tuple(self): class Foo(object): def __getitem__(self, x): return x t = env.from_string('{{ foo[1, 2] }}') assert t.render(foo=Foo()) == u'(1, 2)' def test_raw2(self): tmpl = env.from_string('{% raw %}{{ FOO }} and {% BAR %}{% endraw %}') assert tmpl.render() == '{{ FOO }} and {% BAR %}' def test_const(self): tmpl = env.from_string('{{ true }}|{{ false }}|{{ none }}|' '{{ none is defined }}|{{ missing is defined }}') assert tmpl.render() == 'True|False|None|True|False' def test_neg_filter_priority(self): node = env.parse('{{ -1|foo }}') assert isinstance(node.body[0].nodes[0], nodes.Filter) assert isinstance(node.body[0].nodes[0].node, nodes.Neg) def test_const_assign(self): constass1 = '''{% set true = 42 %}''' constass2 = '''{% for none in seq %}{% endfor %}''' for tmpl in constass1, constass2: self.assert_raises(TemplateSyntaxError, env.from_string, tmpl) def test_localset(self): tmpl = env.from_string('''{% set foo = 0 %}\ {% for item in [1, 2] %}{% set foo = 1 %}{% endfor %}\ {{ foo }}''') assert tmpl.render() == '0' def test_parse_unary(self): tmpl = env.from_string('{{ -foo["bar"] }}') assert tmpl.render(foo={'bar': 42}) == '-42' tmpl = env.from_string('{{ -foo["bar"]|abs }}') assert tmpl.render(foo={'bar': 42}) == '42' def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(LexerTestCase)) suite.addTest(unittest.makeSuite(ParserTestCase)) suite.addTest(unittest.makeSuite(SyntaxTestCase)) return suite
rversteegen/commandergenius
refs/heads/sdl_android
project/jni/python/src/Lib/test/test_urllib2net.py
51
#!/usr/bin/env python import unittest from test import test_support from test.test_urllib2 import sanepathname2url import socket import urllib2 import sys import os import mimetools def _retry_thrice(func, exc, *args, **kwargs): for i in range(3): try: return func(*args, **kwargs) except exc, last_exc: continue except: raise raise last_exc def _wrap_with_retry_thrice(func, exc): def wrapped(*args, **kwargs): return _retry_thrice(func, exc, *args, **kwargs) return wrapped # Connecting to remote hosts is flaky. Make it more robust by retrying # the connection several times. _urlopen_with_retry = _wrap_with_retry_thrice(urllib2.urlopen, urllib2.URLError) class AuthTests(unittest.TestCase): """Tests urllib2 authentication features.""" ## Disabled at the moment since there is no page under python.org which ## could be used to HTTP authentication. # # def test_basic_auth(self): # import httplib # # test_url = "http://www.python.org/test/test_urllib2/basic_auth" # test_hostport = "www.python.org" # test_realm = 'Test Realm' # test_user = 'test.test_urllib2net' # test_password = 'blah' # # # failure # try: # _urlopen_with_retry(test_url) # except urllib2.HTTPError, exc: # self.assertEqual(exc.code, 401) # else: # self.fail("urlopen() should have failed with 401") # # # success # auth_handler = urllib2.HTTPBasicAuthHandler() # auth_handler.add_password(test_realm, test_hostport, # test_user, test_password) # opener = urllib2.build_opener(auth_handler) # f = opener.open('http://localhost/') # response = _urlopen_with_retry("http://www.python.org/") # # # The 'userinfo' URL component is deprecated by RFC 3986 for security # # reasons, let's not implement it! (it's already implemented for proxy # # specification strings (that is, URLs or authorities specifying a # # proxy), so we must keep that) # self.assertRaises(httplib.InvalidURL, # urllib2.urlopen, "http://evil:thing@example.com") class CloseSocketTest(unittest.TestCase): def test_close(self): import socket, httplib, gc # calling .close() on urllib2's response objects should close the # underlying socket # delve deep into response to fetch socket._socketobject response = _urlopen_with_retry("http://www.python.org/") abused_fileobject = response.fp self.assert_(abused_fileobject.__class__ is socket._fileobject) httpresponse = abused_fileobject._sock self.assert_(httpresponse.__class__ is httplib.HTTPResponse) fileobject = httpresponse.fp self.assert_(fileobject.__class__ is socket._fileobject) self.assert_(not fileobject.closed) response.close() self.assert_(fileobject.closed) class OtherNetworkTests(unittest.TestCase): def setUp(self): if 0: # for debugging import logging logger = logging.getLogger("test_urllib2net") logger.addHandler(logging.StreamHandler()) # XXX The rest of these tests aren't very good -- they don't check much. # They do sometimes catch some major disasters, though. def test_ftp(self): urls = [ 'ftp://ftp.kernel.org/pub/linux/kernel/README', 'ftp://ftp.kernel.org/pub/linux/kernel/non-existant-file', #'ftp://ftp.kernel.org/pub/leenox/kernel/test', 'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC' '/research-reports/00README-Legal-Rules-Regs', ] self._test_urls(urls, self._extra_handlers()) def test_file(self): TESTFN = test_support.TESTFN f = open(TESTFN, 'w') try: f.write('hi there\n') f.close() urls = [ 'file:'+sanepathname2url(os.path.abspath(TESTFN)), ('file:///nonsensename/etc/passwd', None, urllib2.URLError), ] self._test_urls(urls, self._extra_handlers(), retry=True) finally: os.remove(TESTFN) # XXX Following test depends on machine configurations that are internal # to CNRI. Need to set up a public server with the right authentication # configuration for test purposes. ## def test_cnri(self): ## if socket.gethostname() == 'bitdiddle': ## localhost = 'bitdiddle.cnri.reston.va.us' ## elif socket.gethostname() == 'bitdiddle.concentric.net': ## localhost = 'localhost' ## else: ## localhost = None ## if localhost is not None: ## urls = [ ## 'file://%s/etc/passwd' % localhost, ## 'http://%s/simple/' % localhost, ## 'http://%s/digest/' % localhost, ## 'http://%s/not/found.h' % localhost, ## ] ## bauth = HTTPBasicAuthHandler() ## bauth.add_password('basic_test_realm', localhost, 'jhylton', ## 'password') ## dauth = HTTPDigestAuthHandler() ## dauth.add_password('digest_test_realm', localhost, 'jhylton', ## 'password') ## self._test_urls(urls, self._extra_handlers()+[bauth, dauth]) def _test_urls(self, urls, handlers, retry=True): import socket import time import logging debug = logging.getLogger("test_urllib2").debug urlopen = urllib2.build_opener(*handlers).open if retry: urlopen = _wrap_with_retry_thrice(urlopen, urllib2.URLError) for url in urls: if isinstance(url, tuple): url, req, expected_err = url else: req = expected_err = None debug(url) try: f = urlopen(url, req) except EnvironmentError, err: debug(err) if expected_err: msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" % (expected_err, url, req, type(err), err)) self.assert_(isinstance(err, expected_err), msg) else: with test_support.transient_internet(): buf = f.read() f.close() debug("read %d bytes" % len(buf)) debug("******** next url coming up...") time.sleep(0.1) def _extra_handlers(self): handlers = [] cfh = urllib2.CacheFTPHandler() cfh.setTimeout(1) handlers.append(cfh) return handlers class TimeoutTest(unittest.TestCase): def test_http_basic(self): self.assertTrue(socket.getdefaulttimeout() is None) u = _urlopen_with_retry("http://www.python.org") self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None) def test_http_default_timeout(self): self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(60) try: u = _urlopen_with_retry("http://www.python.org") finally: socket.setdefaulttimeout(None) self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 60) def test_http_no_timeout(self): self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(60) try: u = _urlopen_with_retry("http://www.python.org", timeout=None) finally: socket.setdefaulttimeout(None) self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None) def test_http_timeout(self): u = _urlopen_with_retry("http://www.python.org", timeout=120) self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 120) FTP_HOST = "ftp://ftp.mirror.nl/pub/mirror/gnu/" def test_ftp_basic(self): self.assertTrue(socket.getdefaulttimeout() is None) u = _urlopen_with_retry(self.FTP_HOST) self.assertTrue(u.fp.fp._sock.gettimeout() is None) def test_ftp_default_timeout(self): self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(60) try: u = _urlopen_with_retry(self.FTP_HOST) finally: socket.setdefaulttimeout(None) self.assertEqual(u.fp.fp._sock.gettimeout(), 60) def test_ftp_no_timeout(self): self.assertTrue(socket.getdefaulttimeout() is None) socket.setdefaulttimeout(60) try: u = _urlopen_with_retry(self.FTP_HOST, timeout=None) finally: socket.setdefaulttimeout(None) self.assertTrue(u.fp.fp._sock.gettimeout() is None) def test_ftp_timeout(self): u = _urlopen_with_retry(self.FTP_HOST, timeout=60) self.assertEqual(u.fp.fp._sock.gettimeout(), 60) def test_main(): test_support.requires("network") test_support.run_unittest(AuthTests, OtherNetworkTests, CloseSocketTest, TimeoutTest, ) if __name__ == "__main__": test_main()
collects/VTK
refs/heads/master
Examples/VisualizationAlgorithms/Python/probeComb.py
27
#!/usr/bin/env python # This shows how to probe a dataset with a plane. The probed data is # then contoured. import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Read data. pl3d = vtk.vtkMultiBlockPLOT3DReader() pl3d.SetXYZFileName(VTK_DATA_ROOT + "/Data/combxyz.bin") pl3d.SetQFileName(VTK_DATA_ROOT + "/Data/combq.bin") pl3d.SetScalarFunctionNumber(100) pl3d.SetVectorFunctionNumber(202) pl3d.Update() pl3d_output = pl3d.GetOutput().GetBlock(0) # We create three planes and position them in the correct position # using transform filters. They are then appended together and used as # a probe. plane = vtk.vtkPlaneSource() plane.SetResolution(50, 50) transP1 = vtk.vtkTransform() transP1.Translate(3.7, 0.0, 28.37) transP1.Scale(5, 5, 5) transP1.RotateY(90) tpd1 = vtk.vtkTransformPolyDataFilter() tpd1.SetInputConnection(plane.GetOutputPort()) tpd1.SetTransform(transP1) outTpd1 = vtk.vtkOutlineFilter() outTpd1.SetInputConnection(tpd1.GetOutputPort()) mapTpd1 = vtk.vtkPolyDataMapper() mapTpd1.SetInputConnection(outTpd1.GetOutputPort()) tpd1Actor = vtk.vtkActor() tpd1Actor.SetMapper(mapTpd1) tpd1Actor.GetProperty().SetColor(0, 0, 0) transP2 = vtk.vtkTransform() transP2.Translate(9.2, 0.0, 31.20) transP2.Scale(5, 5, 5) transP2.RotateY(90) tpd2 = vtk.vtkTransformPolyDataFilter() tpd2.SetInputConnection(plane.GetOutputPort()) tpd2.SetTransform(transP2) outTpd2 = vtk.vtkOutlineFilter() outTpd2.SetInputConnection(tpd2.GetOutputPort()) mapTpd2 = vtk.vtkPolyDataMapper() mapTpd2.SetInputConnection(outTpd2.GetOutputPort()) tpd2Actor = vtk.vtkActor() tpd2Actor.SetMapper(mapTpd2) tpd2Actor.GetProperty().SetColor(0, 0, 0) transP3 = vtk.vtkTransform() transP3.Translate(13.27, 0.0, 33.30) transP3.Scale(5, 5, 5) transP3.RotateY(90) tpd3 = vtk.vtkTransformPolyDataFilter() tpd3.SetInputConnection(plane.GetOutputPort()) tpd3.SetTransform(transP3) outTpd3 = vtk.vtkOutlineFilter() outTpd3.SetInputConnection(tpd3.GetOutputPort()) mapTpd3 = vtk.vtkPolyDataMapper() mapTpd3.SetInputConnection(outTpd3.GetOutputPort()) tpd3Actor = vtk.vtkActor() tpd3Actor.SetMapper(mapTpd3) tpd3Actor.GetProperty().SetColor(0, 0, 0) appendF = vtk.vtkAppendPolyData() appendF.AddInputConnection(tpd1.GetOutputPort()) appendF.AddInputConnection(tpd2.GetOutputPort()) appendF.AddInputConnection(tpd3.GetOutputPort()) # The vtkProbeFilter takes two inputs. One is a dataset to use as the # probe geometry (SetInput); the other is the data to probe # (SetSource). The output dataset structure (geometry and topology) of # the probe is the same as the structure of the input. The probing # process generates new data values resampled from the source. probe = vtk.vtkProbeFilter() probe.SetInputConnection(appendF.GetOutputPort()) probe.SetSourceData(pl3d_output) contour = vtk.vtkContourFilter() contour.SetInputConnection(probe.GetOutputPort()) contour.GenerateValues(50, pl3d_output.GetScalarRange()) contourMapper = vtk.vtkPolyDataMapper() contourMapper.SetInputConnection(contour.GetOutputPort()) contourMapper.SetScalarRange(pl3d_output.GetScalarRange()) planeActor = vtk.vtkActor() planeActor.SetMapper(contourMapper) outline = vtk.vtkStructuredGridOutlineFilter() outline.SetInputData(pl3d_output) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.GetProperty().SetColor(0, 0, 0) # Create the RenderWindow, Renderer and both Actors ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) ren.AddActor(outlineActor) ren.AddActor(planeActor) ren.AddActor(tpd1Actor) ren.AddActor(tpd2Actor) ren.AddActor(tpd3Actor) ren.SetBackground(1, 1, 1) renWin.SetSize(400, 400) ren.ResetCamera() cam1 = ren.GetActiveCamera() cam1.SetClippingRange(3.95297, 50) cam1.SetFocalPoint(8.88908, 0.595038, 29.3342) cam1.SetPosition(-12.3332, 31.7479, 41.2387) cam1.SetViewUp(0.060772, -0.319905, 0.945498) iren.Initialize() renWin.Render() iren.Start()
luotao1/Paddle
refs/heads/develop
python/paddle/fluid/tests/unittests/test_fleet_base.py
2
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import paddle import paddle.distributed.fleet as fleet import paddle.distributed.fleet.base.role_maker as role_maker import os import paddle.fluid as fluid import paddle.nn as nn import numpy as np class TestFleetBase(unittest.TestCase): def setUp(self): os.environ["POD_IP"] = "127.0.0.1" os.environ["PADDLE_TRAINER_ENDPOINTS"] = "127.0.0.1:36000" os.environ["PADDLE_TRAINERS_NUM"] = "2" os.environ["PADDLE_PSERVERS_IP_PORT_LIST"] = \ "127.0.0.1:36001,127.0.0.2:36002" def test_init(self): role = role_maker.PaddleCloudRoleMaker(is_collective=True) fleet.init(role) def test_is_first_worker(self): role = role_maker.PaddleCloudRoleMaker(is_collective=True) fleet.init(role) if fleet.is_first_worker(): print("test fleet first worker done.") def test_worker_index(self): role = role_maker.PaddleCloudRoleMaker(is_collective=True) fleet.init(role) print(fleet.worker_index()) def test_worker_num(self): role = role_maker.PaddleCloudRoleMaker(is_collective=True) fleet.init(role) print(fleet.worker_num()) def test_is_worker(self): role = role_maker.PaddleCloudRoleMaker(is_collective=True) fleet.init(role) if fleet.is_worker(): print("test fleet is worker") def test_worker_endpoints(self): role = role_maker.PaddleCloudRoleMaker(is_collective=True) fleet.init(role) self.assertEqual( "127.0.0.1:36000", fleet.worker_endpoints(to_string=True)) self.assertEqual(["127.0.0.1:36000"], fleet.worker_endpoints()) def test_server_num(self): os.environ["TRAINING_ROLE"] = "PSERVER" os.environ["PADDLE_PORT"] = "36001" os.environ["POD_IP"] = "127.0.0.1" role = role_maker.PaddleCloudRoleMaker() fleet.init(role) os.environ["PADDLE_TRAINERS_NUM"] = "2" self.assertEqual(2, fleet.server_num()) def test_server_index(self): os.environ["TRAINING_ROLE"] = "PSERVER" os.environ["PADDLE_PORT"] = "36001" os.environ["POD_IP"] = "127.0.0.1" role = role_maker.PaddleCloudRoleMaker() fleet.init(role) self.assertEqual(0, fleet.server_index()) def test_server_endpoints(self): os.environ["TRAINING_ROLE"] = "PSERVER" os.environ["PADDLE_PORT"] = "36001" os.environ["POD_IP"] = "127.0.0.1" role = role_maker.PaddleCloudRoleMaker() fleet.init(role) if fleet.is_server(): self.assertEqual( "127.0.0.1:36001,127.0.0.2:36002", fleet.server_endpoints(to_string=True)) self.assertEqual(["127.0.0.1:36001", "127.0.0.2:36002"], fleet.server_endpoints()) def test_is_server(self): os.environ["TRAINING_ROLE"] = "PSERVER" os.environ["PADDLE_PORT"] = "36001" os.environ["POD_IP"] = "127.0.0.1" role = role_maker.PaddleCloudRoleMaker() fleet.init(role) self.assertTrue(fleet.is_server()) def test_util(self): role = role_maker.PaddleCloudRoleMaker(is_collective=True) fleet.init(role) self.assertNotEqual(fleet.util, None) def test_barrier_worker(self): role = role_maker.PaddleCloudRoleMaker(is_collective=True) fleet.init(role) if fleet.is_worker(): fleet.barrier_worker() def test_init_worker(self): role = role_maker.PaddleCloudRoleMaker(is_collective=True) fleet.init(role) with self.assertRaises(ValueError): if fleet.is_worker(): fleet.init_worker() def test_stop_worker(self): role = role_maker.PaddleCloudRoleMaker(is_collective=True) fleet.init(role) with self.assertRaises(ValueError): if fleet.is_worker(): fleet.stop_worker() def test_distributed_optimizer(self): role = role_maker.PaddleCloudRoleMaker(is_collective=True) fleet.init(role) optimizer = paddle.optimizer.SGD(learning_rate=0.001) optimizer = fleet.distributed_optimizer(optimizer) def test_exception(self): import paddle.distributed.fleet as fleet self.assertRaises(Exception, fleet.init_worker) class TestFleetDygraph(unittest.TestCase): def setUp(self): os.environ[ "PADDLE_TRAINER_ENDPOINTS"] = "127.0.0.1:36213,127.0.0.1:36214" os.environ["PADDLE_CURRENT_ENDPOINTS"] = "127.0.0.1:36213" os.environ["PADDLE_TRAINERS_NUM"] = "2" os.environ["PADDLE_TRAINER_ID"] = "0" def test_dygraph_method(self): paddle.disable_static() value = np.arange(26).reshape(2, 13).astype("float32") a = fluid.dygraph.to_variable(value) layer = paddle.nn.Linear(13, 5) adam = paddle.optimizer.Adam( learning_rate=0.01, parameters=layer.parameters()) # remove init cause this UT cannot launch distributed task adam = fleet.distributed_optimizer(adam) try: dp_layer = fleet.distributed_model(layer) except Exception as e: # This is just for testing the interface, # and will not actually be called. Therefore, # use "try-except" to avoid errors. lr = 0.001 adam.set_lr(lr) cur_lr = adam.get_lr() assert (lr == cur_lr) state_dict = adam.state_dict() adam.set_state_dict(state_dict) final_strategy = fleet._final_strategy() class TestFleetBaseSingleError(unittest.TestCase): def setUp(self): os.environ.pop("PADDLE_TRAINER_ENDPOINTS") def gen_data(self): return { "x": np.random.random(size=(128, 32)).astype('float32'), "y": np.random.randint( 2, size=(128, 1)).astype('int64') } def test_single_run_collective_minimize(self): def test_single_error(): input_x = paddle.static.data( name="x", shape=[-1, 32], dtype='float32') input_y = paddle.static.data(name="y", shape=[-1, 1], dtype='int64') fc_1 = fluid.layers.fc(input=input_x, size=64, act='tanh') prediction = fluid.layers.fc(input=fc_1, size=2, act='softmax') cost = fluid.layers.cross_entropy(input=prediction, label=input_y) avg_cost = paddle.mean(x=cost) fleet.init(is_collective=True) # in non_distributed mode(use `python` to launch), raise error if has multi cards if fluid.core.is_compiled_with_cuda( ) and fluid.core.get_cuda_device_count() > 1: self.assertRaises(ValueError, test_single_error) else: test_single_error() if __name__ == "__main__": unittest.main()
jkpr/pmix
refs/heads/master
tests/test_numbering.py
1
"""Unit tests for numbering.py.""" import itertools import unittest import pmix.numbering as numbering class NumberingFormatTest(unittest.TestCase): """Test the string format for fixed numberings.""" def match_re(self, prog, expr, match): found = prog.match(expr) if match: msg = 'Expected "{}" to be accepted.'.format(expr) self.assertIsNotNone(found, msg=msg) else: msg = 'Expected "{}" not to be accepted.'.format(expr) self.assertIsNone(found, msg=msg) def test_upper_re(self): """Regex-ify uppercase numbering.""" this_prog = numbering.Numbering.letter_prog good = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' for item in good: self.match_re(this_prog, item, True) bad_single = tuple('ÁÉ01') other_bad = ('', 'AA', 'A1', '1A', '_', '-', 'A.', ' A', 'A ') for item in itertools.chain(bad_single, other_bad): self.match_re(this_prog, item, False) def test_number_re(self): """Regex-ify pure number numbering.""" this_prog = numbering.Numbering.number_prog good = ('001', '101', '201', 'LCL_301', 'A1', 'FLW801', 'PHC105', '1') for item in good: self.match_re(this_prog, item, True) bad = ('', '001a', '10.', '_', '-', 'SN_101i') for item in bad: self.match_re(this_prog, item, False) def test_ext_letter_re(self): """Regex-ify extended numbering with letter.""" this_prog = numbering.Numbering.ext_letter_prog good = ('001a', 'PHC101d', '101z', 'LCL_308a', 'SN_101.i') for item in good: self.match_re(this_prog, item, True) bad = ('001', 'A', '', '_', '-', 'PHC101.ix', '101a.', ' 101a', '1a ') for item in bad: self.match_re(this_prog, item, False) def test_ext_roman_re(self): """Regex-ify extended numbering with roman numeral.""" this_prog = numbering.Numbering.ext_roman_prog good = ('1a.i', '2b.ii', '3c.iii', '4d:iv', '5e_v', '6f-vi', '7g)vii', '8h_viii', '9i_ix', '10j_x', '1.a.i') for item in good: self.match_re(this_prog, item, True) bad = ('', '_', '-', '001', 'A', '2ii', '1iiii', '25y', '1i ', ' 2ii', '21av') for item in bad: self.match_re(this_prog, item, False) def test_decompose(self): """Decompose numbering.""" answers = ( ('a', 'a', '', '', '', '', '', ''), ('A', 'A', '', '', '', '', '', ''), ('001', '', '', '001', '', '', '', ''), ('001a', '', '', '001', '', 'a', '', ''), ('001.a', '', '', '001', '.', 'a', '', ''), ('3a.iii', '', '', '3', '', 'a', '.', 'iii'), ('PHC101-i', '', 'PHC', '101', '-', 'i', '', ''), ('FLW801', '', 'FLW', '801', '', '', '', ''), ('LCL_101', '', 'LCL_', '101', '', '', '', '') ) for expr, let, lead, number, p0, low, p1, rom in answers: msg = 'Working with "{}"'.format(expr) num = numbering.Numbering(expr) self.assertEqual(let, num.letter, msg=msg) self.assertEqual(lead, num.leader, msg=msg) self.assertEqual(number, num.number, msg=msg) self.assertEqual(p0, num.punc0, msg=msg) self.assertEqual(low, num.lower, msg=msg) self.assertEqual(p1, num.punc1, msg=msg) self.assertEqual(rom, num.roman, msg=msg) class NumberingIncrementTest(unittest.TestCase): """Test numbering increments.""" def test_naive_number_increment(self): """A naive test of incrementing.""" num = numbering.Numbering('001') num.increment('^1') self.assertEqual(str(num), '002') num.increment('^2') self.assertEqual(str(num), '004') num.increment('^a') self.assertEqual(str(num), '004a') num.increment('^1') self.assertEqual(str(num), '005') num.increment('^1a') self.assertEqual(str(num), '006a') num.increment('^1a') self.assertEqual(str(num), '007a') num = numbering.Numbering('101') num.increment('^1') self.assertEqual(str(num), '102') def compare_chains(self, chains): """Compare commands to answers in batches.""" for chain, answers in chains: context = numbering.NumberingContext() for cmd, answer in zip(chain, answers): context.next(cmd) num_now = context.numbers[-1].to_string() msg = 'Mistake on chain {}'.format(chain) self.assertEqual(num_now, answer, msg=msg) def compare_chains_entirely(self, chains): """Compare chains in their entirety.""" for chain, answers in chains: context = numbering.NumberingContext() for cmd in chain: context.next(cmd) results = tuple(context.string_iter()) self.assertEqual(results, answers) def test_increment_lookback(self): """Increment and lookback operators and their interplay.""" chains = ( (('001', '^1', '^1', '^1', '<', '<', '^1a', '^a'), ('001', '002', '003', '004', '004', '004', '005a', '005b')), (('101', '^1', '^1', '^1', '<', '<', '^1a', '^a'), ('101', '102', '103', '104', '104', '104', '105a', '105b')), (('101', '^1a', '^a', '^1', '201', '<', '^a', '<' ), ('101', '102a', '102b', '103', '201', '201', '201a', '201a')), (('323a', '^a', '<2', '<2'), ('323a', '323b', '323a', '323b')), (('323a', '^1a', '<2^a', '<2^a'), ('323a', '324a', '323b', '324b')), (('001a', '<^i'), ('001a', '001a.i')), (('711a.ii', '<^ai'), ('711a.ii', '711b.i')), ) self.compare_chains(chains) def test_letter_increment(self): """Increment upper and lower case letters.""" chains = ( (('A', '^A', '^A'), ('A', 'B', 'C')), (('a', '^a', '^a'), ('a', 'b', 'c')) ) self.compare_chains(chains) def test_all_increment(self): """Increment with ^1ai.""" chains = ( (('1', '^1ai'), ('1', '2a.i')), ) self.compare_chains(chains) def test_sticky(self): """Sticky operator correctness.""" chains = ( (('PHC101', '^1', '#LCL_301', '^1'), ('PHC101', 'PHC102', 'LCL_301', 'PHC103')), (('BF012', '^1', '#NS012', '^1'), ('BF012', 'BF013', 'NS012', 'BF014')), (('001a', '#099', '101a'), ('001a', '099', '101a')) ) self.compare_chains(chains) def test_blanks(self): """Blanks mixed in with commands.""" chains = ( (('', '001a', '', '^1'), ('', '001a', '', '002')), (('PHC_101', '^a', '', '#LCL_100', '', '^1'), ('PHC_101', 'PHC_101a', '', 'LCL_100', '', 'PHC_102')) ) self.compare_chains_entirely(chains) def test_silent(self): """Silent numbers.""" chains = ( (('', '~000', '^1', '^1a'), ('', '', '001', '002a')), (('~PHC100', '', '^1a', '^a'), ('', '', 'PHC101a', 'PHC101b')) ) self.compare_chains_entirely(chains) def test_resume(self): """Resume previous series.""" chains = ( (('PHC101', 'a', '^a', '*^1a'), ('PHC101', 'a', 'b', 'PHC102a')), (('~000', '^1', 'a', '^a', '*<'), ('', '001', 'a', 'b', '001')) ) self.compare_chains_entirely(chains)
supermurat/hamsi-manager
refs/heads/master
Bars/MenuBar.py
1
# This file is part of HamsiManager. # # Copyright (c) 2010 - 2015 Murat Demir <mopened@gmail.com> # # Hamsi Manager 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. # # Hamsi Manager 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 HamsiManager; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from Core import Universals as uni from Core.MyObjects import * from Core import ReportBug from Options import QuickOptions import Bars class MenuBar(MMenuBar): def __init__(self, _parent): MMenuBar.__init__(self, _parent) self.mTableTools = None self.mQuickOptions = None self.mFile = self.addMenu(translate("MenuBar", "File")) self.mFile.setObjectName("File") self.mEdit = self.addMenu(translate("MenuBar", "Edit")) self.mEdit.setObjectName("Edit") self.mView = self.addMenu(translate("MenuBar", "View")) self.mView.setObjectName("View") self.mSettings = self.addMenu(translate("MenuBar", "Settings")) self.mSettings.setObjectName("Settings") if isActivePyKDE4: self.mHelpMenu = getMainWindow().helpMenu() self.mHelpMenu.setObjectName(self.mHelpMenu.title()) self.aHelpMenu = self.addMenu(self.mHelpMenu) else: self.mHelpMenu = self.addMenu(translate("MenuBar", "Help")) self.mHelpMenu.setObjectName("Help") mExport = MMenu(translate("MenuBar", "Export"), self.mEdit) mExport.setObjectName("Export") mExportToFile = MMenu(translate("MenuBar", "Export To File"), self.mEdit) mExportToFile.setObjectName("Export To File") mExportToFile.addAction(translate("MenuBar", "HTML Format")).setObjectName("HTML Format") mExportToFile.addAction(translate("MenuBar", "Text Format")).setObjectName("Text Format") mExportToFile.addAction(translate("MenuBar", "HTML Format (File Tree)")).setObjectName("HTML Format (File Tree)") mExportToFile.addAction(translate("MenuBar", "Text Format (File Tree)")).setObjectName("Text Format (File Tree)") mShowInWindow = MMenu(translate("MenuBar", "Show In New Window"), self.mEdit) mShowInWindow.setObjectName("Show In New Window") mShowInWindow.addAction(translate("MenuBar", "HTML Format")).setObjectName("HTML Format") mShowInWindow.addAction(translate("MenuBar", "Text Format")).setObjectName("Text Format") mShowInWindow.addAction(translate("MenuBar", "HTML Format (File Tree)")).setObjectName("HTML Format (File Tree)") mShowInWindow.addAction(translate("MenuBar", "Text Format (File Tree)")).setObjectName("Text Format (File Tree)") mCopyToClipBoard = MMenu(translate("MenuBar", "Copy To Clipboard"), self.mEdit) mCopyToClipBoard.setObjectName("Copy To Clipboard") mCopyToClipBoard.addAction(translate("MenuBar", "HTML Format")).setObjectName("HTML Format") mCopyToClipBoard.addAction(translate("MenuBar", "Text Format")).setObjectName("Text Format") mCopyToClipBoard.addAction(translate("MenuBar", "HTML Format (File Tree)")).setObjectName("HTML Format (File Tree)") mCopyToClipBoard.addAction(translate("MenuBar", "Text Format (File Tree)")).setObjectName("Text Format (File Tree)") mExport.addMenu(mExportToFile) mExport.addMenu(mShowInWindow) mExport.addMenu(mCopyToClipBoard) self.mFile.addAction(translate("MenuBar", "Open State")).setObjectName("Open State") self.mFile.addAction(translate("MenuBar", "Save State")).setObjectName("Save State") if uni.isRunableAsRoot(): mRunAsRoot = MMenu(translate("MenuBar", "Run As Root"), self.mFile) mRunAsRoot.addAction(translate("MenuBar", "With This Profile (My Settings)")).setObjectName("With This Profile (My Settings)") mRunAsRoot.addAction(translate("MenuBar", "With Root Profile (Own Settings)")).setObjectName("With Root Profile (Own Settings)") self.mFile.addMenu(mRunAsRoot) self.mFile.addAction(translate("MenuBar", "Quit")).setObjectName("Quit") self.mEdit.addMenu(mExport) actOptions = self.mSettings.addAction(translate("MenuBar", "Options")) actOptions.setObjectName("Options") actOptions.setIcon(MIcon("Images:options.png")) self.mSettings.addAction(translate("MenuBar", "My Plugins")).setObjectName("My Plugins") self.mSettings.addAction(translate("MenuBar", "Reconfigure")).setObjectName("Reconfigure") if uni.isRunableAsRoot(): self.mSettings.addAction(translate("MenuBar", "My Plugins (System)")).setObjectName("My Plugins (System)") self.mSettings.addAction(translate("MenuBar", "Reconfigure (System)")).setObjectName("Reconfigure (System)") if isActivePyKDE4: actReportBug = MAction(translate("MenuBar", "Report Bug"), self.mHelpMenu) actReportBug.setObjectName("Report Bug") self.mHelpMenu.insertAction(self.mHelpMenu.actions()[3], actReportBug) actSuggestIdea = MAction(translate("MenuBar", "Suggest Idea"), self.mHelpMenu) actSuggestIdea.setObjectName("Suggest Idea") self.mHelpMenu.insertAction(self.mHelpMenu.actions()[3], actSuggestIdea) actUNo = 9 while actUNo > 0: try: actUpdate = MAction(translate("MenuBar", "Update"), self.mHelpMenu) actUpdate.setObjectName("Update") self.mHelpMenu.insertAction(self.mHelpMenu.actions()[actUNo], actUpdate) break except: actUNo -= 3 else: self.mHelpMenu.addAction(translate("MenuBar", "Report Bug")).setObjectName("Report Bug") self.mHelpMenu.addAction(translate("MenuBar", "Suggest Idea")).setObjectName("Suggest Idea") self.mHelpMenu.addAction(translate("MenuBar", "Update")).setObjectName("Update") self.mHelpMenu.addAction(translate("MenuBar", "About Hamsi Manager")).setObjectName("About Hamsi Manager") self.mHelpMenu.addAction(translate("MenuBar", "About QT")).setObjectName("About QT") MObject.connect(self, SIGNAL("triggered(QAction *)"), Bars.clickedAnAction) def refreshForTableType(self): #self.mView.clear() self.mView.addActions(getMainWindow().createPopupMenu().actions()) self.refreshQuickOptions() def refreshQuickOptions(self): if getMainWindow().Menu.mQuickOptions is not None: getMainWindow().Menu.removeAction(getMainWindow().Menu.mQuickOptions.menuAction()) getMainWindow().Menu.mQuickOptions = QuickOptions.QuickOptions(self) getMainWindow().Menu.insertMenu(getMainWindow().Menu.mSettings.menuAction(), getMainWindow().Menu.mQuickOptions)
TeamTwisted/external_chromium_org
refs/heads/opti-5.1
tools/perf/page_sets/blank_page.py
43
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class BlankPage(page_module.Page): def __init__(self, url, page_set): super(BlankPage, self).__init__(url, page_set=page_set) class BlankPageSet(page_set_module.PageSet): """A single blank page.""" def __init__(self): super(BlankPageSet, self).__init__() self.AddPage(BlankPage('file://blank_page/blank_page.html', self))
yongtang/tensorflow
refs/heads/master
tensorflow/lite/toco/logging/gen_html.py
14
# Copyright 2019 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. # ============================================================================== """A utility class to generate the report HTML based on a common template.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import io import os from tensorflow.lite.toco.logging import toco_conversion_log_pb2 as _toco_conversion_log_pb2 from tensorflow.python.lib.io import file_io as _file_io from tensorflow.python.platform import resource_loader as _resource_loader html_escape_table = { "&": "&amp;", '"': "&quot;", "'": "&apos;", ">": "&gt;", "<": "&lt;", } def html_escape(text): return "".join(html_escape_table.get(c, c) for c in text) def get_input_type_from_signature(op_signature): """Parses op_signature and returns a string denoting the input tensor type. Args: op_signature: a string specifying the signature of a particular operator. The signature of an operator contains the input tensor's shape and type, output tensor's shape and type, operator's name and its version. It has the following schema: INPUT:input_1_shape::input_1_type::input_2_shape::input_2_type::.. ::OUTPUT:output_1_shape::output_1_type::output_2_shape::output_2_type:: ..::NAME:operator_name ::VERSION:operator_version An example of an operator signature is: INPUT:[1,73,73,160]::float::[64,1,1,160]::float::[64]::float:: OUTPUT:[1,73,73,64]::float::NAME:Conv::VERSION:1 Returns: A string denoting the input tensors' type. In the form of shape/type separated by comma. For example: shape:[1,73,73,160],type:float,shape:[64,1,1,160],type:float,shape:[64], type:float """ start = op_signature.find(":") end = op_signature.find("::OUTPUT") inputs = op_signature[start + 1:end] lst = inputs.split("::") out_str = "" for i in range(len(lst)): if i % 2 == 0: out_str += "shape:" else: out_str += "type:" out_str += lst[i] out_str += "," return out_str[:-1] def get_operator_type(op_name, conversion_log): if op_name in conversion_log.built_in_ops: return "BUILT-IN" elif op_name in conversion_log.custom_ops: return "CUSTOM OP" else: return "SELECT OP" class HTMLGenerator(object): """Utility class to generate an HTML report.""" def __init__(self, html_template_path, export_report_path): """Reads the HTML template content. Args: html_template_path: A string, path to the template HTML file. export_report_path: A string, path to the generated HTML report. This path should point to a '.html' file with date and time in its name. e.g. 2019-01-01-10:05.toco_report.html. Raises: IOError: File doesn't exist. """ # Load the template HTML. if not _file_io.file_exists(html_template_path): raise IOError("File '{0}' does not exist.".format(html_template_path)) with _file_io.FileIO(html_template_path, "r") as f: self.html_template = f.read() _file_io.recursive_create_dir(os.path.dirname(export_report_path)) self.export_report_path = export_report_path def generate(self, toco_conversion_log_before, toco_conversion_log_after, post_training_quant_enabled, dot_before, dot_after, toco_err_log="", tflite_graph_path=""): """Generates the HTML report and writes it to local directory. This function uses the fields in `toco_conversion_log_before` and `toco_conversion_log_after` to populate the HTML content. Certain markers (placeholders) in the HTML template are then substituted with the fields from the protos. Once finished it will write the HTML file to the specified local file path. Args: toco_conversion_log_before: A `TocoConversionLog` protobuf generated before the model is converted by TOCO. toco_conversion_log_after: A `TocoConversionLog` protobuf generated after the model is converted by TOCO. post_training_quant_enabled: A boolean, whether post-training quantization is enabled. dot_before: A string, the dot representation of the model before the conversion. dot_after: A string, the dot representation of the model after the conversion. toco_err_log: A string, the logs emitted by TOCO during conversion. Caller need to ensure that this string is properly anonymized (any kind of user data should be eliminated). tflite_graph_path: A string, the filepath to the converted TFLite model. Raises: RuntimeError: When error occurs while generating the template. """ html_dict = {} html_dict["<!--CONVERSION_STATUS-->"] = ( r'<span class="label label-danger">Fail</span>' ) if toco_err_log else r'<span class="label label-success">Success</span>' html_dict["<!--TOTAL_OPS_BEFORE_CONVERT-->"] = str( toco_conversion_log_before.model_size) html_dict["<!--TOTAL_OPS_AFTER_CONVERT-->"] = str( toco_conversion_log_after.model_size) html_dict["<!--BUILT_IN_OPS_COUNT-->"] = str( sum(toco_conversion_log_after.built_in_ops.values())) html_dict["<!--SELECT_OPS_COUNT-->"] = str( sum(toco_conversion_log_after.select_ops.values())) html_dict["<!--CUSTOM_OPS_COUNT-->"] = str( sum(toco_conversion_log_after.custom_ops.values())) html_dict["<!--POST_TRAINING_QUANT_ENABLED-->"] = ( "is" if post_training_quant_enabled else "isn't") pre_op_profile = "" post_op_profile = "" # Generate pre-conversion op profiles as a list of HTML table rows. for i in range(len(toco_conversion_log_before.op_list)): # Append operator name column. pre_op_profile += "<tr><td>" + toco_conversion_log_before.op_list[ i] + "</td>" # Append input type column. if i < len(toco_conversion_log_before.op_signatures): pre_op_profile += "<td>" + get_input_type_from_signature( toco_conversion_log_before.op_signatures[i]) + "</td></tr>" else: pre_op_profile += "<td></td></tr>" # Generate post-conversion op profiles as a list of HTML table rows. for op in toco_conversion_log_after.op_list: supported_type = get_operator_type(op, toco_conversion_log_after) post_op_profile += ("<tr><td>" + op + "</td><td>" + supported_type + "</td></tr>") html_dict["<!--REPEAT_TABLE1_ROWS-->"] = pre_op_profile html_dict["<!--REPEAT_TABLE2_ROWS-->"] = post_op_profile html_dict["<!--DOT_BEFORE_CONVERT-->"] = dot_before html_dict["<!--DOT_AFTER_CONVERT-->"] = dot_after if toco_err_log: html_dict["<!--TOCO_INFO_LOG-->"] = html_escape(toco_err_log) else: success_info = ("TFLite graph conversion successful. You can preview the " "converted model at: ") + tflite_graph_path html_dict["<!--TOCO_INFO_LOG-->"] = html_escape(success_info) # Replace each marker (as keys of html_dict) with the actual text (as values # of html_dict) in the HTML template string. template = self.html_template for marker in html_dict: template = template.replace(marker, html_dict[marker], 1) # Check that the marker text is replaced. if template.find(marker) != -1: raise RuntimeError("Could not populate marker text %r" % marker) with _file_io.FileIO(self.export_report_path, "w") as f: f.write(template) def gen_conversion_log_html(conversion_log_dir, quantization_enabled, tflite_graph_path): """Generates an HTML report about the conversion process. Args: conversion_log_dir: A string specifying the file directory of the conversion logs. It's required that before calling this function, the `conversion_log_dir` already contains the following files: `toco_log_before.pb`, `toco_log_after.pb`, `toco_tf_graph.dot`, `toco_tflite_graph.dot`. quantization_enabled: A boolean, passed from the tflite converter to indicate whether post-training quantization is enabled during conversion. tflite_graph_path: A string, the filepath to the converted TFLite model. Raises: IOError: When any of the required files doesn't exist. """ template_filename = _resource_loader.get_path_to_datafile("template.html") if not os.path.exists(template_filename): raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format( template_filename)) toco_log_before_path = os.path.join(conversion_log_dir, "toco_log_before.pb") toco_log_after_path = os.path.join(conversion_log_dir, "toco_log_after.pb") dot_before_path = os.path.join(conversion_log_dir, "toco_tf_graph.dot") dot_after_path = os.path.join(conversion_log_dir, "toco_tflite_graph.dot") if not os.path.exists(toco_log_before_path): raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format( toco_log_before_path)) if not os.path.exists(toco_log_after_path): raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format( toco_log_after_path)) if not os.path.exists(dot_before_path): raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format( dot_before_path)) if not os.path.exists(dot_after_path): raise IOError("Failed to generate HTML: file '{0}' doesn't exist.".format( dot_after_path)) html_generator = HTMLGenerator( template_filename, os.path.join(conversion_log_dir, "toco_conversion_summary.html")) # Parse the generated `TocoConversionLog`. toco_conversion_log_before = _toco_conversion_log_pb2.TocoConversionLog() toco_conversion_log_after = _toco_conversion_log_pb2.TocoConversionLog() with open(toco_log_before_path, "rb") as f: toco_conversion_log_before.ParseFromString(f.read()) with open(toco_log_after_path, "rb") as f: toco_conversion_log_after.ParseFromString(f.read()) # Read the dot file before/after the conversion. with io.open(dot_before_path, "r", encoding="utf-8") as f: dot_before = f.read().rstrip() with io.open(dot_after_path, "r", encoding="utf-8") as f: dot_after = f.read().rstrip() html_generator.generate(toco_conversion_log_before, toco_conversion_log_after, quantization_enabled, dot_before, dot_after, toco_conversion_log_after.toco_err_logs, tflite_graph_path)
aninternetof/bremen
refs/heads/master
bremenenv/lib/python3.5/site-packages/pip/req/req_set.py
338
from __future__ import absolute_import from collections import defaultdict from itertools import chain import logging import os from pip._vendor import pkg_resources from pip._vendor import requests from pip.compat import expanduser from pip.download import (is_file_url, is_dir_url, is_vcs_url, url_to_path, unpack_url) from pip.exceptions import (InstallationError, BestVersionAlreadyInstalled, DistributionNotFound, PreviousBuildDirError, HashError, HashErrors, HashUnpinned, DirectoryUrlHashUnsupported, VcsHashUnsupported, UnsupportedPythonVersion) from pip.req.req_install import InstallRequirement from pip.utils import ( display_path, dist_in_usersite, ensure_dir, normalize_path) from pip.utils.hashes import MissingHashes from pip.utils.logging import indent_log from pip.utils.packaging import check_dist_requires_python from pip.vcs import vcs from pip.wheel import Wheel logger = logging.getLogger(__name__) class Requirements(object): def __init__(self): self._keys = [] self._dict = {} def keys(self): return self._keys def values(self): return [self._dict[key] for key in self._keys] def __contains__(self, item): return item in self._keys def __setitem__(self, key, value): if key not in self._keys: self._keys.append(key) self._dict[key] = value def __getitem__(self, key): return self._dict[key] def __repr__(self): values = ['%s: %s' % (repr(k), repr(self[k])) for k in self.keys()] return 'Requirements({%s})' % ', '.join(values) class DistAbstraction(object): """Abstracts out the wheel vs non-wheel prepare_files logic. The requirements for anything installable are as follows: - we must be able to determine the requirement name (or we can't correctly handle the non-upgrade case). - we must be able to generate a list of run-time dependencies without installing any additional packages (or we would have to either burn time by doing temporary isolated installs or alternatively violate pips 'don't start installing unless all requirements are available' rule - neither of which are desirable). - for packages with setup requirements, we must also be able to determine their requirements without installing additional packages (for the same reason as run-time dependencies) - we must be able to create a Distribution object exposing the above metadata. """ def __init__(self, req_to_install): self.req_to_install = req_to_install def dist(self, finder): """Return a setuptools Dist object.""" raise NotImplementedError(self.dist) def prep_for_dist(self): """Ensure that we can get a Dist for this requirement.""" raise NotImplementedError(self.dist) def make_abstract_dist(req_to_install): """Factory to make an abstract dist object. Preconditions: Either an editable req with a source_dir, or satisfied_by or a wheel link, or a non-editable req with a source_dir. :return: A concrete DistAbstraction. """ if req_to_install.editable: return IsSDist(req_to_install) elif req_to_install.link and req_to_install.link.is_wheel: return IsWheel(req_to_install) else: return IsSDist(req_to_install) class IsWheel(DistAbstraction): def dist(self, finder): return list(pkg_resources.find_distributions( self.req_to_install.source_dir))[0] def prep_for_dist(self): # FIXME:https://github.com/pypa/pip/issues/1112 pass class IsSDist(DistAbstraction): def dist(self, finder): dist = self.req_to_install.get_dist() # FIXME: shouldn't be globally added: if dist.has_metadata('dependency_links.txt'): finder.add_dependency_links( dist.get_metadata_lines('dependency_links.txt') ) return dist def prep_for_dist(self): self.req_to_install.run_egg_info() self.req_to_install.assert_source_matches_version() class Installed(DistAbstraction): def dist(self, finder): return self.req_to_install.satisfied_by def prep_for_dist(self): pass class RequirementSet(object): def __init__(self, build_dir, src_dir, download_dir, upgrade=False, upgrade_strategy=None, ignore_installed=False, as_egg=False, target_dir=None, ignore_dependencies=False, force_reinstall=False, use_user_site=False, session=None, pycompile=True, isolated=False, wheel_download_dir=None, wheel_cache=None, require_hashes=False, ignore_requires_python=False): """Create a RequirementSet. :param wheel_download_dir: Where still-packed .whl files should be written to. If None they are written to the download_dir parameter. Separate to download_dir to permit only keeping wheel archives for pip wheel. :param download_dir: Where still packed archives should be written to. If None they are not saved, and are deleted immediately after unpacking. :param wheel_cache: The pip wheel cache, for passing to InstallRequirement. """ if session is None: raise TypeError( "RequirementSet() missing 1 required keyword argument: " "'session'" ) self.build_dir = build_dir self.src_dir = src_dir # XXX: download_dir and wheel_download_dir overlap semantically and may # be combined if we're willing to have non-wheel archives present in # the wheelhouse output by 'pip wheel'. self.download_dir = download_dir self.upgrade = upgrade self.upgrade_strategy = upgrade_strategy self.ignore_installed = ignore_installed self.force_reinstall = force_reinstall self.requirements = Requirements() # Mapping of alias: real_name self.requirement_aliases = {} self.unnamed_requirements = [] self.ignore_dependencies = ignore_dependencies self.ignore_requires_python = ignore_requires_python self.successfully_downloaded = [] self.successfully_installed = [] self.reqs_to_cleanup = [] self.as_egg = as_egg self.use_user_site = use_user_site self.target_dir = target_dir # set from --target option self.session = session self.pycompile = pycompile self.isolated = isolated if wheel_download_dir: wheel_download_dir = normalize_path(wheel_download_dir) self.wheel_download_dir = wheel_download_dir self._wheel_cache = wheel_cache self.require_hashes = require_hashes # Maps from install_req -> dependencies_of_install_req self._dependencies = defaultdict(list) def __str__(self): reqs = [req for req in self.requirements.values() if not req.comes_from] reqs.sort(key=lambda req: req.name.lower()) return ' '.join([str(req.req) for req in reqs]) def __repr__(self): reqs = [req for req in self.requirements.values()] reqs.sort(key=lambda req: req.name.lower()) reqs_str = ', '.join([str(req.req) for req in reqs]) return ('<%s object; %d requirement(s): %s>' % (self.__class__.__name__, len(reqs), reqs_str)) def add_requirement(self, install_req, parent_req_name=None, extras_requested=None): """Add install_req as a requirement to install. :param parent_req_name: The name of the requirement that needed this added. The name is used because when multiple unnamed requirements resolve to the same name, we could otherwise end up with dependency links that point outside the Requirements set. parent_req must already be added. Note that None implies that this is a user supplied requirement, vs an inferred one. :param extras_requested: an iterable of extras used to evaluate the environement markers. :return: Additional requirements to scan. That is either [] if the requirement is not applicable, or [install_req] if the requirement is applicable and has just been added. """ name = install_req.name if not install_req.match_markers(extras_requested): logger.warning("Ignoring %s: markers '%s' don't match your " "environment", install_req.name, install_req.markers) return [] # This check has to come after we filter requirements with the # environment markers. if install_req.link and install_req.link.is_wheel: wheel = Wheel(install_req.link.filename) if not wheel.supported(): raise InstallationError( "%s is not a supported wheel on this platform." % wheel.filename ) install_req.as_egg = self.as_egg install_req.use_user_site = self.use_user_site install_req.target_dir = self.target_dir install_req.pycompile = self.pycompile install_req.is_direct = (parent_req_name is None) if not name: # url or path requirement w/o an egg fragment self.unnamed_requirements.append(install_req) return [install_req] else: try: existing_req = self.get_requirement(name) except KeyError: existing_req = None if (parent_req_name is None and existing_req and not existing_req.constraint and existing_req.extras == install_req.extras and not existing_req.req.specifier == install_req.req.specifier): raise InstallationError( 'Double requirement given: %s (already in %s, name=%r)' % (install_req, existing_req, name)) if not existing_req: # Add requirement self.requirements[name] = install_req # FIXME: what about other normalizations? E.g., _ vs. -? if name.lower() != name: self.requirement_aliases[name.lower()] = name result = [install_req] else: # Assume there's no need to scan, and that we've already # encountered this for scanning. result = [] if not install_req.constraint and existing_req.constraint: if (install_req.link and not (existing_req.link and install_req.link.path == existing_req.link.path)): self.reqs_to_cleanup.append(install_req) raise InstallationError( "Could not satisfy constraints for '%s': " "installation from path or url cannot be " "constrained to a version" % name) # If we're now installing a constraint, mark the existing # object for real installation. existing_req.constraint = False existing_req.extras = tuple( sorted(set(existing_req.extras).union( set(install_req.extras)))) logger.debug("Setting %s extras to: %s", existing_req, existing_req.extras) # And now we need to scan this. result = [existing_req] # Canonicalise to the already-added object for the backref # check below. install_req = existing_req if parent_req_name: parent_req = self.get_requirement(parent_req_name) self._dependencies[parent_req].append(install_req) return result def has_requirement(self, project_name): name = project_name.lower() if (name in self.requirements and not self.requirements[name].constraint or name in self.requirement_aliases and not self.requirements[self.requirement_aliases[name]].constraint): return True return False @property def has_requirements(self): return list(req for req in self.requirements.values() if not req.constraint) or self.unnamed_requirements @property def is_download(self): if self.download_dir: self.download_dir = expanduser(self.download_dir) if os.path.exists(self.download_dir): return True else: logger.critical('Could not find download directory') raise InstallationError( "Could not find or access download directory '%s'" % display_path(self.download_dir)) return False def get_requirement(self, project_name): for name in project_name, project_name.lower(): if name in self.requirements: return self.requirements[name] if name in self.requirement_aliases: return self.requirements[self.requirement_aliases[name]] raise KeyError("No project with the name %r" % project_name) def uninstall(self, auto_confirm=False): for req in self.requirements.values(): if req.constraint: continue req.uninstall(auto_confirm=auto_confirm) req.commit_uninstall() def prepare_files(self, finder): """ Prepare process. Create temp directories, download and/or unpack files. """ # make the wheelhouse if self.wheel_download_dir: ensure_dir(self.wheel_download_dir) # If any top-level requirement has a hash specified, enter # hash-checking mode, which requires hashes from all. root_reqs = self.unnamed_requirements + self.requirements.values() require_hashes = (self.require_hashes or any(req.has_hash_options for req in root_reqs)) if require_hashes and self.as_egg: raise InstallationError( '--egg is not allowed with --require-hashes mode, since it ' 'delegates dependency resolution to setuptools and could thus ' 'result in installation of unhashed packages.') # Actually prepare the files, and collect any exceptions. Most hash # exceptions cannot be checked ahead of time, because # req.populate_link() needs to be called before we can make decisions # based on link type. discovered_reqs = [] hash_errors = HashErrors() for req in chain(root_reqs, discovered_reqs): try: discovered_reqs.extend(self._prepare_file( finder, req, require_hashes=require_hashes, ignore_dependencies=self.ignore_dependencies)) except HashError as exc: exc.req = req hash_errors.append(exc) if hash_errors: raise hash_errors def _is_upgrade_allowed(self, req): return self.upgrade and ( self.upgrade_strategy == "eager" or ( self.upgrade_strategy == "only-if-needed" and req.is_direct ) ) def _check_skip_installed(self, req_to_install, finder): """Check if req_to_install should be skipped. This will check if the req is installed, and whether we should upgrade or reinstall it, taking into account all the relevant user options. After calling this req_to_install will only have satisfied_by set to None if the req_to_install is to be upgraded/reinstalled etc. Any other value will be a dist recording the current thing installed that satisfies the requirement. Note that for vcs urls and the like we can't assess skipping in this routine - we simply identify that we need to pull the thing down, then later on it is pulled down and introspected to assess upgrade/ reinstalls etc. :return: A text reason for why it was skipped, or None. """ # Check whether to upgrade/reinstall this req or not. req_to_install.check_if_exists() if req_to_install.satisfied_by: upgrade_allowed = self._is_upgrade_allowed(req_to_install) # Is the best version is installed. best_installed = False if upgrade_allowed: # For link based requirements we have to pull the # tree down and inspect to assess the version #, so # its handled way down. if not (self.force_reinstall or req_to_install.link): try: finder.find_requirement( req_to_install, upgrade_allowed) except BestVersionAlreadyInstalled: best_installed = True except DistributionNotFound: # No distribution found, so we squash the # error - it will be raised later when we # re-try later to do the install. # Why don't we just raise here? pass if not best_installed: # don't uninstall conflict if user install and # conflict is not user install if not (self.use_user_site and not dist_in_usersite(req_to_install.satisfied_by)): req_to_install.conflicts_with = \ req_to_install.satisfied_by req_to_install.satisfied_by = None # Figure out a nice message to say why we're skipping this. if best_installed: skip_reason = 'already up-to-date' elif self.upgrade_strategy == "only-if-needed": skip_reason = 'not upgraded as not directly required' else: skip_reason = 'already satisfied' return skip_reason else: return None def _prepare_file(self, finder, req_to_install, require_hashes=False, ignore_dependencies=False): """Prepare a single requirements file. :return: A list of additional InstallRequirements to also install. """ # Tell user what we are doing for this requirement: # obtain (editable), skipping, processing (local url), collecting # (remote url or package name) if req_to_install.constraint or req_to_install.prepared: return [] req_to_install.prepared = True # ###################### # # # print log messages # # # ###################### # if req_to_install.editable: logger.info('Obtaining %s', req_to_install) else: # satisfied_by is only evaluated by calling _check_skip_installed, # so it must be None here. assert req_to_install.satisfied_by is None if not self.ignore_installed: skip_reason = self._check_skip_installed( req_to_install, finder) if req_to_install.satisfied_by: assert skip_reason is not None, ( '_check_skip_installed returned None but ' 'req_to_install.satisfied_by is set to %r' % (req_to_install.satisfied_by,)) logger.info( 'Requirement %s: %s', skip_reason, req_to_install) else: if (req_to_install.link and req_to_install.link.scheme == 'file'): path = url_to_path(req_to_install.link.url) logger.info('Processing %s', display_path(path)) else: logger.info('Collecting %s', req_to_install) with indent_log(): # ################################ # # # vcs update or unpack archive # # # ################################ # if req_to_install.editable: if require_hashes: raise InstallationError( 'The editable requirement %s cannot be installed when ' 'requiring hashes, because there is no single file to ' 'hash.' % req_to_install) req_to_install.ensure_has_source_dir(self.src_dir) req_to_install.update_editable(not self.is_download) abstract_dist = make_abstract_dist(req_to_install) abstract_dist.prep_for_dist() if self.is_download: req_to_install.archive(self.download_dir) req_to_install.check_if_exists() elif req_to_install.satisfied_by: if require_hashes: logger.debug( 'Since it is already installed, we are trusting this ' 'package without checking its hash. To ensure a ' 'completely repeatable environment, install into an ' 'empty virtualenv.') abstract_dist = Installed(req_to_install) else: # @@ if filesystem packages are not marked # editable in a req, a non deterministic error # occurs when the script attempts to unpack the # build directory req_to_install.ensure_has_source_dir(self.build_dir) # If a checkout exists, it's unwise to keep going. version # inconsistencies are logged later, but do not fail the # installation. # FIXME: this won't upgrade when there's an existing # package unpacked in `req_to_install.source_dir` if os.path.exists( os.path.join(req_to_install.source_dir, 'setup.py')): raise PreviousBuildDirError( "pip can't proceed with requirements '%s' due to a" " pre-existing build directory (%s). This is " "likely due to a previous installation that failed" ". pip is being responsible and not assuming it " "can delete this. Please delete it and try again." % (req_to_install, req_to_install.source_dir) ) req_to_install.populate_link( finder, self._is_upgrade_allowed(req_to_install), require_hashes ) # We can't hit this spot and have populate_link return None. # req_to_install.satisfied_by is None here (because we're # guarded) and upgrade has no impact except when satisfied_by # is not None. # Then inside find_requirement existing_applicable -> False # If no new versions are found, DistributionNotFound is raised, # otherwise a result is guaranteed. assert req_to_install.link link = req_to_install.link # Now that we have the real link, we can tell what kind of # requirements we have and raise some more informative errors # than otherwise. (For example, we can raise VcsHashUnsupported # for a VCS URL rather than HashMissing.) if require_hashes: # We could check these first 2 conditions inside # unpack_url and save repetition of conditions, but then # we would report less-useful error messages for # unhashable requirements, complaining that there's no # hash provided. if is_vcs_url(link): raise VcsHashUnsupported() elif is_file_url(link) and is_dir_url(link): raise DirectoryUrlHashUnsupported() if (not req_to_install.original_link and not req_to_install.is_pinned): # Unpinned packages are asking for trouble when a new # version is uploaded. This isn't a security check, but # it saves users a surprising hash mismatch in the # future. # # file:/// URLs aren't pinnable, so don't complain # about them not being pinned. raise HashUnpinned() hashes = req_to_install.hashes( trust_internet=not require_hashes) if require_hashes and not hashes: # Known-good hashes are missing for this requirement, so # shim it with a facade object that will provoke hash # computation and then raise a HashMissing exception # showing the user what the hash should be. hashes = MissingHashes() try: download_dir = self.download_dir # We always delete unpacked sdists after pip ran. autodelete_unpacked = True if req_to_install.link.is_wheel \ and self.wheel_download_dir: # when doing 'pip wheel` we download wheels to a # dedicated dir. download_dir = self.wheel_download_dir if req_to_install.link.is_wheel: if download_dir: # When downloading, we only unpack wheels to get # metadata. autodelete_unpacked = True else: # When installing a wheel, we use the unpacked # wheel. autodelete_unpacked = False unpack_url( req_to_install.link, req_to_install.source_dir, download_dir, autodelete_unpacked, session=self.session, hashes=hashes) except requests.HTTPError as exc: logger.critical( 'Could not install requirement %s because ' 'of error %s', req_to_install, exc, ) raise InstallationError( 'Could not install requirement %s because ' 'of HTTP error %s for URL %s' % (req_to_install, exc, req_to_install.link) ) abstract_dist = make_abstract_dist(req_to_install) abstract_dist.prep_for_dist() if self.is_download: # Make a .zip of the source_dir we already created. if req_to_install.link.scheme in vcs.all_schemes: req_to_install.archive(self.download_dir) # req_to_install.req is only avail after unpack for URL # pkgs repeat check_if_exists to uninstall-on-upgrade # (#14) if not self.ignore_installed: req_to_install.check_if_exists() if req_to_install.satisfied_by: if self.upgrade or self.ignore_installed: # don't uninstall conflict if user install and # conflict is not user install if not (self.use_user_site and not dist_in_usersite( req_to_install.satisfied_by)): req_to_install.conflicts_with = \ req_to_install.satisfied_by req_to_install.satisfied_by = None else: logger.info( 'Requirement already satisfied (use ' '--upgrade to upgrade): %s', req_to_install, ) # ###################### # # # parse dependencies # # # ###################### # dist = abstract_dist.dist(finder) try: check_dist_requires_python(dist) except UnsupportedPythonVersion as e: if self.ignore_requires_python: logger.warning(e.args[0]) else: req_to_install.remove_temporary_source() raise more_reqs = [] def add_req(subreq, extras_requested): sub_install_req = InstallRequirement( str(subreq), req_to_install, isolated=self.isolated, wheel_cache=self._wheel_cache, ) more_reqs.extend(self.add_requirement( sub_install_req, req_to_install.name, extras_requested=extras_requested)) # We add req_to_install before its dependencies, so that we # can refer to it when adding dependencies. if not self.has_requirement(req_to_install.name): # 'unnamed' requirements will get added here self.add_requirement(req_to_install, None) if not ignore_dependencies: if (req_to_install.extras): logger.debug( "Installing extra requirements: %r", ','.join(req_to_install.extras), ) missing_requested = sorted( set(req_to_install.extras) - set(dist.extras) ) for missing in missing_requested: logger.warning( '%s does not provide the extra \'%s\'', dist, missing ) available_requested = sorted( set(dist.extras) & set(req_to_install.extras) ) for subreq in dist.requires(available_requested): add_req(subreq, extras_requested=available_requested) # cleanup tmp src self.reqs_to_cleanup.append(req_to_install) if not req_to_install.editable and not req_to_install.satisfied_by: # XXX: --no-install leads this to report 'Successfully # downloaded' for only non-editable reqs, even though we took # action on them. self.successfully_downloaded.append(req_to_install) return more_reqs def cleanup_files(self): """Clean up files, remove builds.""" logger.debug('Cleaning up...') with indent_log(): for req in self.reqs_to_cleanup: req.remove_temporary_source() def _to_install(self): """Create the installation order. The installation order is topological - requirements are installed before the requiring thing. We break cycles at an arbitrary point, and make no other guarantees. """ # The current implementation, which we may change at any point # installs the user specified things in the order given, except when # dependencies must come earlier to achieve topological order. order = [] ordered_reqs = set() def schedule(req): if req.satisfied_by or req in ordered_reqs: return if req.constraint: return ordered_reqs.add(req) for dep in self._dependencies[req]: schedule(dep) order.append(req) for install_req in self.requirements.values(): schedule(install_req) return order def install(self, install_options, global_options=(), *args, **kwargs): """ Install everything in this set (after having downloaded and unpacked the packages) """ to_install = self._to_install() if to_install: logger.info( 'Installing collected packages: %s', ', '.join([req.name for req in to_install]), ) with indent_log(): for requirement in to_install: if requirement.conflicts_with: logger.info( 'Found existing installation: %s', requirement.conflicts_with, ) with indent_log(): requirement.uninstall(auto_confirm=True) try: requirement.install( install_options, global_options, *args, **kwargs ) except: # if install did not succeed, rollback previous uninstall if (requirement.conflicts_with and not requirement.install_succeeded): requirement.rollback_uninstall() raise else: if (requirement.conflicts_with and requirement.install_succeeded): requirement.commit_uninstall() requirement.remove_temporary_source() self.successfully_installed = to_install
wfx/epack
refs/heads/master
epack/utils.py
1
#!/usr/bin/env python # encoding: utf-8 # # 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 __future__ import absolute_import, print_function, unicode_literals import os from distutils.spawn import find_executable from efl.ecore import Exe def xdg_open(url_or_file): Exe('xdg-open "%s"' % url_or_file) def open_in_terminal(folder): term = None if os.getenv('TERM') is not None: term = find_executable(os.getenv('TERM')) if term is None: term = find_executable('terminology') if term is None: term = find_executable('x-terminal-emulator') if term is None: print("Cannot find a terminal emulator, please set your $TERM") else: if 'terminology' in term: Exe('%s --current-directory "%s"' % (term, folder)) else: # this works for gnome-terminal, dunno other terms :/ Exe('%s --working-directory "%s"' % (term, folder)) return term GITHUB = 'https://github.com/wfx/epack' AUTHORS = """ <br> <align=center> <hilight>Wolfgang Morawetz (wfx)</hilight><br> wolfgang.morawetz@gmail.com<br><br> <hilight>Davide Andreoli (davemds)</hilight><br> dave@gurumeditation.it<br><br> </align> """ LICENSE = """ <align=center> <hilight> GNU GENERAL PUBLIC LICENSE<br> Version 3, 29 June 2007<br><br> </hilight> 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.<br><br> 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.<br><br> You should have received a copy of the GNU General Public License along with this program. If not, see<br> <link><a href=http://www.gnu.org/licenses>http://www.gnu.org/licenses/</a></link> </align> """ INFO = """ <align=center> <hilight>Epack</hilight> is an archive manager for the Enlightenment desktop.<br> <br> With <hilight>Epack</hilight> you can:<br> View the content of an archive.<br> Extract files from the archive.<br> Extract into a different folder.<br> Create archive folder.<br> Delete archive after extraction.<br> feed youre kitty.<br> <br> </align> """
arista-eosplus/ansible-modules-extras
refs/heads/devel
packaging/os/macports.py
161
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Jimmy Tang <jcftang@gmail.com> # Based on okpg (Patrick Pelletier <pp.pelletier@gmail.com>), pacman # (Afterburn) and pkgin (Shaun Zinck) modules # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: macports author: "Jimmy Tang (@jcftang)" short_description: Package manager for MacPorts description: - Manages MacPorts packages version_added: "1.1" options: name: description: - name of package to install/remove required: true state: description: - state of the package choices: [ 'present', 'absent', 'active', 'inactive' ] required: false default: present update_cache: description: - update the package db first required: false default: "no" choices: [ "yes", "no" ] notes: [] ''' EXAMPLES = ''' - macports: name=foo state=present - macports: name=foo state=present update_cache=yes - macports: name=foo state=absent - macports: name=foo state=active - macports: name=foo state=inactive ''' import pipes def update_package_db(module, port_path): """ Updates packages list. """ rc, out, err = module.run_command("%s sync" % port_path) if rc != 0: module.fail_json(msg="could not update package db") def query_package(module, port_path, name, state="present"): """ Returns whether a package is installed or not. """ if state == "present": rc, out, err = module.run_command("%s installed | grep -q ^.*%s" % (pipes.quote(port_path), pipes.quote(name)), use_unsafe_shell=True) if rc == 0: return True return False elif state == "active": rc, out, err = module.run_command("%s installed %s | grep -q active" % (pipes.quote(port_path), pipes.quote(name)), use_unsafe_shell=True) if rc == 0: return True return False def remove_packages(module, port_path, packages): """ Uninstalls one or more packages if installed. """ remove_c = 0 # Using a for loop incase of error, we can report the package that failed for package in packages: # Query the package first, to see if we even need to remove if not query_package(module, port_path, package): continue rc, out, err = module.run_command("%s uninstall %s" % (port_path, package)) if query_package(module, port_path, package): module.fail_json(msg="failed to remove %s: %s" % (package, out)) remove_c += 1 if remove_c > 0: module.exit_json(changed=True, msg="removed %s package(s)" % remove_c) module.exit_json(changed=False, msg="package(s) already absent") def install_packages(module, port_path, packages): """ Installs one or more packages if not already installed. """ install_c = 0 for package in packages: if query_package(module, port_path, package): continue rc, out, err = module.run_command("%s install %s" % (port_path, package)) if not query_package(module, port_path, package): module.fail_json(msg="failed to install %s: %s" % (package, out)) install_c += 1 if install_c > 0: module.exit_json(changed=True, msg="installed %s package(s)" % (install_c)) module.exit_json(changed=False, msg="package(s) already present") def activate_packages(module, port_path, packages): """ Activate a package if it's inactive. """ activate_c = 0 for package in packages: if not query_package(module, port_path, package): module.fail_json(msg="failed to activate %s, package(s) not present" % (package)) if query_package(module, port_path, package, state="active"): continue rc, out, err = module.run_command("%s activate %s" % (port_path, package)) if not query_package(module, port_path, package, state="active"): module.fail_json(msg="failed to activate %s: %s" % (package, out)) activate_c += 1 if activate_c > 0: module.exit_json(changed=True, msg="activated %s package(s)" % (activate_c)) module.exit_json(changed=False, msg="package(s) already active") def deactivate_packages(module, port_path, packages): """ Deactivate a package if it's active. """ deactivated_c = 0 for package in packages: if not query_package(module, port_path, package): module.fail_json(msg="failed to activate %s, package(s) not present" % (package)) if not query_package(module, port_path, package, state="active"): continue rc, out, err = module.run_command("%s deactivate %s" % (port_path, package)) if query_package(module, port_path, package, state="active"): module.fail_json(msg="failed to deactivated %s: %s" % (package, out)) deactivated_c += 1 if deactivated_c > 0: module.exit_json(changed=True, msg="deactivated %s package(s)" % (deactivated_c)) module.exit_json(changed=False, msg="package(s) already inactive") def main(): module = AnsibleModule( argument_spec = dict( name = dict(aliases=["pkg"], required=True), state = dict(default="present", choices=["present", "installed", "absent", "removed", "active", "inactive"]), update_cache = dict(default="no", aliases=["update-cache"], type='bool') ) ) port_path = module.get_bin_path('port', True, ['/opt/local/bin']) p = module.params if p["update_cache"]: update_package_db(module, port_path) pkgs = p["name"].split(",") if p["state"] in ["present", "installed"]: install_packages(module, port_path, pkgs) elif p["state"] in ["absent", "removed"]: remove_packages(module, port_path, pkgs) elif p["state"] == "active": activate_packages(module, port_path, pkgs) elif p["state"] == "inactive": deactivate_packages(module, port_path, pkgs) # import module snippets from ansible.module_utils.basic import * main()
tktrungna/leetcode
refs/heads/master
Python/longest-increasing-subsequence.py
1
""" QUESTION: Given an unsorted array of integers, find the length of longest increasing subsequence. For example, Given [10, 9, 2, 5, 3, 7, 101, 18], The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length. Your algorithm should run in O(n^2) complexity. Follow up: Could you improve it to O(n log n) time complexity? ANSWER DP, BS for fill DP values """ class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ size = len(nums) dp = [1] * size for x in range(size): for y in range(x): if nums[x] > nums[y]: dp[x] = max(dp[x], dp[y] + 1) return max(dp) if dp else 0 def lengthOfLIS_2(self, nums): """ :type nums: List[int] :rtype: int """ size = len(nums) dp = [] for x in range(size): low, high = 0, len(dp) - 1 while low <= high: mid = (low + high) / 2 if dp[mid] >= nums[x]: high = mid - 1 else: low = mid + 1 if low >= len(dp): dp.append(nums[x]) else: dp[low] = nums[x] return len(dp) if __name__ == '__main__': print Solution().lengthOfLIS([10, 9, 2, 5, 3, 7, 101, 18])
feroda/django
refs/heads/master
django/core/cache/backends/base.py
15
"Base Cache class." from __future__ import unicode_literals import time import warnings from django.core.exceptions import DjangoRuntimeWarning, ImproperlyConfigured from django.utils.module_loading import import_string class InvalidCacheBackendError(ImproperlyConfigured): pass class CacheKeyWarning(DjangoRuntimeWarning): pass # Stub class to ensure not passing in a `timeout` argument results in # the default timeout DEFAULT_TIMEOUT = object() # Memcached does not accept keys longer than this. MEMCACHE_MAX_KEY_LENGTH = 250 def default_key_func(key, key_prefix, version): """ Default function to generate keys. Constructs the key used by all other methods. By default it prepends the `key_prefix'. KEY_FUNCTION can be used to specify an alternate function with custom key making behavior. """ return '%s:%s:%s' % (key_prefix, version, key) def get_key_func(key_func): """ Function to decide which key function to use. Defaults to ``default_key_func``. """ if key_func is not None: if callable(key_func): return key_func else: return import_string(key_func) return default_key_func class BaseCache(object): def __init__(self, params): timeout = params.get('timeout', params.get('TIMEOUT', 300)) if timeout is not None: try: timeout = int(timeout) except (ValueError, TypeError): timeout = 300 self.default_timeout = timeout options = params.get('OPTIONS', {}) max_entries = params.get('max_entries', options.get('MAX_ENTRIES', 300)) try: self._max_entries = int(max_entries) except (ValueError, TypeError): self._max_entries = 300 cull_frequency = params.get('cull_frequency', options.get('CULL_FREQUENCY', 3)) try: self._cull_frequency = int(cull_frequency) except (ValueError, TypeError): self._cull_frequency = 3 self.key_prefix = params.get('KEY_PREFIX', '') self.version = params.get('VERSION', 1) self.key_func = get_key_func(params.get('KEY_FUNCTION', None)) def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT): """ Returns the timeout value usable by this backend based upon the provided timeout. """ if timeout == DEFAULT_TIMEOUT: timeout = self.default_timeout elif timeout == 0: # ticket 21147 - avoid time.time() related precision issues timeout = -1 return None if timeout is None else time.time() + timeout def make_key(self, key, version=None): """Constructs the key used by all other methods. By default it uses the key_func to generate a key (which, by default, prepends the `key_prefix' and 'version'). An different key function can be provided at the time of cache construction; alternatively, you can subclass the cache backend to provide custom key making behavior. """ if version is None: version = self.version new_key = self.key_func(key, self.key_prefix, version) return new_key def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): """ Set a value in the cache if the key does not already exist. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. Returns True if the value was stored, False otherwise. """ raise NotImplementedError('subclasses of BaseCache must provide an add() method') def get(self, key, default=None, version=None): """ Fetch a given key from the cache. If the key does not exist, return default, which itself defaults to None. """ raise NotImplementedError('subclasses of BaseCache must provide a get() method') def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): """ Set a value in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. """ raise NotImplementedError('subclasses of BaseCache must provide a set() method') def delete(self, key, version=None): """ Delete a key from the cache, failing silently. """ raise NotImplementedError('subclasses of BaseCache must provide a delete() method') def get_many(self, keys, version=None): """ Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values. Returns a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the response dict. """ d = {} for k in keys: val = self.get(k, version=version) if val is not None: d[k] = val return d def get_or_set(self, key, default=None, timeout=DEFAULT_TIMEOUT, version=None): """ Fetch a given key from the cache. If the key does not exist, the key is added and set to the default value. The default value can also be any callable. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. Returns the value of the key stored or retrieved on success, False on error. """ if default is None: raise ValueError('You need to specify a value.') val = self.get(key, version=version) if val is None: if callable(default): default = default() val = self.add(key, default, timeout=timeout, version=version) if val: return self.get(key, version=version) return val def has_key(self, key, version=None): """ Returns True if the key is in the cache and has not expired. """ return self.get(key, version=version) is not None def incr(self, key, delta=1, version=None): """ Add delta to value in the cache. If the key does not exist, raise a ValueError exception. """ value = self.get(key, version=version) if value is None: raise ValueError("Key '%s' not found" % key) new_value = value + delta self.set(key, new_value, version=version) return new_value def decr(self, key, delta=1, version=None): """ Subtract delta from value in the cache. If the key does not exist, raise a ValueError exception. """ return self.incr(key, -delta, version=version) def __contains__(self, key): """ Returns True if the key is in the cache and has not expired. """ # This is a separate method, rather than just a copy of has_key(), # so that it always has the same functionality as has_key(), even # if a subclass overrides it. return self.has_key(key) def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None): """ Set a bunch of values in the cache at once from a dict of key/value pairs. For certain backends (memcached), this is much more efficient than calling set() multiple times. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. """ for key, value in data.items(): self.set(key, value, timeout=timeout, version=version) def delete_many(self, keys, version=None): """ Set a bunch of values in the cache at once. For certain backends (memcached), this is much more efficient than calling delete() multiple times. """ for key in keys: self.delete(key, version=version) def clear(self): """Remove *all* values from the cache at once.""" raise NotImplementedError('subclasses of BaseCache must provide a clear() method') def validate_key(self, key): """ Warn about keys that would not be portable to the memcached backend. This encourages (but does not force) writing backend-portable cache code. """ if len(key) > MEMCACHE_MAX_KEY_LENGTH: warnings.warn('Cache key will cause errors if used with memcached: ' '%s (longer than %s)' % (key, MEMCACHE_MAX_KEY_LENGTH), CacheKeyWarning) for char in key: if ord(char) < 33 or ord(char) == 127: warnings.warn('Cache key contains characters that will cause ' 'errors if used with memcached: %r' % key, CacheKeyWarning) def incr_version(self, key, delta=1, version=None): """Adds delta to the cache version for the supplied key. Returns the new version. """ if version is None: version = self.version value = self.get(key, version=version) if value is None: raise ValueError("Key '%s' not found" % key) self.set(key, value, version=version + delta) self.delete(key, version=version) return version + delta def decr_version(self, key, delta=1, version=None): """Substracts delta from the cache version for the supplied key. Returns the new version. """ return self.incr_version(key, -delta, version) def close(self, **kwargs): """Close the cache connection""" pass
nolanliou/tensorflow
refs/heads/master
tensorflow/python/kernel_tests/manip_ops_test.py
4
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for manip_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import errors_impl from tensorflow.python.framework import test_util from tensorflow.python.ops import gradient_checker from tensorflow.python.ops import manip_ops from tensorflow.python.platform import test as test_lib # pylint: disable=g-import-not-at-top try: from distutils.version import StrictVersion as Version # numpy.roll for multiple shifts was introduced in numpy version 1.12.0 NP_ROLL_CAN_MULTISHIFT = Version(np.version.version) >= Version("1.12.0") except ImportError: NP_ROLL_CAN_MULTISHIFT = False # pylint: enable=g-import-not-at-top class RollTest(test_util.TensorFlowTestCase): def _testRoll(self, np_input, shift, axis): expected_roll = np.roll(np_input, shift, axis) with self.test_session(): roll = manip_ops.roll(np_input, shift, axis) self.assertAllEqual(roll.eval(), expected_roll) def _testGradient(self, np_input, shift, axis): with self.test_session(): inx = constant_op.constant(np_input.tolist()) xs = list(np_input.shape) y = manip_ops.roll(inx, shift, axis) # Expected y's shape to be the same ys = xs jacob_t, jacob_n = gradient_checker.compute_gradient( inx, xs, y, ys, x_init_value=np_input) self.assertAllClose(jacob_t, jacob_n, rtol=1e-5, atol=1e-5) def _testAll(self, np_input, shift, axis): self._testRoll(np_input, shift, axis) if np_input.dtype == np.float32: self._testGradient(np_input, shift, axis) def testIntTypes(self): for t in [np.int32, np.int64]: self._testAll(np.random.randint(-100, 100, (5)).astype(t), 3, 0) if NP_ROLL_CAN_MULTISHIFT: self._testAll( np.random.randint(-100, 100, (4, 4, 3)).astype(t), [1, -2, 3], [0, 1, 2]) self._testAll( np.random.randint(-100, 100, (4, 2, 1, 3)).astype(t), [0, 1, -2], [1, 2, 3]) def testFloatTypes(self): for t in [np.float32, np.float64]: self._testAll(np.random.rand(5).astype(t), 2, 0) if NP_ROLL_CAN_MULTISHIFT: self._testAll(np.random.rand(3, 4).astype(t), [1, 2], [1, 0]) self._testAll(np.random.rand(1, 3, 4).astype(t), [1, 0, -3], [0, 1, 2]) def testComplexTypes(self): for t in [np.complex64, np.complex128]: x = np.random.rand(4, 4).astype(t) self._testAll(x + 1j * x, 2, 0) if NP_ROLL_CAN_MULTISHIFT: x = np.random.rand(2, 5).astype(t) self._testAll(x + 1j * x, [1, 2], [1, 0]) x = np.random.rand(3, 2, 1, 1).astype(t) self._testAll(x + 1j * x, [2, 1, 1, 0], [0, 3, 1, 2]) def testRollInputMustVectorHigherRaises(self): tensor = 7 shift = 1 axis = 0 with self.test_session(): with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, "input must be 1-D or higher"): manip_ops.roll(tensor, shift, axis).eval() def testRollAxisMustBeScalarOrVectorRaises(self): tensor = [[1, 2], [3, 4]] shift = 1 axis = [[0, 1]] with self.test_session(): with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, "axis must be a scalar or a 1-D vector"): manip_ops.roll(tensor, shift, axis).eval() def testRollShiftMustBeScalarOrVectorRaises(self): tensor = [[1, 2], [3, 4]] shift = [[0, 1]] axis = 1 with self.test_session(): with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, "shift must be a scalar or a 1-D vector"): manip_ops.roll(tensor, shift, axis).eval() def testRollShiftAndAxisMustBeSameSizeRaises(self): tensor = [[1, 2], [3, 4]] shift = [1] axis = [0, 1] with self.test_session(): with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, "shift and axis must have the same size"): manip_ops.roll(tensor, shift, axis).eval() def testRollAxisOutOfRangeRaises(self): tensor = [1, 2] shift = 1 axis = 1 with self.test_session(): with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, "is out of range"): manip_ops.roll(tensor, shift, axis).eval() if __name__ == "__main__": test_lib.main()
saurabh6790/omn-app
refs/heads/master
hr/report/employee_leave_balance/employee_leave_balance.py
30
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import webnotes from webnotes.widgets.reportview import execute as runreport def execute(filters=None): if not filters: filters = {} employee_filters = filters.get("company") and \ [["Employee", "company", "=", filters.get("company")]] or None employees = runreport(doctype="Employee", fields=["name", "employee_name", "department"], filters=employee_filters) leave_types = webnotes.conn.sql_list("select name from `tabLeave Type`") if filters.get("fiscal_year"): fiscal_years = [filters["fiscal_year"]] else: fiscal_years = webnotes.conn.sql_list("select name from `tabFiscal Year` order by name desc") employee_in = '", "'.join([e.name for e in employees]) allocations = webnotes.conn.sql("""select employee, fiscal_year, leave_type, total_leaves_allocated from `tabLeave Allocation` where docstatus=1 and employee in ("%s")""" % employee_in, as_dict=True) applications = webnotes.conn.sql("""select employee, fiscal_year, leave_type, SUM(total_leave_days) as leaves from `tabLeave Application` where status="Approved" and docstatus = 1 and employee in ("%s") group by employee, fiscal_year, leave_type""" % employee_in, as_dict=True) columns = [ "Fiscal Year", "Employee:Link/Employee:150", "Employee Name::200", "Department::150" ] for leave_type in leave_types: columns.append(leave_type + " Allocated:Float") columns.append(leave_type + " Taken:Float") columns.append(leave_type + " Balance:Float") data = {} for d in allocations: data.setdefault((d.fiscal_year, d.employee, d.leave_type), webnotes._dict()).allocation = d.total_leaves_allocated for d in applications: data.setdefault((d.fiscal_year, d.employee, d.leave_type), webnotes._dict()).leaves = d.leaves result = [] for fiscal_year in fiscal_years: for employee in employees: row = [fiscal_year, employee.name, employee.employee_name, employee.department] result.append(row) for leave_type in leave_types: tmp = data.get((fiscal_year, employee.name, leave_type), webnotes._dict()) row.append(tmp.allocation or 0) row.append(tmp.leaves or 0) row.append((tmp.allocation or 0) - (tmp.leaves or 0)) return columns, result
bzero/statsmodels
refs/heads/master
statsmodels/sandbox/tsa/examples/ex_mle_arma.py
33
# -*- coding: utf-8 -*- """ TODO: broken because of changes to arguments and import paths fixing this needs a closer look Created on Thu Feb 11 23:41:53 2010 Author: josef-pktd copyright: Simplified BSD see license.txt """ from __future__ import print_function import numpy as np from numpy.testing import assert_almost_equal import matplotlib.pyplot as plt import numdifftools as ndt import statsmodels.api as sm from statsmodels.sandbox import tsa from statsmodels.tsa.arma_mle import Arma # local import from statsmodels.tsa.arima_process import arma_generate_sample examples = ['arma'] if 'arma' in examples: print("\nExample 1") print('----------') ar = [1.0, -0.8] ma = [1.0, 0.5] y1 = arma_generate_sample(ar,ma,1000,0.1) y1 -= y1.mean() #no mean correction/constant in estimation so far arma1 = Arma(y1) arma1.nar = 1 arma1.nma = 1 arma1res = arma1.fit_mle(order=(1,1), method='fmin') print(arma1res.params) #Warning need new instance otherwise results carry over arma2 = Arma(y1) arma2.nar = 1 arma2.nma = 1 res2 = arma2.fit(method='bfgs') print(res2.params) print(res2.model.hessian(res2.params)) print(ndt.Hessian(arma1.loglike, stepMax=1e-2)(res2.params)) arest = tsa.arima.ARIMA(y1) resls = arest.fit((1,0,1)) print(resls[0]) print(resls[1]) print('\nparameter estimate - comparing methods') print('---------------------------------------') print('parameter of DGP ar(1), ma(1), sigma_error') print([-0.8, 0.5, 0.1]) print('mle with fmin') print(arma1res.params) print('mle with bfgs') print(res2.params) print('cond. least squares uses optim.leastsq ?') errls = arest.error_estimate print(resls[0], np.sqrt(np.dot(errls,errls)/errls.shape[0])) err = arma1.geterrors(res2.params) print('cond least squares parameter cov') #print(np.dot(err,err)/err.shape[0] * resls[1]) #errls = arest.error_estimate print(np.dot(errls,errls)/errls.shape[0] * resls[1]) # print('fmin hessian') # print(arma1res.model.optimresults['Hopt'][:2,:2]) print('bfgs hessian') print(res2.model.optimresults['Hopt'][:2,:2]) print('numdifftools inverse hessian') print(-np.linalg.inv(ndt.Hessian(arma1.loglike, stepMax=1e-2)(res2.params))[:2,:2]) print('\nFitting Arma(1,1) to squared data') arma3 = Arma(y1**2) res3 = arma3.fit(method='bfgs') print(res3.params) print('\nFitting Arma(3,3) to data from DGP Arma(1,1)') arma4 = Arma(y1) arma4.nar = 3 arma4.nma = 3 #res4 = arma4.fit(method='bfgs') res4 = arma4.fit(start_params=[-0.5, -0.1,-0.1,0.2,0.1,0.1,0.5]) print(res4.params) print('numdifftools inverse hessian') pcov = -np.linalg.inv(ndt.Hessian(arma4.loglike, stepMax=1e-2)(res4.params)) #print(pcov) print('standard error of parameter estimate from Hessian') pstd = np.sqrt(np.diag(pcov)) print(pstd) print('t-values') print(res4.params/pstd) print('eigenvalues of pcov:') print(np.linalg.eigh(pcov)[0]) print('sometimes they are negative') print("\nExample 2 - DGP is Arma(3,3)") print('-----------------------------') ar = [1.0, -0.6, -0.2, -0.1] ma = [1.0, 0.5, 0.1, 0.1] y2 = arest.generate_sample(ar,ma,1000,0.1) y2 -= y2.mean() #no mean correction/constant in estimation so far print('\nFitting Arma(3,3) to data from DGP Arma(3,3)') arma4 = Arma(y2) arma4.nar = 3 arma4.nma = 3 #res4 = arma4.fit(method='bfgs') print('\ntrue parameters') print('ar', ar[1:]) print('ma', ma[1:]) res4 = arma4.fit(start_params=[-0.5, -0.1,-0.1,0.2,0.1,0.1,0.5]) print(res4.params) print('numdifftools inverse hessian') pcov = -np.linalg.inv(ndt.Hessian(arma4.loglike, stepMax=1e-2)(res4.params)) #print(pcov) print('standard error of parameter estimate from Hessian') pstd = np.sqrt(np.diag(pcov)) print(pstd) print('t-values') print(res4.params/pstd) print('eigenvalues of pcov:') print(np.linalg.eigh(pcov)[0]) print('sometimes they are negative') arma6 = Arma(y2) arma6.nar = 3 arma6.nma = 3 res6 = arma6.fit(start_params=[-0.5, -0.1,-0.1,0.2,0.1,0.1,0.5], method='bfgs') print('\nmle with bfgs') print(res6.params) print('pstd with bfgs hessian') hopt = res6.model.optimresults['Hopt'] print(np.sqrt(np.diag(hopt))) #fmin estimates for coefficients in ARMA(3,3) look good #but not inverse Hessian, sometimes negative values for variance
klusark/android_external_chromium_org
refs/heads/cm-11.0
tools/telemetry/telemetry/core/extension_to_load.py
29
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from telemetry.core.chrome import crx_id class ExtensionPathNonExistentException(Exception): pass class MissingPublicKeyException(Exception): pass class ExtensionToLoad(object): def __init__(self, path, browser_type, is_component=False): if not os.path.isdir(path): raise ExtensionPathNonExistentException( 'Extension path not a directory %s' % path) self._path = path self._local_path = path self._is_component = is_component if is_component and not crx_id.HasPublicKey(path): raise MissingPublicKeyException( 'Component extension %s must have a public key' % path) # It is possible that we are running telemetry on Windows targeting # a remote CrOS or Android device. In this case, we need the # browser_type argument to determine how we should encode # the extension path. self._is_win = (os.name == 'nt' and not (browser_type.startswith('android') or browser_type.startswith('cros'))) @property def extension_id(self): """Unique extension id of this extension.""" if crx_id.HasPublicKey(self._path): # Calculate extension id from the public key. return crx_id.GetCRXAppID(os.path.realpath(self._path)) else: # Calculate extension id based on the path on the device. return crx_id.GetCRXAppID( os.path.realpath(self._local_path), from_file_path=True, is_win_path=self._is_win) @property def path(self): """Path to extension source directory.""" return self._path @property def local_path(self): """Path to extension destination directory, for remote instances of chrome""" return self._local_path @local_path.setter def local_path(self, local_path): self._local_path = local_path @property def is_component(self): """Whether this extension should be loaded as a component extension.""" return self._is_component
ehashman/oh-mainline
refs/heads/master
vendor/packages/Django/django/contrib/gis/tests/__init__.py
113
from django.conf import settings from django.test.simple import build_suite, DjangoTestSuiteRunner from django.utils import unittest from .test_geoforms import GeometryFieldTest from .test_measure import DistanceTest, AreaTest from .test_spatialrefsys import SpatialRefSysTest def geo_apps(namespace=True, runtests=False): """ Returns a list of GeoDjango test applications that reside in `django.contrib.gis.tests` that can be used with the current database and the spatial libraries that are installed. """ from django.db import connection from django.contrib.gis.geos import GEOS_PREPARE from django.contrib.gis.gdal import HAS_GDAL apps = ['geoapp', 'relatedapp'] # No distance queries on MySQL. if not connection.ops.mysql: apps.append('distapp') # Test geography support with PostGIS 1.5+. if connection.ops.postgis and connection.ops.geography: apps.append('geogapp') # The following GeoDjango test apps depend on GDAL support. if HAS_GDAL: # Geographic admin, LayerMapping, and ogrinspect test apps # all require GDAL. apps.extend(['geoadmin', 'layermap', 'inspectapp']) # 3D apps use LayerMapping, which uses GDAL and require GEOS 3.1+. if connection.ops.postgis and GEOS_PREPARE: apps.append('geo3d') if runtests: return [('django.contrib.gis.tests', app) for app in apps] elif namespace: return ['django.contrib.gis.tests.%s' % app for app in apps] else: return apps def geodjango_suite(apps=True): """ Returns a TestSuite consisting only of GeoDjango tests that can be run. """ import sys from django.db.models import get_app suite = unittest.TestSuite() # Adding the GEOS tests. from django.contrib.gis.geos import tests as geos_tests suite.addTest(geos_tests.suite()) # Adding GDAL tests, and any test suite that depends on GDAL, to the # suite if GDAL is available. from django.contrib.gis.gdal import HAS_GDAL if HAS_GDAL: from django.contrib.gis.gdal import tests as gdal_tests suite.addTest(gdal_tests.suite()) else: sys.stderr.write('GDAL not available - no tests requiring GDAL will be run.\n') # Add GeoIP tests to the suite, if the library and data is available. from django.contrib.gis.geoip import HAS_GEOIP if HAS_GEOIP and hasattr(settings, 'GEOIP_PATH'): from django.contrib.gis.geoip import tests as geoip_tests suite.addTest(geoip_tests.suite()) # Finally, adding the suites for each of the GeoDjango test apps. if apps: for app_name in geo_apps(namespace=False): suite.addTest(build_suite(get_app(app_name))) return suite class GeoDjangoTestSuiteRunner(DjangoTestSuiteRunner): def setup_test_environment(self, **kwargs): super(GeoDjangoTestSuiteRunner, self).setup_test_environment(**kwargs) # Saving original values of INSTALLED_APPS, ROOT_URLCONF, and SITE_ID. self.old_installed = getattr(settings, 'INSTALLED_APPS', None) self.old_root_urlconf = getattr(settings, 'ROOT_URLCONF', '') self.old_site_id = getattr(settings, 'SITE_ID', None) # Constructing the new INSTALLED_APPS, and including applications # within the GeoDjango test namespace. new_installed = [ 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.gis', ] # Calling out to `geo_apps` to get GeoDjango applications supported # for testing. new_installed.extend(geo_apps()) settings.INSTALLED_APPS = list(self.old_installed) + new_installed # SITE_ID needs to be set settings.SITE_ID = 1 # ROOT_URLCONF needs to be set, else `AttributeErrors` are raised # when TestCases are torn down that have `urls` defined. settings.ROOT_URLCONF = '' def teardown_test_environment(self, **kwargs): super(GeoDjangoTestSuiteRunner, self).teardown_test_environment(**kwargs) settings.INSTALLED_APPS = self.old_installed settings.ROOT_URLCONF = self.old_root_urlconf settings.SITE_ID = self.old_site_id def build_suite(self, test_labels, extra_tests=None, **kwargs): return geodjango_suite()
gnuhub/intellij-community
refs/heads/master
plugins/hg4idea/testData/bin/hgext/rebase.py
90
# rebase.py - rebasing feature for mercurial # # Copyright 2008 Stefano Tortarolo <stefano.tortarolo at gmail dot com> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. '''command to move sets of revisions to a different ancestor This extension lets you rebase changesets in an existing Mercurial repository. For more information: http://mercurial.selenic.com/wiki/RebaseExtension ''' from mercurial import hg, util, repair, merge, cmdutil, commands, bookmarks from mercurial import extensions, patch, scmutil, phases, obsolete, error from mercurial.commands import templateopts from mercurial.node import nullrev from mercurial.lock import release from mercurial.i18n import _ import os, errno nullmerge = -2 revignored = -3 cmdtable = {} command = cmdutil.command(cmdtable) testedwith = 'internal' @command('rebase', [('s', 'source', '', _('rebase from the specified changeset'), _('REV')), ('b', 'base', '', _('rebase from the base of the specified changeset ' '(up to greatest common ancestor of base and dest)'), _('REV')), ('r', 'rev', [], _('rebase these revisions'), _('REV')), ('d', 'dest', '', _('rebase onto the specified changeset'), _('REV')), ('', 'collapse', False, _('collapse the rebased changesets')), ('m', 'message', '', _('use text as collapse commit message'), _('TEXT')), ('e', 'edit', False, _('invoke editor on commit messages')), ('l', 'logfile', '', _('read collapse commit message from file'), _('FILE')), ('', 'keep', False, _('keep original changesets')), ('', 'keepbranches', False, _('keep original branch names')), ('D', 'detach', False, _('(DEPRECATED)')), ('t', 'tool', '', _('specify merge tool')), ('c', 'continue', False, _('continue an interrupted rebase')), ('a', 'abort', False, _('abort an interrupted rebase'))] + templateopts, _('[-s REV | -b REV] [-d REV] [OPTION]')) def rebase(ui, repo, **opts): """move changeset (and descendants) to a different branch Rebase uses repeated merging to graft changesets from one part of history (the source) onto another (the destination). This can be useful for linearizing *local* changes relative to a master development tree. You should not rebase changesets that have already been shared with others. Doing so will force everybody else to perform the same rebase or they will end up with duplicated changesets after pulling in your rebased changesets. In its default configuration, Mercurial will prevent you from rebasing published changes. See :hg:`help phases` for details. If you don't specify a destination changeset (``-d/--dest``), rebase uses the tipmost head of the current named branch as the destination. (The destination changeset is not modified by rebasing, but new changesets are added as its descendants.) You can specify which changesets to rebase in two ways: as a "source" changeset or as a "base" changeset. Both are shorthand for a topologically related set of changesets (the "source branch"). If you specify source (``-s/--source``), rebase will rebase that changeset and all of its descendants onto dest. If you specify base (``-b/--base``), rebase will select ancestors of base back to but not including the common ancestor with dest. Thus, ``-b`` is less precise but more convenient than ``-s``: you can specify any changeset in the source branch, and rebase will select the whole branch. If you specify neither ``-s`` nor ``-b``, rebase uses the parent of the working directory as the base. For advanced usage, a third way is available through the ``--rev`` option. It allows you to specify an arbitrary set of changesets to rebase. Descendants of revs you specify with this option are not automatically included in the rebase. By default, rebase recreates the changesets in the source branch as descendants of dest and then destroys the originals. Use ``--keep`` to preserve the original source changesets. Some changesets in the source branch (e.g. merges from the destination branch) may be dropped if they no longer contribute any change. One result of the rules for selecting the destination changeset and source branch is that, unlike ``merge``, rebase will do nothing if you are at the latest (tipmost) head of a named branch with two heads. You need to explicitly specify source and/or destination (or ``update`` to the other head, if it's the head of the intended source branch). If a rebase is interrupted to manually resolve a merge, it can be continued with --continue/-c or aborted with --abort/-a. Returns 0 on success, 1 if nothing to rebase. """ originalwd = target = None activebookmark = None external = nullrev state = {} skipped = set() targetancestors = set() editor = None if opts.get('edit'): editor = cmdutil.commitforceeditor lock = wlock = None try: wlock = repo.wlock() lock = repo.lock() # Validate input and define rebasing points destf = opts.get('dest', None) srcf = opts.get('source', None) basef = opts.get('base', None) revf = opts.get('rev', []) contf = opts.get('continue') abortf = opts.get('abort') collapsef = opts.get('collapse', False) collapsemsg = cmdutil.logmessage(ui, opts) extrafn = opts.get('extrafn') # internal, used by e.g. hgsubversion keepf = opts.get('keep', False) keepbranchesf = opts.get('keepbranches', False) # keepopen is not meant for use on the command line, but by # other extensions keepopen = opts.get('keepopen', False) if collapsemsg and not collapsef: raise util.Abort( _('message can only be specified with collapse')) if contf or abortf: if contf and abortf: raise util.Abort(_('cannot use both abort and continue')) if collapsef: raise util.Abort( _('cannot use collapse with continue or abort')) if srcf or basef or destf: raise util.Abort( _('abort and continue do not allow specifying revisions')) if opts.get('tool', False): ui.warn(_('tool option will be ignored\n')) (originalwd, target, state, skipped, collapsef, keepf, keepbranchesf, external, activebookmark) = restorestatus(repo) if abortf: return abort(repo, originalwd, target, state) else: if srcf and basef: raise util.Abort(_('cannot specify both a ' 'source and a base')) if revf and basef: raise util.Abort(_('cannot specify both a ' 'revision and a base')) if revf and srcf: raise util.Abort(_('cannot specify both a ' 'revision and a source')) cmdutil.bailifchanged(repo) if not destf: # Destination defaults to the latest revision in the # current branch branch = repo[None].branch() dest = repo[branch] else: dest = scmutil.revsingle(repo, destf) if revf: rebaseset = repo.revs('%lr', revf) elif srcf: src = scmutil.revrange(repo, [srcf]) rebaseset = repo.revs('(%ld)::', src) else: base = scmutil.revrange(repo, [basef or '.']) rebaseset = repo.revs( '(children(ancestor(%ld, %d)) and ::(%ld))::', base, dest, base) if rebaseset: root = min(rebaseset) else: root = None if not rebaseset: repo.ui.debug('base is ancestor of destination\n') result = None elif (not (keepf or obsolete._enabled) and repo.revs('first(children(%ld) - %ld)', rebaseset, rebaseset)): raise util.Abort( _("can't remove original changesets with" " unrebased descendants"), hint=_('use --keep to keep original changesets')) else: result = buildstate(repo, dest, rebaseset, collapsef) if not result: # Empty state built, nothing to rebase ui.status(_('nothing to rebase\n')) return 1 elif not keepf and not repo[root].mutable(): raise util.Abort(_("can't rebase immutable changeset %s") % repo[root], hint=_('see hg help phases for details')) else: originalwd, target, state = result if collapsef: targetancestors = repo.changelog.ancestors([target], inclusive=True) external = checkexternal(repo, state, targetancestors) if keepbranchesf: assert not extrafn, 'cannot use both keepbranches and extrafn' def extrafn(ctx, extra): extra['branch'] = ctx.branch() if collapsef: branches = set() for rev in state: branches.add(repo[rev].branch()) if len(branches) > 1: raise util.Abort(_('cannot collapse multiple named ' 'branches')) # Rebase if not targetancestors: targetancestors = repo.changelog.ancestors([target], inclusive=True) # Keep track of the current bookmarks in order to reset them later currentbookmarks = repo._bookmarks.copy() activebookmark = activebookmark or repo._bookmarkcurrent if activebookmark: bookmarks.unsetcurrent(repo) sortedstate = sorted(state) total = len(sortedstate) pos = 0 for rev in sortedstate: pos += 1 if state[rev] == -1: ui.progress(_("rebasing"), pos, ("%d:%s" % (rev, repo[rev])), _('changesets'), total) storestatus(repo, originalwd, target, state, collapsef, keepf, keepbranchesf, external, activebookmark) p1, p2 = defineparents(repo, rev, target, state, targetancestors) if len(repo.parents()) == 2: repo.ui.debug('resuming interrupted rebase\n') else: try: ui.setconfig('ui', 'forcemerge', opts.get('tool', '')) stats = rebasenode(repo, rev, p1, state, collapsef) if stats and stats[3] > 0: raise error.InterventionRequired( _('unresolved conflicts (see hg ' 'resolve, then hg rebase --continue)')) finally: ui.setconfig('ui', 'forcemerge', '') cmdutil.duplicatecopies(repo, rev, target) if not collapsef: newrev = concludenode(repo, rev, p1, p2, extrafn=extrafn, editor=editor) else: # Skip commit if we are collapsing repo.setparents(repo[p1].node()) newrev = None # Update the state if newrev is not None: state[rev] = repo[newrev].rev() else: if not collapsef: ui.note(_('no changes, revision %d skipped\n') % rev) ui.debug('next revision set to %s\n' % p1) skipped.add(rev) state[rev] = p1 ui.progress(_('rebasing'), None) ui.note(_('rebase merging completed\n')) if collapsef and not keepopen: p1, p2 = defineparents(repo, min(state), target, state, targetancestors) if collapsemsg: commitmsg = collapsemsg else: commitmsg = 'Collapsed revision' for rebased in state: if rebased not in skipped and state[rebased] > nullmerge: commitmsg += '\n* %s' % repo[rebased].description() commitmsg = ui.edit(commitmsg, repo.ui.username()) newrev = concludenode(repo, rev, p1, external, commitmsg=commitmsg, extrafn=extrafn, editor=editor) if 'qtip' in repo.tags(): updatemq(repo, state, skipped, **opts) if currentbookmarks: # Nodeids are needed to reset bookmarks nstate = {} for k, v in state.iteritems(): if v > nullmerge: nstate[repo[k].node()] = repo[v].node() # XXX this is the same as dest.node() for the non-continue path -- # this should probably be cleaned up targetnode = repo[target].node() if not keepf: collapsedas = None if collapsef: collapsedas = newrev clearrebased(ui, repo, state, skipped, collapsedas) if currentbookmarks: updatebookmarks(repo, targetnode, nstate, currentbookmarks) clearstatus(repo) ui.note(_("rebase completed\n")) util.unlinkpath(repo.sjoin('undo'), ignoremissing=True) if skipped: ui.note(_("%d revisions have been skipped\n") % len(skipped)) if (activebookmark and repo['tip'].node() == repo._bookmarks[activebookmark]): bookmarks.setcurrent(repo, activebookmark) finally: release(lock, wlock) def checkexternal(repo, state, targetancestors): """Check whether one or more external revisions need to be taken in consideration. In the latter case, abort. """ external = nullrev source = min(state) for rev in state: if rev == source: continue # Check externals and fail if there are more than one for p in repo[rev].parents(): if (p.rev() not in state and p.rev() not in targetancestors): if external != nullrev: raise util.Abort(_('unable to collapse, there is more ' 'than one external parent')) external = p.rev() return external def concludenode(repo, rev, p1, p2, commitmsg=None, editor=None, extrafn=None): 'Commit the changes and store useful information in extra' try: repo.setparents(repo[p1].node(), repo[p2].node()) ctx = repo[rev] if commitmsg is None: commitmsg = ctx.description() extra = {'rebase_source': ctx.hex()} if extrafn: extrafn(ctx, extra) # Commit might fail if unresolved files exist newrev = repo.commit(text=commitmsg, user=ctx.user(), date=ctx.date(), extra=extra, editor=editor) repo.dirstate.setbranch(repo[newrev].branch()) targetphase = max(ctx.phase(), phases.draft) # retractboundary doesn't overwrite upper phase inherited from parent newnode = repo[newrev].node() if newnode: phases.retractboundary(repo, targetphase, [newnode]) return newrev except util.Abort: # Invalidate the previous setparents repo.dirstate.invalidate() raise def rebasenode(repo, rev, p1, state, collapse): 'Rebase a single revision' # Merge phase # Update to target and merge it with local if repo['.'].rev() != repo[p1].rev(): repo.ui.debug(" update to %d:%s\n" % (repo[p1].rev(), repo[p1])) merge.update(repo, p1, False, True, False) else: repo.ui.debug(" already in target\n") repo.dirstate.write() repo.ui.debug(" merge against %d:%s\n" % (repo[rev].rev(), repo[rev])) base = None if repo[rev].rev() != repo[min(state)].rev(): base = repo[rev].p1().node() # When collapsing in-place, the parent is the common ancestor, we # have to allow merging with it. return merge.update(repo, rev, True, True, False, base, collapse) def nearestrebased(repo, rev, state): """return the nearest ancestors of rev in the rebase result""" rebased = [r for r in state if state[r] > nullmerge] candidates = repo.revs('max(%ld and (::%d))', rebased, rev) if candidates: return state[candidates[0]] else: return None def defineparents(repo, rev, target, state, targetancestors): 'Return the new parent relationship of the revision that will be rebased' parents = repo[rev].parents() p1 = p2 = nullrev P1n = parents[0].rev() if P1n in targetancestors: p1 = target elif P1n in state: if state[P1n] == nullmerge: p1 = target elif state[P1n] == revignored: p1 = nearestrebased(repo, P1n, state) if p1 is None: p1 = target else: p1 = state[P1n] else: # P1n external p1 = target p2 = P1n if len(parents) == 2 and parents[1].rev() not in targetancestors: P2n = parents[1].rev() # interesting second parent if P2n in state: if p1 == target: # P1n in targetancestors or external p1 = state[P2n] elif state[P2n] == revignored: p2 = nearestrebased(repo, P2n, state) if p2 is None: # no ancestors rebased yet, detach p2 = target else: p2 = state[P2n] else: # P2n external if p2 != nullrev: # P1n external too => rev is a merged revision raise util.Abort(_('cannot use revision %d as base, result ' 'would have 3 parents') % rev) p2 = P2n repo.ui.debug(" future parents are %d and %d\n" % (repo[p1].rev(), repo[p2].rev())) return p1, p2 def isagitpatch(repo, patchname): 'Return true if the given patch is in git format' mqpatch = os.path.join(repo.mq.path, patchname) for line in patch.linereader(file(mqpatch, 'rb')): if line.startswith('diff --git'): return True return False def updatemq(repo, state, skipped, **opts): 'Update rebased mq patches - finalize and then import them' mqrebase = {} mq = repo.mq original_series = mq.fullseries[:] skippedpatches = set() for p in mq.applied: rev = repo[p.node].rev() if rev in state: repo.ui.debug('revision %d is an mq patch (%s), finalize it.\n' % (rev, p.name)) mqrebase[rev] = (p.name, isagitpatch(repo, p.name)) else: # Applied but not rebased, not sure this should happen skippedpatches.add(p.name) if mqrebase: mq.finish(repo, mqrebase.keys()) # We must start import from the newest revision for rev in sorted(mqrebase, reverse=True): if rev not in skipped: name, isgit = mqrebase[rev] repo.ui.debug('import mq patch %d (%s)\n' % (state[rev], name)) mq.qimport(repo, (), patchname=name, git=isgit, rev=[str(state[rev])]) else: # Rebased and skipped skippedpatches.add(mqrebase[rev][0]) # Patches were either applied and rebased and imported in # order, applied and removed or unapplied. Discard the removed # ones while preserving the original series order and guards. newseries = [s for s in original_series if mq.guard_re.split(s, 1)[0] not in skippedpatches] mq.fullseries[:] = newseries mq.seriesdirty = True mq.savedirty() def updatebookmarks(repo, targetnode, nstate, originalbookmarks): 'Move bookmarks to their correct changesets, and delete divergent ones' marks = repo._bookmarks for k, v in originalbookmarks.iteritems(): if v in nstate: # update the bookmarks for revs that have moved marks[k] = nstate[v] bookmarks.deletedivergent(repo, [targetnode], k) marks.write() def storestatus(repo, originalwd, target, state, collapse, keep, keepbranches, external, activebookmark): 'Store the current status to allow recovery' f = repo.opener("rebasestate", "w") f.write(repo[originalwd].hex() + '\n') f.write(repo[target].hex() + '\n') f.write(repo[external].hex() + '\n') f.write('%d\n' % int(collapse)) f.write('%d\n' % int(keep)) f.write('%d\n' % int(keepbranches)) f.write('%s\n' % (activebookmark or '')) for d, v in state.iteritems(): oldrev = repo[d].hex() if v > nullmerge: newrev = repo[v].hex() else: newrev = v f.write("%s:%s\n" % (oldrev, newrev)) f.close() repo.ui.debug('rebase status stored\n') def clearstatus(repo): 'Remove the status files' util.unlinkpath(repo.join("rebasestate"), ignoremissing=True) def restorestatus(repo): 'Restore a previously stored status' try: target = None collapse = False external = nullrev activebookmark = None state = {} f = repo.opener("rebasestate") for i, l in enumerate(f.read().splitlines()): if i == 0: originalwd = repo[l].rev() elif i == 1: target = repo[l].rev() elif i == 2: external = repo[l].rev() elif i == 3: collapse = bool(int(l)) elif i == 4: keep = bool(int(l)) elif i == 5: keepbranches = bool(int(l)) elif i == 6 and not (len(l) == 81 and ':' in l): # line 6 is a recent addition, so for backwards compatibility # check that the line doesn't look like the oldrev:newrev lines activebookmark = l else: oldrev, newrev = l.split(':') if newrev in (str(nullmerge), str(revignored)): state[repo[oldrev].rev()] = int(newrev) else: state[repo[oldrev].rev()] = repo[newrev].rev() skipped = set() # recompute the set of skipped revs if not collapse: seen = set([target]) for old, new in sorted(state.items()): if new != nullrev and new in seen: skipped.add(old) seen.add(new) repo.ui.debug('computed skipped revs: %s\n' % skipped) repo.ui.debug('rebase status resumed\n') return (originalwd, target, state, skipped, collapse, keep, keepbranches, external, activebookmark) except IOError, err: if err.errno != errno.ENOENT: raise raise util.Abort(_('no rebase in progress')) def abort(repo, originalwd, target, state): 'Restore the repository to its original state' dstates = [s for s in state.values() if s != nullrev] immutable = [d for d in dstates if not repo[d].mutable()] if immutable: raise util.Abort(_("can't abort rebase due to immutable changesets %s") % ', '.join(str(repo[r]) for r in immutable), hint=_('see hg help phases for details')) descendants = set() if dstates: descendants = set(repo.changelog.descendants(dstates)) if descendants - set(dstates): repo.ui.warn(_("warning: new changesets detected on target branch, " "can't abort\n")) return -1 else: # Strip from the first rebased revision merge.update(repo, repo[originalwd].rev(), False, True, False) rebased = filter(lambda x: x > -1 and x != target, state.values()) if rebased: strippoints = [c.node() for c in repo.set('roots(%ld)', rebased)] # no backup of rebased cset versions needed repair.strip(repo.ui, repo, strippoints) clearstatus(repo) repo.ui.warn(_('rebase aborted\n')) return 0 def buildstate(repo, dest, rebaseset, collapse): '''Define which revisions are going to be rebased and where repo: repo dest: context rebaseset: set of rev ''' # This check isn't strictly necessary, since mq detects commits over an # applied patch. But it prevents messing up the working directory when # a partially completed rebase is blocked by mq. if 'qtip' in repo.tags() and (dest.node() in [s.node for s in repo.mq.applied]): raise util.Abort(_('cannot rebase onto an applied mq patch')) roots = list(repo.set('roots(%ld)', rebaseset)) if not roots: raise util.Abort(_('no matching revisions')) roots.sort() state = {} detachset = set() for root in roots: commonbase = root.ancestor(dest) if commonbase == root: raise util.Abort(_('source is ancestor of destination')) if commonbase == dest: samebranch = root.branch() == dest.branch() if not collapse and samebranch and root in dest.children(): repo.ui.debug('source is a child of destination\n') return None repo.ui.debug('rebase onto %d starting from %s\n' % (dest, roots)) state.update(dict.fromkeys(rebaseset, nullrev)) # Rebase tries to turn <dest> into a parent of <root> while # preserving the number of parents of rebased changesets: # # - A changeset with a single parent will always be rebased as a # changeset with a single parent. # # - A merge will be rebased as merge unless its parents are both # ancestors of <dest> or are themselves in the rebased set and # pruned while rebased. # # If one parent of <root> is an ancestor of <dest>, the rebased # version of this parent will be <dest>. This is always true with # --base option. # # Otherwise, we need to *replace* the original parents with # <dest>. This "detaches" the rebased set from its former location # and rebases it onto <dest>. Changes introduced by ancestors of # <root> not common with <dest> (the detachset, marked as # nullmerge) are "removed" from the rebased changesets. # # - If <root> has a single parent, set it to <dest>. # # - If <root> is a merge, we cannot decide which parent to # replace, the rebase operation is not clearly defined. # # The table below sums up this behavior: # # +------------------+----------------------+-------------------------+ # | | one parent | merge | # +------------------+----------------------+-------------------------+ # | parent in | new parent is <dest> | parents in ::<dest> are | # | ::<dest> | | remapped to <dest> | # +------------------+----------------------+-------------------------+ # | unrelated source | new parent is <dest> | ambiguous, abort | # +------------------+----------------------+-------------------------+ # # The actual abort is handled by `defineparents` if len(root.parents()) <= 1: # ancestors of <root> not ancestors of <dest> detachset.update(repo.changelog.findmissingrevs([commonbase.rev()], [root.rev()])) for r in detachset: if r not in state: state[r] = nullmerge if len(roots) > 1: # If we have multiple roots, we may have "hole" in the rebase set. # Rebase roots that descend from those "hole" should not be detached as # other root are. We use the special `revignored` to inform rebase that # the revision should be ignored but that `defineparents` should search # a rebase destination that make sense regarding rebased topology. rebasedomain = set(repo.revs('%ld::%ld', rebaseset, rebaseset)) for ignored in set(rebasedomain) - set(rebaseset): state[ignored] = revignored return repo['.'].rev(), dest.rev(), state def clearrebased(ui, repo, state, skipped, collapsedas=None): """dispose of rebased revision at the end of the rebase If `collapsedas` is not None, the rebase was a collapse whose result if the `collapsedas` node.""" if obsolete._enabled: markers = [] for rev, newrev in sorted(state.items()): if newrev >= 0: if rev in skipped: succs = () elif collapsedas is not None: succs = (repo[collapsedas],) else: succs = (repo[newrev],) markers.append((repo[rev], succs)) if markers: obsolete.createmarkers(repo, markers) else: rebased = [rev for rev in state if state[rev] > nullmerge] if rebased: stripped = [] for root in repo.set('roots(%ld)', rebased): if set(repo.changelog.descendants([root.rev()])) - set(state): ui.warn(_("warning: new changesets detected " "on source branch, not stripping\n")) else: stripped.append(root.node()) if stripped: # backup the old csets by default repair.strip(ui, repo, stripped, "all") def pullrebase(orig, ui, repo, *args, **opts): 'Call rebase after pull if the latter has been invoked with --rebase' if opts.get('rebase'): if opts.get('update'): del opts['update'] ui.debug('--update and --rebase are not compatible, ignoring ' 'the update flag\n') movemarkfrom = repo['.'].node() cmdutil.bailifchanged(repo) revsprepull = len(repo) origpostincoming = commands.postincoming def _dummy(*args, **kwargs): pass commands.postincoming = _dummy try: orig(ui, repo, *args, **opts) finally: commands.postincoming = origpostincoming revspostpull = len(repo) if revspostpull > revsprepull: # --rev option from pull conflict with rebase own --rev # dropping it if 'rev' in opts: del opts['rev'] rebase(ui, repo, **opts) branch = repo[None].branch() dest = repo[branch].rev() if dest != repo['.'].rev(): # there was nothing to rebase we force an update hg.update(repo, dest) if bookmarks.update(repo, [movemarkfrom], repo['.'].node()): ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent) else: if opts.get('tool'): raise util.Abort(_('--tool can only be used with --rebase')) orig(ui, repo, *args, **opts) def uisetup(ui): 'Replace pull with a decorator to provide --rebase option' entry = extensions.wrapcommand(commands.table, 'pull', pullrebase) entry[1].append(('', 'rebase', None, _("rebase working directory to branch head"))) entry[1].append(('t', 'tool', '', _("specify merge tool for rebase")))
plotly/plotly.py
refs/heads/master
packages/python/plotly/plotly/graph_objs/ohlc/legendgrouptitle/_font.py
1
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Font(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "ohlc.legendgrouptitle" _path_str = "ohlc.legendgrouptitle.font" _valid_props = {"color", "family", "size"} # color # ----- @property def color(self): """ The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val # family # ------ @property def family(self): """ HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart- studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". The 'family' property is a string and must be specified as: - A non-empty string Returns ------- str """ return self["family"] @family.setter def family(self, val): self["family"] = val # size # ---- @property def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] Returns ------- int|float """ return self["size"] @size.setter def size(self, val): self["size"] = val # Self properties description # --------------------------- @property def _prop_descriptions(self): return """\ color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on- premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size """ def __init__(self, arg=None, color=None, family=None, size=None, **kwargs): """ Construct a new Font object Sets this legend group's title font. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.ohlc.legendgrouptitle.Font` color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on- premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". size Returns ------- Font """ super(Font, self).__init__("font") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.ohlc.legendgrouptitle.Font constructor must be a dict or an instance of :class:`plotly.graph_objs.ohlc.legendgrouptitle.Font`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("color", None) _v = color if color is not None else _v if _v is not None: self["color"] = _v _v = arg.pop("family", None) _v = family if family is not None else _v if _v is not None: self["family"] = _v _v = arg.pop("size", None) _v = size if size is not None else _v if _v is not None: self["size"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
pranjan77/kb_cummerbund
refs/heads/master
lib/GenomeFileUtil/baseclient.py
150
############################################################ # # Autogenerated by the KBase type compiler - # any changes made here will be overwritten # ############################################################ from __future__ import print_function import json as _json import requests as _requests import random as _random import os as _os try: from configparser import ConfigParser as _ConfigParser # py 3 except ImportError: from ConfigParser import ConfigParser as _ConfigParser # py 2 try: from urllib.parse import urlparse as _urlparse # py3 except ImportError: from urlparse import urlparse as _urlparse # py2 import time _CT = 'content-type' _AJ = 'application/json' _URL_SCHEME = frozenset(['http', 'https']) def _get_token(user_id, password, auth_svc): # This is bandaid helper function until we get a full # KBase python auth client released # note that currently globus usernames, and therefore kbase usernames, # cannot contain non-ascii characters. In python 2, quote doesn't handle # unicode, so if this changes this client will need to change. body = ('user_id=' + _requests.utils.quote(user_id) + '&password=' + _requests.utils.quote(password) + '&fields=token') ret = _requests.post(auth_svc, data=body, allow_redirects=True) status = ret.status_code if status >= 200 and status <= 299: tok = _json.loads(ret.text) elif status == 403: raise Exception('Authentication failed: Bad user_id/password ' + 'combination for user %s' % (user_id)) else: raise Exception(ret.text) return tok['token'] def _read_inifile(file=_os.environ.get( # @ReservedAssignment 'KB_DEPLOYMENT_CONFIG', _os.environ['HOME'] + '/.kbase_config')): # Another bandaid to read in the ~/.kbase_config file if one is present authdata = None if _os.path.exists(file): try: config = _ConfigParser() config.read(file) # strip down whatever we read to only what is legit authdata = {x: config.get('authentication', x) if config.has_option('authentication', x) else None for x in ('user_id', 'token', 'client_secret', 'keyfile', 'keyfile_passphrase', 'password')} except Exception as e: print('Error while reading INI file {}: {}'.format(file, e)) return authdata class ServerError(Exception): def __init__(self, name, code, message, data=None, error=None): super(Exception, self).__init__(message) self.name = name self.code = code self.message = '' if message is None else message self.data = data or error or '' # data = JSON RPC 2.0, error = 1.1 def __str__(self): return self.name + ': ' + str(self.code) + '. ' + self.message + \ '\n' + self.data class _JSONObjectEncoder(_json.JSONEncoder): def default(self, obj): if isinstance(obj, set): return list(obj) if isinstance(obj, frozenset): return list(obj) return _json.JSONEncoder.default(self, obj) class BaseClient(object): ''' The KBase base client. Required initialization arguments (positional): url - the url of the the service to contact: For SDK methods: either the url of the callback service or the Narrative Job Service Wrapper. For SDK dynamic services: the url of the Service Wizard. For other services: the url of the service. Optional arguments (keywords in positional order): timeout - methods will fail if they take longer than this value in seconds. Default 1800. user_id - a KBase user name. password - the password corresponding to the user name. token - a KBase authentication token. ignore_authrc - if True, don't read auth configuration from ~/.kbase_config. trust_all_ssl_certificates - set to True to trust self-signed certificates. If you don't understand the implications, leave as the default, False. auth_svc - the url of the KBase authorization service. lookup_url - set to true when contacting KBase dynamic services. async_job_check_time_ms - the wait time between checking job state for asynchronous jobs run with the run_job method. ''' def __init__( self, url=None, timeout=30 * 60, user_id=None, password=None, token=None, ignore_authrc=False, trust_all_ssl_certificates=False, auth_svc='https://kbase.us/services/authorization/Sessions/Login', lookup_url=False, async_job_check_time_ms=100, async_job_check_time_scale_percent=150, async_job_check_max_time_ms=300000): if url is None: raise ValueError('A url is required') scheme, _, _, _, _, _ = _urlparse(url) if scheme not in _URL_SCHEME: raise ValueError(url + " isn't a valid http url") self.url = url self.timeout = int(timeout) self._headers = dict() self.trust_all_ssl_certificates = trust_all_ssl_certificates self.lookup_url = lookup_url self.async_job_check_time = async_job_check_time_ms / 1000.0 self.async_job_check_time_scale_percent = ( async_job_check_time_scale_percent) self.async_job_check_max_time = async_job_check_max_time_ms / 1000.0 # token overrides user_id and password if token is not None: self._headers['AUTHORIZATION'] = token elif user_id is not None and password is not None: self._headers['AUTHORIZATION'] = _get_token( user_id, password, auth_svc) elif 'KB_AUTH_TOKEN' in _os.environ: self._headers['AUTHORIZATION'] = _os.environ.get('KB_AUTH_TOKEN') elif not ignore_authrc: authdata = _read_inifile() if authdata is not None: if authdata.get('token') is not None: self._headers['AUTHORIZATION'] = authdata['token'] elif(authdata.get('user_id') is not None and authdata.get('password') is not None): self._headers['AUTHORIZATION'] = _get_token( authdata['user_id'], authdata['password'], auth_svc) if self.timeout < 1: raise ValueError('Timeout value must be at least 1 second') def _call(self, url, method, params, context=None): arg_hash = {'method': method, 'params': params, 'version': '1.1', 'id': str(_random.random())[2:] } if context: if type(context) is not dict: raise ValueError('context is not type dict as required.') arg_hash['context'] = context body = _json.dumps(arg_hash, cls=_JSONObjectEncoder) ret = _requests.post(url, data=body, headers=self._headers, timeout=self.timeout, verify=not self.trust_all_ssl_certificates) ret.encoding = 'utf-8' if ret.status_code == 500: if ret.headers.get(_CT) == _AJ: err = ret.json() if 'error' in err: raise ServerError(**err['error']) else: raise ServerError('Unknown', 0, ret.text) else: raise ServerError('Unknown', 0, ret.text) if not ret.ok: ret.raise_for_status() resp = ret.json() if 'result' not in resp: raise ServerError('Unknown', 0, 'An unknown server error occurred') if not resp['result']: return if len(resp['result']) == 1: return resp['result'][0] return resp['result'] def _get_service_url(self, service_method, service_version): if not self.lookup_url: return self.url service, _ = service_method.split('.') service_status_ret = self._call( self.url, 'ServiceWizard.get_service_status', [{'module_name': service, 'version': service_version}]) return service_status_ret['url'] def _set_up_context(self, service_ver=None, context=None): if service_ver: if not context: context = {} context['service_ver'] = service_ver return context def _check_job(self, service, job_id): return self._call(self.url, service + '._check_job', [job_id]) def _submit_job(self, service_method, args, service_ver=None, context=None): context = self._set_up_context(service_ver, context) mod, meth = service_method.split('.') return self._call(self.url, mod + '._' + meth + '_submit', args, context) def run_job(self, service_method, args, service_ver=None, context=None): ''' Run a SDK method asynchronously. Required arguments: service_method - the service and method to run, e.g. myserv.mymeth. args - a list of arguments to the method. Optional arguments: service_ver - the version of the service to run, e.g. a git hash or dev/beta/release. context - the rpc context dict. ''' mod, _ = service_method.split('.') job_id = self._submit_job(service_method, args, service_ver, context) async_job_check_time = self.async_job_check_time while True: time.sleep(async_job_check_time) async_job_check_time = (async_job_check_time * self.async_job_check_time_scale_percent / 100.0) if async_job_check_time > self.async_job_check_max_time: async_job_check_time = self.async_job_check_max_time job_state = self._check_job(mod, job_id) if job_state['finished']: if not job_state['result']: return if len(job_state['result']) == 1: return job_state['result'][0] return job_state['result'] def call_method(self, service_method, args, service_ver=None, context=None): ''' Call a standard or dynamic service synchronously. Required arguments: service_method - the service and method to run, e.g. myserv.mymeth. args - a list of arguments to the method. Optional arguments: service_ver - the version of the service to run, e.g. a git hash or dev/beta/release. context - the rpc context dict. ''' url = self._get_service_url(service_method, service_ver) context = self._set_up_context(service_ver, context) return self._call(url, service_method, args, context)
mute/elasticsearch
refs/heads/master
dev-tools/create_bwc_index_with_some_ancient_segments.py
217
import create_bwc_index import logging import os import random import shutil import subprocess import sys import tempfile def fetch_version(version): logging.info('fetching ES version %s' % version) if subprocess.call([sys.executable, os.path.join(os.path.split(sys.argv[0])[0], 'get-bwc-version.py'), version]) != 0: raise RuntimeError('failed to download ES version %s' % version) def main(): ''' Creates a static back compat index (.zip) with mixed 0.20 (Lucene 3.x) and 0.90 (Lucene 4.x) segments. ''' logging.basicConfig(format='[%(levelname)s] [%(asctime)s] %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %I:%M:%S %p') logging.getLogger('elasticsearch').setLevel(logging.ERROR) logging.getLogger('urllib3').setLevel(logging.WARN) tmp_dir = tempfile.mkdtemp() try: data_dir = os.path.join(tmp_dir, 'data') repo_dir = os.path.join(tmp_dir, 'repo') logging.info('Temp data dir: %s' % data_dir) logging.info('Temp repo dir: %s' % repo_dir) first_version = '0.20.6' second_version = '0.90.6' index_name = 'index-%s-and-%s' % (first_version, second_version) # Download old ES releases if necessary: release_dir = os.path.join('backwards', 'elasticsearch-%s' % first_version) if not os.path.exists(release_dir): fetch_version(first_version) node = create_bwc_index.start_node(first_version, release_dir, data_dir, repo_dir, cluster_name=index_name) client = create_bwc_index.create_client() # Creates the index & indexes docs w/ first_version: create_bwc_index.generate_index(client, first_version, index_name) # Make sure we write segments: flush_result = client.indices.flush(index=index_name) if not flush_result['ok']: raise RuntimeError('flush failed: %s' % str(flush_result)) segs = client.indices.segments(index=index_name) shards = segs['indices'][index_name]['shards'] if len(shards) != 1: raise RuntimeError('index should have 1 shard but got %s' % len(shards)) first_version_segs = shards['0'][0]['segments'].keys() create_bwc_index.shutdown_node(node) print('%s server output:\n%s' % (first_version, node.stdout.read().decode('utf-8'))) node = None release_dir = os.path.join('backwards', 'elasticsearch-%s' % second_version) if not os.path.exists(release_dir): fetch_version(second_version) # Now also index docs with second_version: node = create_bwc_index.start_node(second_version, release_dir, data_dir, repo_dir, cluster_name=index_name) client = create_bwc_index.create_client() # If we index too many docs, the random refresh/flush causes the ancient segments to be merged away: num_docs = 10 create_bwc_index.index_documents(client, index_name, 'doc', num_docs) # Make sure we get a segment: flush_result = client.indices.flush(index=index_name) if not flush_result['ok']: raise RuntimeError('flush failed: %s' % str(flush_result)) # Make sure we see mixed segments (it's possible Lucene could have "accidentally" merged away the first_version segments): segs = client.indices.segments(index=index_name) shards = segs['indices'][index_name]['shards'] if len(shards) != 1: raise RuntimeError('index should have 1 shard but got %s' % len(shards)) second_version_segs = shards['0'][0]['segments'].keys() #print("first: %s" % first_version_segs) #print("second: %s" % second_version_segs) for segment_name in first_version_segs: if segment_name in second_version_segs: # Good: an ancient version seg "survived": break else: raise RuntimeError('index has no first_version segs left') for segment_name in second_version_segs: if segment_name not in first_version_segs: # Good: a second_version segment was written break else: raise RuntimeError('index has no second_version segs left') create_bwc_index.shutdown_node(node) print('%s server output:\n%s' % (second_version, node.stdout.read().decode('utf-8'))) node = None create_bwc_index.compress_index('%s-and-%s' % (first_version, second_version), tmp_dir, 'core/src/test/resources/org/elasticsearch/action/admin/indices/upgrade') finally: if node is not None: create_bwc_index.shutdown_node(node) shutil.rmtree(tmp_dir) if __name__ == '__main__': main()
jonnary/keystone
refs/heads/master
keystone/common/sql/migrate_repo/versions/046_placeholder.py
70
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # This is a placeholder for Icehouse backports. Do not use this number for new # Juno work. New Juno work starts after all the placeholders. # # See blueprint reserved-db-migrations-icehouse and the related discussion: # http://lists.openstack.org/pipermail/openstack-dev/2013-March/006827.html def upgrade(migrate_engine): pass
coderbone/SickRage
refs/heads/master
lib/bs4/tests/test_html5lib.py
293
"""Tests to ensure that the html5lib tree builder generates good trees.""" import warnings try: from bs4.builder import HTML5TreeBuilder HTML5LIB_PRESENT = True except ImportError, e: HTML5LIB_PRESENT = False from bs4.element import SoupStrainer from bs4.testing import ( HTML5TreeBuilderSmokeTest, SoupTest, skipIf, ) @skipIf( not HTML5LIB_PRESENT, "html5lib seems not to be present, not testing its tree builder.") class HTML5LibBuilderSmokeTest(SoupTest, HTML5TreeBuilderSmokeTest): """See ``HTML5TreeBuilderSmokeTest``.""" @property def default_builder(self): return HTML5TreeBuilder() def test_soupstrainer(self): # The html5lib tree builder does not support SoupStrainers. strainer = SoupStrainer("b") markup = "<p>A <b>bold</b> statement.</p>" with warnings.catch_warnings(record=True) as w: soup = self.soup(markup, parse_only=strainer) self.assertEqual( soup.decode(), self.document_for(markup)) self.assertTrue( "the html5lib tree builder doesn't support parse_only" in str(w[0].message)) def test_correctly_nested_tables(self): """html5lib inserts <tbody> tags where other parsers don't.""" markup = ('<table id="1">' '<tr>' "<td>Here's another table:" '<table id="2">' '<tr><td>foo</td></tr>' '</table></td>') self.assertSoupEquals( markup, '<table id="1"><tbody><tr><td>Here\'s another table:' '<table id="2"><tbody><tr><td>foo</td></tr></tbody></table>' '</td></tr></tbody></table>') self.assertSoupEquals( "<table><thead><tr><td>Foo</td></tr></thead>" "<tbody><tr><td>Bar</td></tr></tbody>" "<tfoot><tr><td>Baz</td></tr></tfoot></table>") def test_xml_declaration_followed_by_doctype(self): markup = '''<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html> <html> <head> </head> <body> <p>foo</p> </body> </html>''' soup = self.soup(markup) # Verify that we can reach the <p> tag; this means the tree is connected. self.assertEqual(b"<p>foo</p>", soup.p.encode()) def test_reparented_markup(self): markup = '<p><em>foo</p>\n<p>bar<a></a></em></p>' soup = self.soup(markup) self.assertEqual(u"<body><p><em>foo</em></p><em>\n</em><p><em>bar<a></a></em></p></body>", soup.body.decode()) self.assertEqual(2, len(soup.find_all('p'))) def test_reparented_markup_ends_with_whitespace(self): markup = '<p><em>foo</p>\n<p>bar<a></a></em></p>\n' soup = self.soup(markup) self.assertEqual(u"<body><p><em>foo</em></p><em>\n</em><p><em>bar<a></a></em></p>\n</body>", soup.body.decode()) self.assertEqual(2, len(soup.find_all('p')))
meirwah/st2contrib
refs/heads/master
packs/hue/actions/lib/action.py
9
from hue import Hue from st2actions.runners.pythonrunner import Action class BaseAction(Action): def __init__(self, config): super(BaseAction, self).__init__(config) self.hue = self._get_client() def _get_client(self): hue = Hue() hue.station_ip = self.config['station_ip'] hue.get_state() return hue
CS-SI/QGIS
refs/heads/master
tests/src/python/test_provider_postgres.py
3
# -*- coding: utf-8 -*- """QGIS Unit tests for the postgres provider. Note: to prepare the DB, you need to run the sql files specified in tests/testdata/provider/testdata_pg.sh .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ from builtins import next __author__ = 'Matthias Kuhn' __date__ = '2015-04-23' __copyright__ = 'Copyright 2015, The QGIS Project' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import qgis # NOQA import psycopg2 import os import time from qgis.core import ( QgsVectorLayer, QgsVectorLayerExporter, QgsFeatureRequest, QgsFeature, QgsFieldConstraints, QgsDataProvider, NULL, QgsVectorLayerUtils, QgsSettings, QgsTransactionGroup, QgsReadWriteContext, QgsRectangle, QgsDefaultValue, QgsCoordinateReferenceSystem, QgsProject, QgsWkbTypes, QgsGeometry ) from qgis.gui import QgsGui, QgsAttributeForm from qgis.PyQt.QtCore import QDate, QTime, QDateTime, QVariant, QDir, QObject from qgis.PyQt.QtWidgets import QLabel from qgis.testing import start_app, unittest from qgis.PyQt.QtXml import QDomDocument from utilities import unitTestDataPath from providertestbase import ProviderTestCase QGISAPP = start_app() TEST_DATA_DIR = unitTestDataPath() class TestPyQgsPostgresProvider(unittest.TestCase, ProviderTestCase): @classmethod def setUpClass(cls): """Run before all tests""" cls.dbconn = 'dbname=\'qgis_test\'' if 'QGIS_PGTEST_DB' in os.environ: cls.dbconn = os.environ['QGIS_PGTEST_DB'] # Create test layers cls.vl = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'pk\' srid=4326 type=POINT table="qgis_test"."someData" (geom) sql=', 'test', 'postgres') assert cls.vl.isValid() cls.source = cls.vl.dataProvider() cls.poly_vl = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'pk\' srid=4326 type=POLYGON table="qgis_test"."some_poly_data" (geom) sql=', 'test', 'postgres') assert cls.poly_vl.isValid() cls.poly_provider = cls.poly_vl.dataProvider() QgsGui.editorWidgetRegistry().initEditors() cls.con = psycopg2.connect(cls.dbconn) @classmethod def tearDownClass(cls): """Run after all tests""" def execSQLCommand(self, sql): self.assertTrue(self.con) cur = self.con.cursor() self.assertTrue(cur) cur.execute(sql) cur.close() self.con.commit() def getSource(self): # create temporary table for edit tests self.execSQLCommand('DROP TABLE IF EXISTS qgis_test."editData" CASCADE') self.execSQLCommand('CREATE TABLE qgis_test."editData" ( pk SERIAL NOT NULL PRIMARY KEY, cnt integer, name text, name2 text, num_char text, geom public.geometry(Point, 4326))') self.execSQLCommand("INSERT INTO qgis_test.\"editData\" (pk, cnt, name, name2, num_char, geom) VALUES " "(5, -200, NULL, 'NuLl', '5', '0101000020E61000001D5A643BDFC751C01F85EB51B88E5340')," "(3, 300, 'Pear', 'PEaR', '3', NULL)," "(1, 100, 'Orange', 'oranGe', '1', '0101000020E61000006891ED7C3F9551C085EB51B81E955040')," "(2, 200, 'Apple', 'Apple', '2', '0101000020E6100000CDCCCCCCCC0C51C03333333333B35140')," "(4, 400, 'Honey', 'Honey', '4', '0101000020E610000014AE47E17A5450C03333333333935340')") vl = QgsVectorLayer( self.dbconn + ' sslmode=disable key=\'pk\' srid=4326 type=POINT table="qgis_test"."editData" (geom) sql=', 'test', 'postgres') return vl def getEditableLayer(self): return self.getSource() def enableCompiler(self): QgsSettings().setValue('/qgis/compileExpressions', True) def disableCompiler(self): QgsSettings().setValue('/qgis/compileExpressions', False) def uncompiledFilters(self): return set([]) def partiallyCompiledFilters(self): return set([]) # HERE GO THE PROVIDER SPECIFIC TESTS def testDefaultValue(self): self.source.setProviderProperty(QgsDataProvider.EvaluateDefaultValues, True) self.assertIsInstance(self.source.defaultValue(0), int) self.assertEqual(self.source.defaultValue(1), NULL) self.assertEqual(self.source.defaultValue(2), 'qgis') self.source.setProviderProperty(QgsDataProvider.EvaluateDefaultValues, False) def testDefaultValueClause(self): self.source.setProviderProperty(QgsDataProvider.EvaluateDefaultValues, False) self.assertEqual(self.source.defaultValueClause(0), 'nextval(\'qgis_test."someData_pk_seq"\'::regclass)') self.assertFalse(self.source.defaultValueClause(1)) self.assertEqual(self.source.defaultValueClause(2), '\'qgis\'::text') def testDateTimeTypes(self): vl = QgsVectorLayer('%s table="qgis_test"."date_times" sql=' % (self.dbconn), "testdatetimes", "postgres") self.assertTrue(vl.isValid()) fields = vl.dataProvider().fields() self.assertEqual(fields.at(fields.indexFromName('date_field')).type(), QVariant.Date) self.assertEqual(fields.at(fields.indexFromName('time_field')).type(), QVariant.Time) self.assertEqual(fields.at(fields.indexFromName('datetime_field')).type(), QVariant.DateTime) f = next(vl.getFeatures(QgsFeatureRequest())) date_idx = vl.fields().lookupField('date_field') self.assertIsInstance(f.attributes()[date_idx], QDate) self.assertEqual(f.attributes()[date_idx], QDate(2004, 3, 4)) time_idx = vl.fields().lookupField('time_field') self.assertIsInstance(f.attributes()[time_idx], QTime) self.assertEqual(f.attributes()[time_idx], QTime(13, 41, 52)) datetime_idx = vl.fields().lookupField('datetime_field') self.assertIsInstance(f.attributes()[datetime_idx], QDateTime) self.assertEqual(f.attributes()[datetime_idx], QDateTime(QDate(2004, 3, 4), QTime(13, 41, 52))) def testBooleanType(self): vl = QgsVectorLayer('{} table="qgis_test"."boolean_table" sql='.format(self.dbconn), "testbool", "postgres") self.assertTrue(vl.isValid()) fields = vl.dataProvider().fields() self.assertEqual(fields.at(fields.indexFromName('fld1')).type(), QVariant.Bool) values = {feat['id']: feat['fld1'] for feat in vl.getFeatures()} expected = { 1: True, 2: False, 3: NULL } self.assertEqual(values, expected) def testQueryLayers(self): def test_query(dbconn, query, key): ql = QgsVectorLayer('%s srid=4326 table="%s" (geom) key=\'%s\' sql=' % (dbconn, query.replace('"', '\\"'), key), "testgeom", "postgres") self.assertTrue(ql.isValid(), '{} ({})'.format(query, key)) test_query(self.dbconn, '(SELECT NULL::integer "Id1", NULL::integer "Id2", NULL::geometry(Point, 4326) geom LIMIT 0)', '"Id1","Id2"') def testWkbTypes(self): def test_table(dbconn, table_name, wkt): vl = QgsVectorLayer('%s srid=4326 table="qgis_test".%s (geom) sql=' % (dbconn, table_name), "testgeom", "postgres") self.assertTrue(vl.isValid()) for f in vl.getFeatures(): self.assertEqual(f.geometry().asWkt(), wkt) test_table(self.dbconn, 'p2d', 'Polygon ((0 0, 1 0, 1 1, 0 1, 0 0))') test_table(self.dbconn, 'p3d', 'PolygonZ ((0 0 0, 1 0 0, 1 1 0, 0 1 0, 0 0 0))') test_table(self.dbconn, 'triangle2d', 'Polygon ((0 0, 1 0, 1 1, 0 0))') test_table(self.dbconn, 'triangle3d', 'PolygonZ ((0 0 0, 1 0 0, 1 1 0, 0 0 0))') test_table(self.dbconn, 'tin2d', 'MultiPolygon (((0 0, 1 0, 1 1, 0 0)),((0 0, 0 1, 1 1, 0 0)))') test_table(self.dbconn, 'tin3d', 'MultiPolygonZ (((0 0 0, 1 0 0, 1 1 0, 0 0 0)),((0 0 0, 0 1 0, 1 1 0, 0 0 0)))') test_table(self.dbconn, 'ps2d', 'MultiPolygon (((0 0, 1 0, 1 1, 0 1, 0 0)))') test_table(self.dbconn, 'ps3d', 'MultiPolygonZ (((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)),((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)),((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)),((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),((1 0 0, 1 0 1, 0 0 1, 0 0 0, 1 0 0)))') test_table(self.dbconn, 'mp3d', 'MultiPolygonZ (((0 0 0, 0 1 0, 1 1 0, 1 0 0, 0 0 0)),((0 0 1, 1 0 1, 1 1 1, 0 1 1, 0 0 1)),((0 0 0, 0 0 1, 0 1 1, 0 1 0, 0 0 0)),((0 1 0, 0 1 1, 1 1 1, 1 1 0, 0 1 0)),((1 1 0, 1 1 1, 1 0 1, 1 0 0, 1 1 0)),((1 0 0, 1 0 1, 0 0 1, 0 0 0, 1 0 0)))') test_table(self.dbconn, 'pt2d', 'Point (0 0)') test_table(self.dbconn, 'pt3d', 'PointZ (0 0 0)') test_table(self.dbconn, 'ls2d', 'LineString (0 0, 1 1)') test_table(self.dbconn, 'ls3d', 'LineStringZ (0 0 0, 1 1 1)') test_table(self.dbconn, 'mpt2d', 'MultiPoint ((0 0),(1 1))') test_table(self.dbconn, 'mpt3d', 'MultiPointZ ((0 0 0),(1 1 1))') test_table(self.dbconn, 'mls2d', 'MultiLineString ((0 0, 1 1),(2 2, 3 3))') test_table(self.dbconn, 'mls3d', 'MultiLineStringZ ((0 0 0, 1 1 1),(2 2 2, 3 3 3))') test_table(self.dbconn, 'pt4d', 'PointZM (1 2 3 4)') def testMetadata(self): """ Test that metadata is correctly acquired from provider """ metadata = self.vl.metadata() self.assertEqual(metadata.crs(), QgsCoordinateReferenceSystem.fromEpsgId(4326)) self.assertEqual(metadata.type(), 'dataset') self.assertEqual(metadata.abstract(), 'QGIS Test Table') def testGetFeaturesUniqueId(self): """ Test tables with inheritance for unique ids """ def test_unique(features, num_features): featureids = [] for f in features: self.assertFalse(f.id() in featureids) featureids.append(f.id()) self.assertEqual(len(features), num_features) vl = QgsVectorLayer('%s srid=4326 table="qgis_test".%s (geom) sql=' % (self.dbconn, 'someData'), "testgeom", "postgres") self.assertTrue(vl.isValid()) # Test someData test_unique([f for f in vl.getFeatures()], 5) # Test base_table_bad: layer is invalid vl = QgsVectorLayer('%s srid=4326 table="qgis_test".%s (geom) sql=' % (self.dbconn, 'base_table_bad'), "testgeom", "postgres") self.assertFalse(vl.isValid()) # Test base_table_bad with use estimated metadata: layer is valid because the unique test is skipped vl = QgsVectorLayer('%s srid=4326 estimatedmetadata="true" table="qgis_test".%s (geom) sql=' % (self.dbconn, 'base_table_bad'), "testgeom", "postgres") self.assertTrue(vl.isValid()) # Test base_table_good: layer is valid vl = QgsVectorLayer('%s srid=4326 table="qgis_test".%s (geom) sql=' % (self.dbconn, 'base_table_good'), "testgeom", "postgres") self.assertTrue(vl.isValid()) test_unique([f for f in vl.getFeatures()], 4) # Test base_table_good with use estimated metadata: layer is valid vl = QgsVectorLayer('%s srid=4326 estimatedmetadata="true" table="qgis_test".%s (geom) sql=' % (self.dbconn, 'base_table_good'), "testgeom", "postgres") self.assertTrue(vl.isValid()) test_unique([f for f in vl.getFeatures()], 4) # See https://issues.qgis.org/issues/14262 # TODO: accept multi-featured layers, and an array of values/fids def testSignedIdentifiers(self): def test_layer(ql, att, val, fidval): self.assertTrue(ql.isValid()) features = ql.getFeatures() att_idx = ql.fields().lookupField(att) count = 0 for f in features: count += 1 self.assertEqual(f.attributes()[att_idx], val) self.assertEqual(f.id(), fidval) self.assertEqual(count, 1) def test(dbconn, query, att, val, fidval): table = query.replace('"', '\\"') uri = '%s table="%s" (g) key=\'%s\'' % (dbconn, table, att) ql = QgsVectorLayer(uri, "t", "postgres") test_layer(ql, att, val, fidval) # now with estimated metadata uri += ' estimatedmetadata="true"' test_layer(ql, att, val, fidval) # --- INT16 ---- # zero test(self.dbconn, '(SELECT 0::int2 i, NULL::geometry(Point) g)', 'i', 0, 0) # low positive test(self.dbconn, '(SELECT 1::int2 i, NULL::geometry(Point) g)', 'i', 1, 1) # low negative test(self.dbconn, '(SELECT -1::int2 i, NULL::geometry(Point) g)', 'i', -1, 4294967295) # max positive signed 16bit integer test(self.dbconn, '(SELECT 32767::int2 i, NULL::geometry(Point) g)', 'i', 32767, 32767) # max negative signed 16bit integer test(self.dbconn, '(SELECT (-32768)::int2 i, NULL::geometry(Point) g)', 'i', -32768, 4294934528) # --- INT32 ---- # zero test(self.dbconn, '(SELECT 0::int4 i, NULL::geometry(Point) g)', 'i', 0, 0) # low positive test(self.dbconn, '(SELECT 2::int4 i, NULL::geometry(Point) g)', 'i', 2, 2) # low negative test(self.dbconn, '(SELECT -2::int4 i, NULL::geometry(Point) g)', 'i', -2, 4294967294) # max positive signed 32bit integer test(self.dbconn, '(SELECT 2147483647::int4 i, NULL::geometry(Point) g)', 'i', 2147483647, 2147483647) # max negative signed 32bit integer test(self.dbconn, '(SELECT (-2147483648)::int4 i, NULL::geometry(Point) g)', 'i', -2147483648, 2147483648) # --- INT64 (FIDs are always 1 because assigned ex-novo) ---- # zero test(self.dbconn, '(SELECT 0::int8 i, NULL::geometry(Point) g)', 'i', 0, 1) # low positive test(self.dbconn, '(SELECT 3::int8 i, NULL::geometry(Point) g)', 'i', 3, 1) # low negative test(self.dbconn, '(SELECT -3::int8 i, NULL::geometry(Point) g)', 'i', -3, 1) # max positive signed 64bit integer test(self.dbconn, '(SELECT 9223372036854775807::int8 i, NULL::geometry(Point) g)', 'i', 9223372036854775807, 1) # max negative signed 32bit integer test(self.dbconn, '(SELECT (-9223372036854775808)::int8 i, NULL::geometry(Point) g)', 'i', -9223372036854775808, 1) def testPktIntInsert(self): vl = QgsVectorLayer('{} table="qgis_test"."{}" key="pk" sql='.format(self.dbconn, 'bikes_view'), "bikes_view", "postgres") self.assertTrue(vl.isValid()) f = QgsFeature(vl.fields()) f['pk'] = NULL f['name'] = 'Cilo' r, f = vl.dataProvider().addFeatures([f]) self.assertTrue(r) self.assertNotEqual(f[0]['pk'], NULL, f[0].attributes()) vl.deleteFeatures([f[0].id()]) def testPktMapInsert(self): vl = QgsVectorLayer('{} table="qgis_test"."{}" key="obj_id" sql='.format(self.dbconn, 'oid_serial_table'), "oid_serial", "postgres") self.assertTrue(vl.isValid()) f = QgsFeature(vl.fields()) f['obj_id'] = vl.dataProvider().defaultValueClause(0) f['name'] = 'Test' r, f = vl.dataProvider().addFeatures([f]) self.assertTrue(r) self.assertNotEqual(f[0]['obj_id'], NULL, f[0].attributes()) vl.deleteFeatures([f[0].id()]) def testNull(self): """ Asserts that 0, '' and NULL are treated as different values on insert """ vl = QgsVectorLayer(self.dbconn + ' sslmode=disable key=\'gid\' table="qgis_test"."constraints" sql=', 'test1', 'postgres') self.assertTrue(vl.isValid()) QgsProject.instance().addMapLayer(vl) tg = QgsTransactionGroup() tg.addLayer(vl) vl.startEditing() def onError(message): """We should not get here. If we do, fail and say why""" self.assertFalse(True, message) vl.raiseError.connect(onError) f = QgsFeature(vl.fields()) f['gid'] = 100 f['val'] = 0 f['name'] = '' self.assertTrue(vl.addFeature(f)) feature = next(vl.getFeatures('"gid" = 100')) self.assertEqual(f['val'], feature['val']) self.assertEqual(f['name'], feature['name']) def testNestedInsert(self): tg = QgsTransactionGroup() tg.addLayer(self.vl) self.vl.startEditing() it = self.vl.getFeatures() f = next(it) f['pk'] = NULL self.vl.addFeature(f) # Should not deadlock during an active iteration f = next(it) def testTimeout(self): """ Asserts that we will not deadlock if more iterators are opened in parallel than available in the connection pool """ request = QgsFeatureRequest() request.setConnectionTimeout(1) iterators = list() for i in range(100): iterators.append(self.vl.getFeatures(request)) def testTransactionDirtyName(self): # create a vector ayer based on postgres vl = QgsVectorLayer(self.dbconn + ' sslmode=disable key=\'pk\' srid=4326 type=POLYGON table="qgis_test"."some_poly_data" (geom) sql=', 'test', 'postgres') self.assertTrue(vl.isValid()) # prepare a project with transactions enabled p = QgsProject() p.setAutoTransaction(True) p.addMapLayers([vl]) vl.startEditing() # update the data within the transaction tr = vl.dataProvider().transaction() sql = "update qgis_test.some_poly_data set pk=1 where pk=1" name = "My Awesome Transaction!" self.assertTrue(tr.executeSql(sql, True, name)[0]) # test name self.assertEqual(vl.undoStack().command(0).text(), name) # rollback vl.rollBack() def testTransactionDirty(self): # create a vector layer based on postgres vl = QgsVectorLayer(self.dbconn + ' sslmode=disable key=\'pk\' srid=4326 type=POLYGON table="qgis_test"."some_poly_data" (geom) sql=', 'test', 'postgres') self.assertTrue(vl.isValid()) # prepare a project with transactions enabled p = QgsProject() p.setAutoTransaction(True) p.addMapLayers([vl]) vl.startEditing() # check that the feature used for testing is ok ft0 = vl.getFeatures('pk=1') f = QgsFeature() self.assertTrue(ft0.nextFeature(f)) # update the data within the transaction tr = vl.dataProvider().transaction() sql = "update qgis_test.some_poly_data set pk=33 where pk=1" self.assertTrue(tr.executeSql(sql, True)[0]) # check that the pk of the feature has been changed ft = vl.getFeatures('pk=1') self.assertFalse(ft.nextFeature(f)) ft = vl.getFeatures('pk=33') self.assertTrue(ft.nextFeature(f)) # underlying data has been modified but the layer is not tagged as # modified self.assertTrue(vl.isModified()) # undo sql query vl.undoStack().undo() # check that the original feature with pk is back ft0 = vl.getFeatures('pk=1') self.assertTrue(ft0.nextFeature(f)) # redo vl.undoStack().redo() # check that the pk of the feature has been changed ft1 = vl.getFeatures('pk=1') self.assertFalse(ft1.nextFeature(f)) def testTransactionConstrains(self): # create a vector layer based on postgres vl = QgsVectorLayer(self.dbconn + ' sslmode=disable key=\'id\' table="qgis_test"."check_constraints" sql=', 'test', 'postgres') self.assertTrue(vl.isValid()) # prepare a project with transactions enabled p = QgsProject() p.setAutoTransaction(True) p.addMapLayers([vl]) # get feature f = QgsFeature() self.assertTrue(vl.getFeatures('id=1').nextFeature(f)) self.assertEqual(f.attributes(), [1, 4, 3]) # start edition vl.startEditing() # update attribute form with a failing constraints # coming from the database if attributes are updated # one at a time. # Current feature: a = 4 / b = 3 # Update feature: a = 1 / b = 0 # If updated one at a time, '(a = 1) < (b = 3)' => FAIL! form = QgsAttributeForm(vl, f) for w in form.findChildren(QLabel): if w.buddy(): spinBox = w.buddy() if w.text() == 'a': spinBox.setValue(1) elif w.text() == 'b': spinBox.setValue(0) # save form.save() # check new values self.assertTrue(vl.getFeatures('id=1').nextFeature(f)) self.assertEqual(f.attributes(), [1, 1, NULL]) def testTransactionTuple(self): # create a vector layer based on postgres vl = QgsVectorLayer(self.dbconn + ' sslmode=disable key=\'pk\' srid=4326 type=POLYGON table="qgis_test"."some_poly_data" (geom) sql=', 'test', 'postgres') self.assertTrue(vl.isValid()) # prepare a project with transactions enabled p = QgsProject() p.setAutoTransaction(True) p.addMapLayers([vl]) vl.startEditing() # execute a query which returns a tuple tr = vl.dataProvider().transaction() sql = "select * from qgis_test.some_poly_data" self.assertTrue(tr.executeSql(sql, False)[0]) # underlying data has not been modified self.assertFalse(vl.isModified()) def testDomainTypes(self): """Test that domain types are correctly mapped""" vl = QgsVectorLayer('%s table="qgis_test"."domains" sql=' % (self.dbconn), "domains", "postgres") self.assertTrue(vl.isValid()) fields = vl.dataProvider().fields() expected = {} expected['fld_var_char_domain'] = {'type': QVariant.String, 'typeName': 'qgis_test.var_char_domain', 'length': -1} expected['fld_var_char_domain_6'] = {'type': QVariant.String, 'typeName': 'qgis_test.var_char_domain_6', 'length': 6} expected['fld_character_domain'] = {'type': QVariant.String, 'typeName': 'qgis_test.character_domain', 'length': 1} expected['fld_character_domain_6'] = {'type': QVariant.String, 'typeName': 'qgis_test.character_domain_6', 'length': 6} expected['fld_char_domain'] = {'type': QVariant.String, 'typeName': 'qgis_test.char_domain', 'length': 1} expected['fld_char_domain_6'] = {'type': QVariant.String, 'typeName': 'qgis_test.char_domain_6', 'length': 6} expected['fld_text_domain'] = {'type': QVariant.String, 'typeName': 'qgis_test.text_domain', 'length': -1} expected['fld_numeric_domain'] = {'type': QVariant.Double, 'typeName': 'qgis_test.numeric_domain', 'length': 10, 'precision': 4} for f, e in list(expected.items()): self.assertEqual(fields.at(fields.indexFromName(f)).type(), e['type']) self.assertEqual(fields.at(fields.indexFromName(f)).typeName(), e['typeName']) self.assertEqual(fields.at(fields.indexFromName(f)).length(), e['length']) if 'precision' in e: self.assertEqual(fields.at(fields.indexFromName(f)).precision(), e['precision']) def testRenameAttributes(self): ''' Test renameAttributes() ''' vl = QgsVectorLayer('%s table="qgis_test"."rename_table" sql=' % (self.dbconn), "renames", "postgres") provider = vl.dataProvider() provider.renameAttributes({1: 'field1', 2: 'field2'}) # bad rename self.assertFalse(provider.renameAttributes({-1: 'not_a_field'})) self.assertFalse(provider.renameAttributes({100: 'not_a_field'})) # already exists self.assertFalse(provider.renameAttributes({1: 'field2'})) # rename one field self.assertTrue(provider.renameAttributes({1: 'newname'})) self.assertEqual(provider.fields().at(1).name(), 'newname') vl.updateFields() fet = next(vl.getFeatures()) self.assertEqual(fet.fields()[1].name(), 'newname') # rename two fields self.assertTrue(provider.renameAttributes({1: 'newname2', 2: 'another'})) self.assertEqual(provider.fields().at(1).name(), 'newname2') self.assertEqual(provider.fields().at(2).name(), 'another') vl.updateFields() fet = next(vl.getFeatures()) self.assertEqual(fet.fields()[1].name(), 'newname2') self.assertEqual(fet.fields()[2].name(), 'another') # close layer and reopen, then recheck to confirm that changes were saved to db del vl vl = None vl = QgsVectorLayer('%s table="qgis_test"."rename_table" sql=' % (self.dbconn), "renames", "postgres") provider = vl.dataProvider() self.assertEqual(provider.fields().at(1).name(), 'newname2') self.assertEqual(provider.fields().at(2).name(), 'another') fet = next(vl.getFeatures()) self.assertEqual(fet.fields()[1].name(), 'newname2') self.assertEqual(fet.fields()[2].name(), 'another') def testEditorWidgetTypes(self): """Test that editor widget types can be fetched from the qgis_editor_widget_styles table""" vl = QgsVectorLayer('%s table="qgis_test"."widget_styles" sql=' % (self.dbconn), "widget_styles", "postgres") self.assertTrue(vl.isValid()) fields = vl.dataProvider().fields() setup1 = fields.field("fld1").editorWidgetSetup() self.assertFalse(setup1.isNull()) self.assertEqual(setup1.type(), "FooEdit") self.assertEqual(setup1.config(), {"param1": "value1", "param2": "2"}) best1 = QgsGui.editorWidgetRegistry().findBest(vl, "fld1") self.assertEqual(best1.type(), "FooEdit") self.assertEqual(best1.config(), setup1.config()) self.assertTrue(fields.field("fld2").editorWidgetSetup().isNull()) best2 = QgsGui.editorWidgetRegistry().findBest(vl, "fld2") self.assertEqual(best2.type(), "TextEdit") def testHstore(self): vl = QgsVectorLayer('%s table="qgis_test"."dict" sql=' % (self.dbconn), "testhstore", "postgres") self.assertTrue(vl.isValid()) fields = vl.dataProvider().fields() self.assertEqual(fields.at(fields.indexFromName('value')).type(), QVariant.Map) f = next(vl.getFeatures(QgsFeatureRequest())) value_idx = vl.fields().lookupField('value') self.assertIsInstance(f.attributes()[value_idx], dict) self.assertEqual(f.attributes()[value_idx], {'a': 'b', '1': '2'}) new_f = QgsFeature(vl.fields()) new_f['pk'] = NULL new_f['value'] = {'simple': '1', 'doubleQuote': '"y"', 'quote': "'q'", 'backslash': '\\'} r, fs = vl.dataProvider().addFeatures([new_f]) self.assertTrue(r) new_pk = fs[0]['pk'] self.assertNotEqual(new_pk, NULL, fs[0].attributes()) try: read_back = vl.getFeature(new_pk) self.assertEqual(read_back['pk'], new_pk) self.assertEqual(read_back['value'], new_f['value']) finally: self.assertTrue(vl.startEditing()) self.assertTrue(vl.deleteFeatures([new_pk])) self.assertTrue(vl.commitChanges()) def testStringArray(self): vl = QgsVectorLayer('%s table="qgis_test"."string_array" sql=' % (self.dbconn), "teststringarray", "postgres") self.assertTrue(vl.isValid()) fields = vl.dataProvider().fields() self.assertEqual(fields.at(fields.indexFromName('value')).type(), QVariant.StringList) self.assertEqual(fields.at(fields.indexFromName('value')).subType(), QVariant.String) f = next(vl.getFeatures(QgsFeatureRequest())) value_idx = vl.fields().lookupField('value') self.assertIsInstance(f.attributes()[value_idx], list) self.assertEqual(f.attributes()[value_idx], ['a', 'b', 'c']) new_f = QgsFeature(vl.fields()) new_f['pk'] = NULL new_f['value'] = ['simple', '"doubleQuote"', "'quote'", 'back\\slash'] r, fs = vl.dataProvider().addFeatures([new_f]) self.assertTrue(r) new_pk = fs[0]['pk'] self.assertNotEqual(new_pk, NULL, fs[0].attributes()) try: read_back = vl.getFeature(new_pk) self.assertEqual(read_back['pk'], new_pk) self.assertEqual(read_back['value'], new_f['value']) finally: self.assertTrue(vl.startEditing()) self.assertTrue(vl.deleteFeatures([new_pk])) self.assertTrue(vl.commitChanges()) def testIntArray(self): vl = QgsVectorLayer('%s table="qgis_test"."int_array" sql=' % (self.dbconn), "testintarray", "postgres") self.assertTrue(vl.isValid()) fields = vl.dataProvider().fields() self.assertEqual(fields.at(fields.indexFromName('value')).type(), QVariant.List) self.assertEqual(fields.at(fields.indexFromName('value')).subType(), QVariant.Int) f = next(vl.getFeatures(QgsFeatureRequest())) value_idx = vl.fields().lookupField('value') self.assertIsInstance(f.attributes()[value_idx], list) self.assertEqual(f.attributes()[value_idx], [1, 2, -5]) def testDoubleArray(self): vl = QgsVectorLayer('%s table="qgis_test"."double_array" sql=' % (self.dbconn), "testdoublearray", "postgres") self.assertTrue(vl.isValid()) fields = vl.dataProvider().fields() self.assertEqual(fields.at(fields.indexFromName('value')).type(), QVariant.List) self.assertEqual(fields.at(fields.indexFromName('value')).subType(), QVariant.Double) f = next(vl.getFeatures(QgsFeatureRequest())) value_idx = vl.fields().lookupField('value') self.assertIsInstance(f.attributes()[value_idx], list) self.assertEqual(f.attributes()[value_idx], [1.1, 2, -5.12345]) def testNotNullConstraint(self): vl = QgsVectorLayer('%s table="qgis_test"."constraints" sql=' % (self.dbconn), "constraints", "postgres") self.assertTrue(vl.isValid()) self.assertEqual(len(vl.fields()), 4) # test some bad field indexes self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsFieldConstraints.Constraints()) self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsFieldConstraints.Constraints()) self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsFieldConstraints.ConstraintNotNull) self.assertFalse(vl.dataProvider().fieldConstraints(1) & QgsFieldConstraints.ConstraintNotNull) self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsFieldConstraints.ConstraintNotNull) self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsFieldConstraints.ConstraintNotNull) # test that constraints have been saved to fields correctly fields = vl.fields() self.assertTrue(fields.at(0).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) self.assertEqual(fields.at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginProvider) self.assertFalse(fields.at(1).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) self.assertTrue(fields.at(2).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) self.assertEqual(fields.at(2).constraints().constraintOrigin(QgsFieldConstraints.ConstraintNotNull), QgsFieldConstraints.ConstraintOriginProvider) self.assertFalse(fields.at(3).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) def testUniqueConstraint(self): vl = QgsVectorLayer('%s table="qgis_test"."constraints" sql=' % (self.dbconn), "constraints", "postgres") self.assertTrue(vl.isValid()) self.assertEqual(len(vl.fields()), 4) # test some bad field indexes self.assertEqual(vl.dataProvider().fieldConstraints(-1), QgsFieldConstraints.Constraints()) self.assertEqual(vl.dataProvider().fieldConstraints(1001), QgsFieldConstraints.Constraints()) self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsFieldConstraints.ConstraintUnique) self.assertTrue(vl.dataProvider().fieldConstraints(1) & QgsFieldConstraints.ConstraintUnique) self.assertTrue(vl.dataProvider().fieldConstraints(2) & QgsFieldConstraints.ConstraintUnique) self.assertFalse(vl.dataProvider().fieldConstraints(3) & QgsFieldConstraints.ConstraintUnique) # test that constraints have been saved to fields correctly fields = vl.fields() self.assertTrue(fields.at(0).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) self.assertEqual(fields.at(0).constraints().constraintOrigin(QgsFieldConstraints.ConstraintUnique), QgsFieldConstraints.ConstraintOriginProvider) self.assertTrue(fields.at(1).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) self.assertEqual(fields.at(1).constraints().constraintOrigin(QgsFieldConstraints.ConstraintUnique), QgsFieldConstraints.ConstraintOriginProvider) self.assertTrue(fields.at(2).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) self.assertEqual(fields.at(2).constraints().constraintOrigin(QgsFieldConstraints.ConstraintUnique), QgsFieldConstraints.ConstraintOriginProvider) self.assertFalse(fields.at(3).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) def testConstraintOverwrite(self): """ test that Postgres provider constraints can't be overwritten by vector layer method """ vl = QgsVectorLayer('%s table="qgis_test"."constraints" sql=' % (self.dbconn), "constraints", "postgres") self.assertTrue(vl.isValid()) self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsFieldConstraints.ConstraintNotNull) self.assertTrue(vl.fields().at(0).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) # add a constraint at the layer level vl.setFieldConstraint(0, QgsFieldConstraints.ConstraintUnique) # should be no change at provider level self.assertTrue(vl.dataProvider().fieldConstraints(0) & QgsFieldConstraints.ConstraintNotNull) # but layer should still keep provider constraints... self.assertTrue(vl.fields().at(0).constraints().constraints() & QgsFieldConstraints.ConstraintNotNull) self.assertTrue(vl.fieldConstraints(0) & QgsFieldConstraints.ConstraintNotNull) # ...in addition to layer level constraint self.assertTrue(vl.fields().at(0).constraints().constraints() & QgsFieldConstraints.ConstraintUnique) self.assertTrue(vl.fieldConstraints(0) & QgsFieldConstraints.ConstraintUnique) def testVectorLayerUtilsUniqueWithProviderDefault(self): vl = QgsVectorLayer('%s table="qgis_test"."someData" sql=' % (self.dbconn), "someData", "postgres") default_clause = 'nextval(\'qgis_test."someData_pk_seq"\'::regclass)' vl.dataProvider().setProviderProperty(QgsDataProvider.EvaluateDefaultValues, False) self.assertEqual(vl.dataProvider().defaultValueClause(0), default_clause) self.assertTrue(QgsVectorLayerUtils.valueExists(vl, 0, 4)) vl.startEditing() f = QgsFeature(vl.fields()) f.setAttribute(0, default_clause) self.assertFalse(QgsVectorLayerUtils.valueExists(vl, 0, default_clause)) self.assertTrue(vl.addFeatures([f])) # the default value clause should exist... self.assertTrue(QgsVectorLayerUtils.valueExists(vl, 0, default_clause)) # but it should not prevent the attribute being validated self.assertTrue(QgsVectorLayerUtils.validateAttribute(vl, f, 0)) vl.rollBack() def testSkipConstraintCheck(self): vl = QgsVectorLayer('%s table="qgis_test"."someData" sql=' % (self.dbconn), "someData", "postgres") default_clause = 'nextval(\'qgis_test."someData_pk_seq"\'::regclass)' vl.dataProvider().setProviderProperty(QgsDataProvider.EvaluateDefaultValues, False) self.assertTrue(vl.dataProvider().skipConstraintCheck(0, QgsFieldConstraints.ConstraintUnique, default_clause)) self.assertFalse(vl.dataProvider().skipConstraintCheck(0, QgsFieldConstraints.ConstraintUnique, 59)) def testVectorLayerUtilsCreateFeatureWithProviderDefault(self): vl = QgsVectorLayer('%s table="qgis_test"."someData" sql=' % (self.dbconn), "someData", "postgres") default_clause = 'nextval(\'qgis_test."someData_pk_seq"\'::regclass)' self.assertEqual(vl.dataProvider().defaultValueClause(0), default_clause) # check that provider default clause takes precedence over passed attribute values # this also checks that the inbuilt unique constraint handling is bypassed in the case of a provider default clause f = QgsVectorLayerUtils.createFeature(vl, attributes={1: 5, 3: 'map'}) self.assertEqual(f.attributes(), [default_clause, 5, "'qgis'::text", "'qgis'::text", None, None]) # test take vector layer default value expression overrides postgres provider default clause vl.setDefaultValueDefinition(3, QgsDefaultValue("'mappy'")) f = QgsVectorLayerUtils.createFeature(vl, attributes={1: 5, 3: 'map'}) self.assertEqual(f.attributes(), [default_clause, 5, "'qgis'::text", 'mappy', None, None]) # See https://issues.qgis.org/issues/15188 def testNumericPrecision(self): uri = 'point?field=f1:int' uri += '&field=f2:double(6,4)' uri += '&field=f3:string(20)' lyr = QgsVectorLayer(uri, "x", "memory") self.assertTrue(lyr.isValid()) f = QgsFeature(lyr.fields()) f['f1'] = 1 f['f2'] = 123.456 f['f3'] = '12345678.90123456789' lyr.dataProvider().addFeatures([f]) uri = '%s table="qgis_test"."b18155" (g) key=\'f1\'' % (self.dbconn) self.execSQLCommand('DROP TABLE IF EXISTS qgis_test.b18155') err = QgsVectorLayerExporter.exportLayer(lyr, uri, "postgres", lyr.crs()) self.assertEqual(err[0], QgsVectorLayerExporter.NoError, 'unexpected import error {0}'.format(err)) lyr = QgsVectorLayer(uri, "y", "postgres") self.assertTrue(lyr.isValid()) f = next(lyr.getFeatures()) self.assertEqual(f['f1'], 1) self.assertEqual(f['f2'], 123.456) self.assertEqual(f['f3'], '12345678.90123456789') # See https://issues.qgis.org/issues/15226 def testImportKey(self): uri = 'point?field=f1:int' uri += '&field=F2:double(6,4)' uri += '&field=f3:string(20)' lyr = QgsVectorLayer(uri, "x", "memory") self.assertTrue(lyr.isValid()) def testKey(lyr, key, kfnames): self.execSQLCommand('DROP TABLE IF EXISTS qgis_test.import_test') uri = '%s table="qgis_test"."import_test" (g)' % self.dbconn if key is not None: uri += ' key=\'%s\'' % key err = QgsVectorLayerExporter.exportLayer(lyr, uri, "postgres", lyr.crs()) self.assertEqual(err[0], QgsVectorLayerExporter.NoError, 'unexpected import error {0}'.format(err)) olyr = QgsVectorLayer(uri, "y", "postgres") self.assertTrue(olyr.isValid()) flds = lyr.fields() oflds = olyr.fields() if key is None: # if the pkey was not given, it will create a pkey self.assertEqual(oflds.size(), flds.size() + 1) self.assertEqual(oflds[0].name(), kfnames[0]) for i in range(flds.size()): self.assertEqual(oflds[i + 1].name(), flds[i].name()) else: # pkey was given, no extra field generated self.assertEqual(oflds.size(), flds.size()) for i in range(oflds.size()): self.assertEqual(oflds[i].name(), flds[i].name()) pks = olyr.primaryKeyAttributes() self.assertEqual(len(pks), len(kfnames)) for i in range(0, len(kfnames)): self.assertEqual(oflds[pks[i]].name(), kfnames[i]) testKey(lyr, 'f1', ['f1']) testKey(lyr, '"f1"', ['f1']) testKey(lyr, '"f1","F2"', ['f1', 'F2']) testKey(lyr, '"f1","F2","f3"', ['f1', 'F2', 'f3']) testKey(lyr, None, ['id']) # See https://issues.qgis.org/issues/17518 def testImportWithoutSchema(self): def _test(table, schema=None): self.execSQLCommand('DROP TABLE IF EXISTS %s CASCADE' % table) uri = 'point?field=f1:int' uri += '&field=F2:double(6,4)' uri += '&field=f3:string(20)' lyr = QgsVectorLayer(uri, "x", "memory") self.assertTrue(lyr.isValid()) table = ("%s" % table) if schema is None else ("\"%s\".\"%s\"" % (schema, table)) dest_uri = "%s sslmode=disable table=%s (geom) sql" % (self.dbconn, table) QgsVectorLayerExporter.exportLayer(lyr, dest_uri, "postgres", lyr.crs()) olyr = QgsVectorLayer(dest_uri, "y", "postgres") self.assertTrue(olyr.isValid(), "Failed URI: %s" % dest_uri) # Test bug 17518 _test('b17518') # Test fully qualified table (with schema) _test("b17518", "qgis_test") # Test empty schema _test("b17518", "") # Test public schema _test("b17518", "public") # Test fully qualified table (with wrong schema) with self.assertRaises(AssertionError): _test("b17518", "qgis_test_wrong") def testStyle(self): self.execSQLCommand('DROP TABLE IF EXISTS layer_styles CASCADE') vl = self.getEditableLayer() self.assertTrue(vl.isValid()) self.assertTrue(vl.dataProvider().isSaveAndLoadStyleToDatabaseSupported()) self.assertTrue(vl.dataProvider().isDeleteStyleFromDatabaseSupported()) # table layer_styles does not exit related_count, idlist, namelist, desclist, errmsg = vl.listStylesInDatabase() self.assertEqual(related_count, -1) self.assertEqual(idlist, []) self.assertEqual(namelist, []) self.assertEqual(desclist, []) self.assertNotEqual(errmsg, "") qml, errmsg = vl.getStyleFromDatabase("1") self.assertEqual(qml, "") self.assertNotEqual(errmsg, "") mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.qml' % (unitTestDataPath(), "singleSymbol")) status = vl.loadNamedStyle(mFilePath) self.assertTrue(status) errorMsg = vl.saveStyleToDatabase("by day", "faded greens and elegant patterns", False, "") self.assertEqual(errorMsg, "") # the style id should be "1", not "by day" qml, errmsg = vl.getStyleFromDatabase("by day") self.assertEqual(qml, "") self.assertNotEqual(errmsg, "") related_count, idlist, namelist, desclist, errmsg = vl.listStylesInDatabase() self.assertEqual(related_count, 1) self.assertEqual(errmsg, "") self.assertEqual(idlist, ["1"]) self.assertEqual(namelist, ["by day"]) self.assertEqual(desclist, ["faded greens and elegant patterns"]) qml, errmsg = vl.getStyleFromDatabase("100") self.assertEqual(qml, "") self.assertNotEqual(errmsg, "") qml, errmsg = vl.getStyleFromDatabase("1") self.assertTrue(qml.startswith('<!DOCTYPE qgis'), qml) self.assertEqual(errmsg, "") res, errmsg = vl.deleteStyleFromDatabase("100") self.assertTrue(res) self.assertEqual(errmsg, "") res, errmsg = vl.deleteStyleFromDatabase("1") self.assertTrue(res) self.assertEqual(errmsg, "") # table layer_styles does exit, but is now empty related_count, idlist, namelist, desclist, errmsg = vl.listStylesInDatabase() self.assertEqual(related_count, 0) self.assertEqual(idlist, []) self.assertEqual(namelist, []) self.assertEqual(desclist, []) self.assertEqual(errmsg, "") def testHasMetadata(self): # views don't have metadata vl = QgsVectorLayer('{} table="qgis_test"."{}" key="pk" sql='.format(self.dbconn, 'bikes_view'), "bikes_view", "postgres") self.assertTrue(vl.isValid()) self.assertFalse(vl.dataProvider().hasMetadata()) # ordinary tables have metadata vl = QgsVectorLayer('%s table="qgis_test"."someData" sql=' % (self.dbconn), "someData", "postgres") self.assertTrue(vl.isValid()) self.assertTrue(vl.dataProvider().hasMetadata()) def testReadExtentOnView(self): # vector layer based on view vl0 = QgsVectorLayer(self.dbconn + ' sslmode=disable key=\'pk\' srid=4326 type=POLYGON table="qgis_test"."some_poly_data_view" (geom) sql=', 'test', 'postgres') self.assertTrue(vl0.isValid()) self.assertFalse(vl0.dataProvider().hasMetadata()) # set a custom extent originalExtent = vl0.extent() customExtent = QgsRectangle(-80, 80, -70, 90) vl0.setExtent(customExtent) # write xml doc = QDomDocument("testdoc") elem = doc.createElement("maplayer") self.assertTrue(vl0.writeLayerXml(elem, doc, QgsReadWriteContext())) # read xml with the custom extent. It should not be used by default vl1 = QgsVectorLayer() vl1.readLayerXml(elem, QgsReadWriteContext()) self.assertTrue(vl1.isValid()) self.assertEqual(vl1.extent(), originalExtent) # read xml with custom extent with readExtent option. Extent read from # xml document should be used because we have a view vl2 = QgsVectorLayer() vl2.setReadExtentFromXml(True) vl2.readLayerXml(elem, QgsReadWriteContext()) self.assertTrue(vl2.isValid()) self.assertEqual(vl2.extent(), customExtent) # but a force update on extent should allow retrieveing the data # provider extent vl2.updateExtents() vl2.readLayerXml(elem, QgsReadWriteContext()) self.assertEqual(vl2.extent(), customExtent) vl2.updateExtents(force=True) vl2.readLayerXml(elem, QgsReadWriteContext()) self.assertEqual(vl2.extent(), originalExtent) def testReadExtentOnTable(self): # vector layer based on a standard table vl0 = QgsVectorLayer(self.dbconn + ' sslmode=disable key=\'pk\' srid=4326 type=POLYGON table="qgis_test"."some_poly_data" (geom) sql=', 'test', 'postgres') self.assertTrue(vl0.isValid()) self.assertTrue(vl0.dataProvider().hasMetadata()) # set a custom extent originalExtent = vl0.extent() customExtent = QgsRectangle(-80, 80, -70, 90) vl0.setExtent(customExtent) # write xml doc = QDomDocument("testdoc") elem = doc.createElement("maplayer") self.assertTrue(vl0.writeLayerXml(elem, doc, QgsReadWriteContext())) # read xml with the custom extent. It should not be used by default vl1 = QgsVectorLayer() vl1.readLayerXml(elem, QgsReadWriteContext()) self.assertTrue(vl1.isValid()) self.assertEqual(vl1.extent(), originalExtent) # read xml with custom extent with readExtent option. Extent read from # xml document should NOT be used because we don't have a view or a # materialized view vl2 = QgsVectorLayer() vl2.setReadExtentFromXml(True) vl2.readLayerXml(elem, QgsReadWriteContext()) self.assertTrue(vl2.isValid()) self.assertEqual(vl2.extent(), originalExtent) def testNotify(self): vl0 = QgsVectorLayer(self.dbconn + ' sslmode=disable key=\'pk\' srid=4326 type=POLYGON table="qgis_test"."some_poly_data" (geom) sql=', 'test', 'postgres') vl0.dataProvider().setListening(True) class Notified(QObject): def __init__(self): super(Notified, self).__init__() self.received = "" def receive(self, msg): self.received = msg notified = Notified() vl0.dataProvider().notify.connect(notified.receive) vl0.dataProvider().setListening(True) cur = self.con.cursor() ok = False start = time.time() while True: cur.execute("NOTIFY qgis, 'my message'") self.con.commit() QGISAPP.processEvents() if notified.received == "my message": ok = True break if (time.time() - start) > 5: # timeout break vl0.dataProvider().notify.disconnect(notified.receive) vl0.dataProvider().setListening(False) self.assertTrue(ok) def testStyleDatabaseWithService(self): myconn = 'service=\'qgis_test\'' if 'QGIS_PGTEST_DB' in os.environ: myconn = os.environ['QGIS_PGTEST_DB'] myvl = QgsVectorLayer(myconn + ' sslmode=disable key=\'pk\' srid=4326 type=POINT table="qgis_test"."someData" (geom) sql=', 'test', 'postgres') styles = myvl.listStylesInDatabase() ids = styles[1] self.assertEqual(len(ids), 0) myvl.saveStyleToDatabase('mystyle', '', False, '') styles = myvl.listStylesInDatabase() ids = styles[1] self.assertEqual(len(ids), 1) myvl.deleteStyleFromDatabase(ids[0]) styles = myvl.listStylesInDatabase() ids = styles[1] self.assertEqual(len(ids), 0) def testCurveToMultipolygon(self): self.execSQLCommand('CREATE TABLE IF NOT EXISTS multicurve(pk SERIAL NOT NULL PRIMARY KEY, geom public.geometry(MultiPolygon, 4326))') self.execSQLCommand('TRUNCATE multicurve') vl = QgsVectorLayer(self.dbconn + ' sslmode=disable key=\'pk\' srid=4326 type=MULTIPOLYGON table="multicurve" (geom) sql=', 'test', 'postgres') f = QgsFeature(vl.fields()) f.setGeometry(QgsGeometry.fromWkt('CurvePolygon(CircularString (20 30, 50 30, 50 90, 10 50, 20 30))')) self.assertTrue(vl.startEditing()) self.assertTrue(vl.addFeatures([f])) self.assertTrue(vl.commitChanges()) f = next(vl.getFeatures(QgsFeatureRequest())) g = f.geometry().constGet() self.assertTrue(g) self.assertEqual(g.wkbType(), QgsWkbTypes.MultiPolygon) self.assertEqual(g.childCount(), 1) self.assertTrue(g.childGeometry(0).vertexCount() > 3) class TestPyQgsPostgresProviderCompoundKey(unittest.TestCase, ProviderTestCase): @classmethod def setUpClass(cls): """Run before all tests""" cls.dbconn = 'dbname=\'qgis_test\'' if 'QGIS_PGTEST_DB' in os.environ: cls.dbconn = os.environ['QGIS_PGTEST_DB'] # Create test layers cls.vl = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'"key1","key2"\' srid=4326 type=POINT table="qgis_test"."someDataCompound" (geom) sql=', 'test', 'postgres') assert cls.vl.isValid() cls.source = cls.vl.dataProvider() @classmethod def tearDownClass(cls): """Run after all tests""" def enableCompiler(self): QgsSettings().setValue('/qgis/compileExpressions', True) def disableCompiler(self): QgsSettings().setValue('/qgis/compileExpressions', False) def uncompiledFilters(self): return set([]) def partiallyCompiledFilters(self): return set([]) if __name__ == '__main__': unittest.main()
newswangerd/ansible
refs/heads/devel
lib/ansible/plugins/loader.py
8
# (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com> # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> and others # (c) 2017, Toshio Kuratomi <tkuratomi@ansible.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import glob import os import os.path import sys import warnings from collections import defaultdict, namedtuple from ansible import constants as C from ansible.errors import AnsibleError, AnsiblePluginCircularRedirect, AnsiblePluginRemovedError, AnsibleCollectionUnsupportedVersionError from ansible.module_utils._text import to_bytes, to_text, to_native from ansible.module_utils.compat.importlib import import_module from ansible.module_utils.six import string_types from ansible.parsing.utils.yaml import from_yaml from ansible.parsing.yaml.loader import AnsibleLoader from ansible.plugins import get_plugin_class, MODULE_CACHE, PATH_CACHE, PLUGIN_PATH_CACHE from ansible.utils.collection_loader import AnsibleCollectionConfig, AnsibleCollectionRef from ansible.utils.collection_loader._collection_finder import _AnsibleCollectionFinder, _get_collection_metadata from ansible.utils.display import Display from ansible.utils.plugin_docs import add_fragments from ansible import __version__ as ansible_version # TODO: take the packaging dep, or vendor SpecifierSet? try: from packaging.specifiers import SpecifierSet from packaging.version import Version except ImportError: SpecifierSet = None Version = None try: import importlib.util imp = None except ImportError: import imp display = Display() get_with_context_result = namedtuple('get_with_context_result', ['object', 'plugin_load_context']) def get_all_plugin_loaders(): return [(name, obj) for (name, obj) in globals().items() if isinstance(obj, PluginLoader)] def add_all_plugin_dirs(path): ''' add any existing plugin dirs in the path provided ''' b_path = os.path.expanduser(to_bytes(path, errors='surrogate_or_strict')) if os.path.isdir(b_path): for name, obj in get_all_plugin_loaders(): if obj.subdir: plugin_path = os.path.join(b_path, to_bytes(obj.subdir)) if os.path.isdir(plugin_path): obj.add_directory(to_text(plugin_path)) else: display.warning("Ignoring invalid path provided to plugin path: '%s' is not a directory" % to_text(path)) def get_shell_plugin(shell_type=None, executable=None): if not shell_type: # default to sh shell_type = 'sh' # mostly for backwards compat if executable: if isinstance(executable, string_types): shell_filename = os.path.basename(executable) try: shell = shell_loader.get(shell_filename) except Exception: shell = None if shell is None: for shell in shell_loader.all(): if shell_filename in shell.COMPATIBLE_SHELLS: shell_type = shell.SHELL_FAMILY break else: raise AnsibleError("Either a shell type or a shell executable must be provided ") shell = shell_loader.get(shell_type) if not shell: raise AnsibleError("Could not find the shell plugin required (%s)." % shell_type) if executable: setattr(shell, 'executable', executable) return shell def add_dirs_to_loader(which_loader, paths): loader = getattr(sys.modules[__name__], '%s_loader' % which_loader) for path in paths: loader.add_directory(path, with_subdir=True) class PluginPathContext(object): def __init__(self, path, internal): self.path = path self.internal = internal class PluginLoadContext(object): def __init__(self): self.original_name = None self.redirect_list = [] self.error_list = [] self.import_error_list = [] self.load_attempts = [] self.pending_redirect = None self.exit_reason = None self.plugin_resolved_path = None self.plugin_resolved_name = None self.plugin_resolved_collection = None # empty string for resolved plugins from user-supplied paths self.deprecated = False self.removal_date = None self.removal_version = None self.deprecation_warnings = [] self.resolved = False def record_deprecation(self, name, deprecation, collection_name): if not deprecation: return self warning_text = deprecation.get('warning_text', None) removal_date = deprecation.get('removal_date', None) removal_version = deprecation.get('removal_version', None) # If both removal_date and removal_version are specified, use removal_date if removal_date is not None: removal_version = None if not warning_text: warning_text = '{0} has been deprecated'.format(name) display.deprecated(warning_text, date=removal_date, version=removal_version, collection_name=collection_name) self.deprecated = True if removal_date: self.removal_date = removal_date if removal_version: self.removal_version = removal_version self.deprecation_warnings.append(warning_text) return self def resolve(self, resolved_name, resolved_path, resolved_collection, exit_reason): self.pending_redirect = None self.plugin_resolved_name = resolved_name self.plugin_resolved_path = resolved_path self.plugin_resolved_collection = resolved_collection self.exit_reason = exit_reason self.resolved = True return self def redirect(self, redirect_name): self.pending_redirect = redirect_name self.exit_reason = 'pending redirect resolution from {0} to {1}'.format(self.original_name, redirect_name) self.resolved = False return self def nope(self, exit_reason): self.pending_redirect = None self.exit_reason = exit_reason self.resolved = False return self class PluginLoader: ''' PluginLoader loads plugins from the configured plugin directories. It searches for plugins by iterating through the combined list of play basedirs, configured paths, and the python path. The first match is used. ''' def __init__(self, class_name, package, config, subdir, aliases=None, required_base_class=None): aliases = {} if aliases is None else aliases self.class_name = class_name self.base_class = required_base_class self.package = package self.subdir = subdir # FIXME: remove alias dict in favor of alias by symlink? self.aliases = aliases if config and not isinstance(config, list): config = [config] elif not config: config = [] self.config = config if class_name not in MODULE_CACHE: MODULE_CACHE[class_name] = {} if class_name not in PATH_CACHE: PATH_CACHE[class_name] = None if class_name not in PLUGIN_PATH_CACHE: PLUGIN_PATH_CACHE[class_name] = defaultdict(dict) # hold dirs added at runtime outside of config self._extra_dirs = [] # caches self._module_cache = MODULE_CACHE[class_name] self._paths = PATH_CACHE[class_name] self._plugin_path_cache = PLUGIN_PATH_CACHE[class_name] self._searched_paths = set() def __repr__(self): return 'PluginLoader(type={0})'.format(AnsibleCollectionRef.legacy_plugin_dir_to_plugin_type(self.subdir)) def _clear_caches(self): if C.OLD_PLUGIN_CACHE_CLEARING: self._paths = None else: # reset global caches MODULE_CACHE[self.class_name] = {} PATH_CACHE[self.class_name] = None PLUGIN_PATH_CACHE[self.class_name] = defaultdict(dict) # reset internal caches self._module_cache = MODULE_CACHE[self.class_name] self._paths = PATH_CACHE[self.class_name] self._plugin_path_cache = PLUGIN_PATH_CACHE[self.class_name] self._searched_paths = set() def __setstate__(self, data): ''' Deserializer. ''' class_name = data.get('class_name') package = data.get('package') config = data.get('config') subdir = data.get('subdir') aliases = data.get('aliases') base_class = data.get('base_class') PATH_CACHE[class_name] = data.get('PATH_CACHE') PLUGIN_PATH_CACHE[class_name] = data.get('PLUGIN_PATH_CACHE') self.__init__(class_name, package, config, subdir, aliases, base_class) self._extra_dirs = data.get('_extra_dirs', []) self._searched_paths = data.get('_searched_paths', set()) def __getstate__(self): ''' Serializer. ''' return dict( class_name=self.class_name, base_class=self.base_class, package=self.package, config=self.config, subdir=self.subdir, aliases=self.aliases, _extra_dirs=self._extra_dirs, _searched_paths=self._searched_paths, PATH_CACHE=PATH_CACHE[self.class_name], PLUGIN_PATH_CACHE=PLUGIN_PATH_CACHE[self.class_name], ) def format_paths(self, paths): ''' Returns a string suitable for printing of the search path ''' # Uses a list to get the order right ret = [] for i in paths: if i not in ret: ret.append(i) return os.pathsep.join(ret) def print_paths(self): return self.format_paths(self._get_paths(subdirs=False)) def _all_directories(self, dir): results = [] results.append(dir) for root, subdirs, files in os.walk(dir, followlinks=True): if '__init__.py' in files: for x in subdirs: results.append(os.path.join(root, x)) return results def _get_package_paths(self, subdirs=True): ''' Gets the path of a Python package ''' if not self.package: return [] if not hasattr(self, 'package_path'): m = __import__(self.package) parts = self.package.split('.')[1:] for parent_mod in parts: m = getattr(m, parent_mod) self.package_path = to_text(os.path.dirname(m.__file__), errors='surrogate_or_strict') if subdirs: return self._all_directories(self.package_path) return [self.package_path] def _get_paths_with_context(self, subdirs=True): ''' Return a list of PluginPathContext objects to search for plugins in ''' # FIXME: This is potentially buggy if subdirs is sometimes True and sometimes False. # In current usage, everything calls this with subdirs=True except for module_utils_loader and ansible-doc # which always calls it with subdirs=False. So there currently isn't a problem with this caching. if self._paths is not None: return self._paths ret = [PluginPathContext(p, False) for p in self._extra_dirs] # look in any configured plugin paths, allow one level deep for subcategories if self.config is not None: for path in self.config: path = os.path.abspath(os.path.expanduser(path)) if subdirs: contents = glob.glob("%s/*" % path) + glob.glob("%s/*/*" % path) for c in contents: c = to_text(c, errors='surrogate_or_strict') if os.path.isdir(c) and c not in ret: ret.append(PluginPathContext(c, False)) path = to_text(path, errors='surrogate_or_strict') if path not in ret: ret.append(PluginPathContext(path, False)) # look for any plugins installed in the package subtree # Note package path always gets added last so that every other type of # path is searched before it. ret.extend([PluginPathContext(p, True) for p in self._get_package_paths(subdirs=subdirs)]) # HACK: because powershell modules are in the same directory # hierarchy as other modules we have to process them last. This is # because powershell only works on windows but the other modules work # anywhere (possibly including windows if the correct language # interpreter is installed). the non-powershell modules can have any # file extension and thus powershell modules are picked up in that. # The non-hack way to fix this is to have powershell modules be # a different PluginLoader/ModuleLoader. But that requires changing # other things too (known thing to change would be PATHS_CACHE, # PLUGIN_PATHS_CACHE, and MODULE_CACHE. Since those three dicts key # on the class_name and neither regular modules nor powershell modules # would have class_names, they would not work as written. # # The expected sort order is paths in the order in 'ret' with paths ending in '/windows' at the end, # also in the original order they were found in 'ret'. # The .sort() method is guaranteed to be stable, so original order is preserved. ret.sort(key=lambda p: p.path.endswith('/windows')) # cache and return the result self._paths = ret return ret def _get_paths(self, subdirs=True): ''' Return a list of paths to search for plugins in ''' paths_with_context = self._get_paths_with_context(subdirs=subdirs) return [path_with_context.path for path_with_context in paths_with_context] def _load_config_defs(self, name, module, path): ''' Reads plugin docs to find configuration setting definitions, to push to config manager for later use ''' # plugins w/o class name don't support config if self.class_name: type_name = get_plugin_class(self.class_name) # if type name != 'module_doc_fragment': if type_name in C.CONFIGURABLE_PLUGINS: dstring = AnsibleLoader(getattr(module, 'DOCUMENTATION', ''), file_name=path).get_single_data() if dstring: add_fragments(dstring, path, fragment_loader=fragment_loader, is_module=(type_name == 'module')) if dstring and 'options' in dstring and isinstance(dstring['options'], dict): C.config.initialize_plugin_configuration_definitions(type_name, name, dstring['options']) display.debug('Loaded config def from plugin (%s/%s)' % (type_name, name)) def add_directory(self, directory, with_subdir=False): ''' Adds an additional directory to the search path ''' directory = os.path.realpath(directory) if directory is not None: if with_subdir: directory = os.path.join(directory, self.subdir) if directory not in self._extra_dirs: # append the directory and invalidate the path cache self._extra_dirs.append(directory) self._clear_caches() display.debug('Added %s to loader search path' % (directory)) def _query_collection_routing_meta(self, acr, plugin_type, extension=None): collection_pkg = import_module(acr.n_python_collection_package_name) if not collection_pkg: return None # FIXME: shouldn't need this... try: # force any type-specific metadata postprocessing to occur import_module(acr.n_python_collection_package_name + '.plugins.{0}'.format(plugin_type)) except ImportError: pass # this will be created by the collection PEP302 loader collection_meta = getattr(collection_pkg, '_collection_meta', None) if not collection_meta: return None # TODO: add subdirs support # check for extension-specific entry first (eg 'setup.ps1') # TODO: str/bytes on extension/name munging if acr.subdirs: subdir_qualified_resource = '.'.join([acr.subdirs, acr.resource]) else: subdir_qualified_resource = acr.resource entry = collection_meta.get('plugin_routing', {}).get(plugin_type, {}).get(subdir_qualified_resource + extension, None) if not entry: # try for extension-agnostic entry entry = collection_meta.get('plugin_routing', {}).get(plugin_type, {}).get(subdir_qualified_resource, None) return entry def _find_fq_plugin(self, fq_name, extension, plugin_load_context): """Search builtin paths to find a plugin. No external paths are searched, meaning plugins inside roles inside collections will be ignored. """ plugin_load_context.resolved = False plugin_type = AnsibleCollectionRef.legacy_plugin_dir_to_plugin_type(self.subdir) acr = AnsibleCollectionRef.from_fqcr(fq_name, plugin_type) # check collection metadata to see if any special handling is required for this plugin routing_metadata = self._query_collection_routing_meta(acr, plugin_type, extension=extension) # TODO: factor this into a wrapper method if routing_metadata: deprecation = routing_metadata.get('deprecation', None) # this will no-op if there's no deprecation metadata for this plugin plugin_load_context.record_deprecation(fq_name, deprecation, acr.collection) tombstone = routing_metadata.get('tombstone', None) # FIXME: clean up text gen if tombstone: removal_date = tombstone.get('removal_date') removal_version = tombstone.get('removal_version') warning_text = tombstone.get('warning_text') or '{0} has been removed.'.format(fq_name) removed_msg = display.get_deprecation_message(msg=warning_text, version=removal_version, date=removal_date, removed=True, collection_name=acr.collection) plugin_load_context.removal_date = removal_date plugin_load_context.removal_version = removal_version plugin_load_context.resolved = True plugin_load_context.exit_reason = removed_msg raise AnsiblePluginRemovedError(removed_msg, plugin_load_context=plugin_load_context) redirect = routing_metadata.get('redirect', None) if redirect: # FIXME: remove once this is covered in debug or whatever display.vv("redirecting (type: {0}) {1} to {2}".format(plugin_type, fq_name, redirect)) return plugin_load_context.redirect(redirect) # TODO: non-FQCN case, do we support `.` prefix for current collection, assume it with no dots, require it for subdirs in current, or ? n_resource = to_native(acr.resource, errors='strict') # we want this before the extension is added full_name = '{0}.{1}'.format(acr.n_python_package_name, n_resource) if extension: n_resource += extension pkg = sys.modules.get(acr.n_python_package_name) if not pkg: # FIXME: there must be cheaper/safer way to do this try: pkg = import_module(acr.n_python_package_name) except ImportError: return plugin_load_context.nope('Python package {0} not found'.format(acr.n_python_package_name)) pkg_path = os.path.dirname(pkg.__file__) n_resource_path = os.path.join(pkg_path, n_resource) # FIXME: and is file or file link or ... if os.path.exists(n_resource_path): return plugin_load_context.resolve( full_name, to_text(n_resource_path), acr.collection, 'found exact match for {0} in {1}'.format(full_name, acr.collection)) if extension: # the request was extension-specific, don't try for an extensionless match return plugin_load_context.nope('no match for {0} in {1}'.format(to_text(n_resource), acr.collection)) # look for any matching extension in the package location (sans filter) found_files = [f for f in glob.iglob(os.path.join(pkg_path, n_resource) + '.*') if os.path.isfile(f) and not f.endswith(C.MODULE_IGNORE_EXTS)] if not found_files: return plugin_load_context.nope('failed fuzzy extension match for {0} in {1}'.format(full_name, acr.collection)) if len(found_files) > 1: # TODO: warn? pass return plugin_load_context.resolve( full_name, to_text(found_files[0]), acr.collection, 'found fuzzy extension match for {0} in {1}'.format(full_name, acr.collection)) def find_plugin(self, name, mod_type='', ignore_deprecated=False, check_aliases=False, collection_list=None): ''' Find a plugin named name ''' result = self.find_plugin_with_context(name, mod_type, ignore_deprecated, check_aliases, collection_list) if result.resolved and result.plugin_resolved_path: return result.plugin_resolved_path return None def find_plugin_with_context(self, name, mod_type='', ignore_deprecated=False, check_aliases=False, collection_list=None): ''' Find a plugin named name, returning contextual info about the load, recursively resolving redirection ''' plugin_load_context = PluginLoadContext() plugin_load_context.original_name = name while True: result = self._resolve_plugin_step(name, mod_type, ignore_deprecated, check_aliases, collection_list, plugin_load_context=plugin_load_context) if result.pending_redirect: if result.pending_redirect in result.redirect_list: raise AnsiblePluginCircularRedirect('plugin redirect loop resolving {0} (path: {1})'.format(result.original_name, result.redirect_list)) name = result.pending_redirect result.pending_redirect = None plugin_load_context = result else: break # TODO: smuggle these to the controller when we're in a worker, reduce noise from normal things like missing plugin packages during collection search if plugin_load_context.error_list: display.warning("errors were encountered during the plugin load for {0}:\n{1}".format(name, plugin_load_context.error_list)) # TODO: display/return import_error_list? Only useful for forensics... # FIXME: store structured deprecation data in PluginLoadContext and use display.deprecate # if plugin_load_context.deprecated and C.config.get_config_value('DEPRECATION_WARNINGS'): # for dw in plugin_load_context.deprecation_warnings: # # TODO: need to smuggle these to the controller if we're in a worker context # display.warning('[DEPRECATION WARNING] ' + dw) return plugin_load_context # FIXME: name bikeshed def _resolve_plugin_step(self, name, mod_type='', ignore_deprecated=False, check_aliases=False, collection_list=None, plugin_load_context=PluginLoadContext()): if not plugin_load_context: raise ValueError('A PluginLoadContext is required') plugin_load_context.redirect_list.append(name) plugin_load_context.resolved = False global _PLUGIN_FILTERS if name in _PLUGIN_FILTERS[self.package]: plugin_load_context.exit_reason = '{0} matched a defined plugin filter'.format(name) return plugin_load_context if mod_type: suffix = mod_type elif self.class_name: # Ansible plugins that run in the controller process (most plugins) suffix = '.py' else: # Only Ansible Modules. Ansible modules can be any executable so # they can have any suffix suffix = '' # FIXME: need this right now so we can still load shipped PS module_utils- come up with a more robust solution if (AnsibleCollectionRef.is_valid_fqcr(name) or collection_list) and not name.startswith('Ansible'): if '.' in name or not collection_list: candidates = [name] else: candidates = ['{0}.{1}'.format(c, name) for c in collection_list] for candidate_name in candidates: try: plugin_load_context.load_attempts.append(candidate_name) # HACK: refactor this properly if candidate_name.startswith('ansible.legacy'): # 'ansible.legacy' refers to the plugin finding behavior used before collections existed. # They need to search 'library' and the various '*_plugins' directories in order to find the file. plugin_load_context = self._find_plugin_legacy(name.replace('ansible.legacy.', '', 1), plugin_load_context, ignore_deprecated, check_aliases, suffix) else: # 'ansible.builtin' should be handled here. This means only internal, or builtin, paths are searched. plugin_load_context = self._find_fq_plugin(candidate_name, suffix, plugin_load_context=plugin_load_context) if candidate_name != plugin_load_context.original_name and candidate_name not in plugin_load_context.redirect_list: plugin_load_context.redirect_list.append(candidate_name) if plugin_load_context.resolved or plugin_load_context.pending_redirect: # if we got an answer or need to chase down a redirect, return return plugin_load_context except (AnsiblePluginRemovedError, AnsiblePluginCircularRedirect, AnsibleCollectionUnsupportedVersionError): # these are generally fatal, let them fly raise except ImportError as ie: plugin_load_context.import_error_list.append(ie) except Exception as ex: # FIXME: keep actual errors, not just assembled messages plugin_load_context.error_list.append(to_native(ex)) if plugin_load_context.error_list: display.debug(msg='plugin lookup for {0} failed; errors: {1}'.format(name, '; '.join(plugin_load_context.error_list))) plugin_load_context.exit_reason = 'no matches found for {0}'.format(name) return plugin_load_context # if we got here, there's no collection list and it's not an FQ name, so do legacy lookup return self._find_plugin_legacy(name, plugin_load_context, ignore_deprecated, check_aliases, suffix) def _find_plugin_legacy(self, name, plugin_load_context, ignore_deprecated=False, check_aliases=False, suffix=None): """Search library and various *_plugins paths in order to find the file. This was behavior prior to the existence of collections. """ plugin_load_context.resolved = False if check_aliases: name = self.aliases.get(name, name) # The particular cache to look for modules within. This matches the # requested mod_type pull_cache = self._plugin_path_cache[suffix] try: path_with_context = pull_cache[name] plugin_load_context.plugin_resolved_path = path_with_context.path plugin_load_context.plugin_resolved_name = name plugin_load_context.plugin_resolved_collection = 'ansible.builtin' if path_with_context.internal else '' plugin_load_context.resolved = True return plugin_load_context except KeyError: # Cache miss. Now let's find the plugin pass # TODO: Instead of using the self._paths cache (PATH_CACHE) and # self._searched_paths we could use an iterator. Before enabling that # we need to make sure we don't want to add additional directories # (add_directory()) once we start using the iterator. # We can use _get_paths_with_context() since add_directory() forces a cache refresh. for path_with_context in (p for p in self._get_paths_with_context() if p.path not in self._searched_paths and os.path.isdir(to_bytes(p.path))): path = path_with_context.path b_path = to_bytes(path) display.debug('trying %s' % path) plugin_load_context.load_attempts.append(path) internal = path_with_context.internal try: full_paths = (os.path.join(b_path, f) for f in os.listdir(b_path)) except OSError as e: display.warning("Error accessing plugin paths: %s" % to_text(e)) for full_path in (to_native(f) for f in full_paths if os.path.isfile(f) and not f.endswith(b'__init__.py')): full_name = os.path.basename(full_path) # HACK: We have no way of executing python byte compiled files as ansible modules so specifically exclude them # FIXME: I believe this is only correct for modules and module_utils. # For all other plugins we want .pyc and .pyo should be valid if any(full_path.endswith(x) for x in C.MODULE_IGNORE_EXTS): continue splitname = os.path.splitext(full_name) base_name = splitname[0] try: extension = splitname[1] except IndexError: extension = '' # everything downstream expects unicode full_path = to_text(full_path, errors='surrogate_or_strict') # Module found, now enter it into the caches that match this file if base_name not in self._plugin_path_cache['']: self._plugin_path_cache[''][base_name] = PluginPathContext(full_path, internal) if full_name not in self._plugin_path_cache['']: self._plugin_path_cache[''][full_name] = PluginPathContext(full_path, internal) if base_name not in self._plugin_path_cache[extension]: self._plugin_path_cache[extension][base_name] = PluginPathContext(full_path, internal) if full_name not in self._plugin_path_cache[extension]: self._plugin_path_cache[extension][full_name] = PluginPathContext(full_path, internal) self._searched_paths.add(path) try: path_with_context = pull_cache[name] plugin_load_context.plugin_resolved_path = path_with_context.path plugin_load_context.plugin_resolved_name = name plugin_load_context.plugin_resolved_collection = 'ansible.builtin' if path_with_context.internal else '' plugin_load_context.resolved = True return plugin_load_context except KeyError: # Didn't find the plugin in this directory. Load modules from the next one pass # if nothing is found, try finding alias/deprecated if not name.startswith('_'): alias_name = '_' + name # We've already cached all the paths at this point if alias_name in pull_cache: path_with_context = pull_cache[alias_name] if not ignore_deprecated and not os.path.islink(path_with_context.path): # FIXME: this is not always the case, some are just aliases display.deprecated('%s is kept for backwards compatibility but usage is discouraged. ' # pylint: disable=ansible-deprecated-no-version 'The module documentation details page may explain more about this rationale.' % name.lstrip('_')) plugin_load_context.plugin_resolved_path = path_with_context.path plugin_load_context.plugin_resolved_name = alias_name plugin_load_context.plugin_resolved_collection = 'ansible.builtin' if path_with_context.internal else '' plugin_load_context.resolved = True return plugin_load_context # last ditch, if it's something that can be redirected, look for a builtin redirect before giving up candidate_fqcr = 'ansible.builtin.{0}'.format(name) if '.' not in name and AnsibleCollectionRef.is_valid_fqcr(candidate_fqcr): return self._find_fq_plugin(fq_name=candidate_fqcr, extension=suffix, plugin_load_context=plugin_load_context) return plugin_load_context.nope('{0} is not eligible for last-chance resolution'.format(name)) def has_plugin(self, name, collection_list=None): ''' Checks if a plugin named name exists ''' try: return self.find_plugin(name, collection_list=collection_list) is not None except Exception as ex: if isinstance(ex, AnsibleError): raise # log and continue, likely an innocuous type/package loading failure in collections import display.debug('has_plugin error: {0}'.format(to_text(ex))) __contains__ = has_plugin def _load_module_source(self, name, path): # avoid collisions across plugins if name.startswith('ansible_collections.'): full_name = name else: full_name = '.'.join([self.package, name]) if full_name in sys.modules: # Avoids double loading, See https://github.com/ansible/ansible/issues/13110 return sys.modules[full_name] with warnings.catch_warnings(): warnings.simplefilter("ignore", RuntimeWarning) if imp is None: spec = importlib.util.spec_from_file_location(to_native(full_name), to_native(path)) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) sys.modules[full_name] = module else: with open(to_bytes(path), 'rb') as module_file: # to_native is used here because imp.load_source's path is for tracebacks and python's traceback formatting uses native strings module = imp.load_source(to_native(full_name), to_native(path), module_file) return module def _update_object(self, obj, name, path, redirected_names=None): # set extra info on the module, in case we want it later setattr(obj, '_original_path', path) setattr(obj, '_load_name', name) setattr(obj, '_redirected_names', redirected_names or []) def get(self, name, *args, **kwargs): return self.get_with_context(name, *args, **kwargs).object def get_with_context(self, name, *args, **kwargs): ''' instantiates a plugin of the given name using arguments ''' found_in_cache = True class_only = kwargs.pop('class_only', False) collection_list = kwargs.pop('collection_list', None) if name in self.aliases: name = self.aliases[name] plugin_load_context = self.find_plugin_with_context(name, collection_list=collection_list) if not plugin_load_context.resolved or not plugin_load_context.plugin_resolved_path: # FIXME: this is probably an error (eg removed plugin) return get_with_context_result(None, plugin_load_context) name = plugin_load_context.plugin_resolved_name path = plugin_load_context.plugin_resolved_path redirected_names = plugin_load_context.redirect_list or [] if path not in self._module_cache: self._module_cache[path] = self._load_module_source(name, path) self._load_config_defs(name, self._module_cache[path], path) found_in_cache = False obj = getattr(self._module_cache[path], self.class_name) if self.base_class: # The import path is hardcoded and should be the right place, # so we are not expecting an ImportError. module = __import__(self.package, fromlist=[self.base_class]) # Check whether this obj has the required base class. try: plugin_class = getattr(module, self.base_class) except AttributeError: return get_with_context_result(None, plugin_load_context) if not issubclass(obj, plugin_class): return get_with_context_result(None, plugin_load_context) # FIXME: update this to use the load context self._display_plugin_load(self.class_name, name, self._searched_paths, path, found_in_cache=found_in_cache, class_only=class_only) if not class_only: try: # A plugin may need to use its _load_name in __init__ (for example, to set # or get options from config), so update the object before using the constructor instance = object.__new__(obj) self._update_object(instance, name, path, redirected_names) obj.__init__(instance, *args, **kwargs) obj = instance except TypeError as e: if "abstract" in e.args[0]: # Abstract Base Class. The found plugin file does not # fully implement the defined interface. return get_with_context_result(None, plugin_load_context) raise self._update_object(obj, name, path, redirected_names) return get_with_context_result(obj, plugin_load_context) def _display_plugin_load(self, class_name, name, searched_paths, path, found_in_cache=None, class_only=None): ''' formats data to display debug info for plugin loading, also avoids processing unless really needed ''' if C.DEFAULT_DEBUG: msg = 'Loading %s \'%s\' from %s' % (class_name, os.path.basename(name), path) if len(searched_paths) > 1: msg = '%s (searched paths: %s)' % (msg, self.format_paths(searched_paths)) if found_in_cache or class_only: msg = '%s (found_in_cache=%s, class_only=%s)' % (msg, found_in_cache, class_only) display.debug(msg) def all(self, *args, **kwargs): ''' Iterate through all plugins of this type A plugin loader is initialized with a specific type. This function is an iterator returning all of the plugins of that type to the caller. :kwarg path_only: If this is set to True, then we return the paths to where the plugins reside instead of an instance of the plugin. This conflicts with class_only and both should not be set. :kwarg class_only: If this is set to True then we return the python class which implements a plugin rather than an instance of the plugin. This conflicts with path_only and both should not be set. :kwarg _dedupe: By default, we only return one plugin per plugin name. Deduplication happens in the same way as the :meth:`get` and :meth:`find_plugin` methods resolve which plugin should take precedence. If this is set to False, then we return all of the plugins found, including those with duplicate names. In the case of duplicates, the order in which they are returned is the one that would take precedence first, followed by the others in decreasing precedence order. This should only be used by subclasses which want to manage their own deduplication of the plugins. :*args: Any extra arguments are passed to each plugin when it is instantiated. :**kwargs: Any extra keyword arguments are passed to each plugin when it is instantiated. ''' # TODO: Change the signature of this method to: # def all(return_type='instance', args=None, kwargs=None): # if args is None: args = [] # if kwargs is None: kwargs = {} # return_type can be instance, class, or path. # These changes will mean that plugin parameters won't conflict with our params and # will also make it impossible to request both a path and a class at the same time. # # Move _dedupe to be a class attribute, CUSTOM_DEDUPE, with subclasses for filters and # tests setting it to True global _PLUGIN_FILTERS dedupe = kwargs.pop('_dedupe', True) path_only = kwargs.pop('path_only', False) class_only = kwargs.pop('class_only', False) # Having both path_only and class_only is a coding bug if path_only and class_only: raise AnsibleError('Do not set both path_only and class_only when calling PluginLoader.all()') all_matches = [] found_in_cache = True for i in self._get_paths(): all_matches.extend(glob.glob(to_native(os.path.join(i, "*.py")))) loaded_modules = set() for path in sorted(all_matches, key=os.path.basename): name = os.path.splitext(path)[0] basename = os.path.basename(name) if basename == '__init__' or basename in _PLUGIN_FILTERS[self.package]: continue if dedupe and basename in loaded_modules: continue loaded_modules.add(basename) if path_only: yield path continue if path not in self._module_cache: try: if self.subdir in ('filter_plugins', 'test_plugins'): # filter and test plugin files can contain multiple plugins # they must have a unique python module name to prevent them from shadowing each other full_name = '{0}_{1}'.format(abs(hash(path)), basename) else: full_name = basename module = self._load_module_source(full_name, path) self._load_config_defs(basename, module, path) except Exception as e: display.warning("Skipping plugin (%s) as it seems to be invalid: %s" % (path, to_text(e))) continue self._module_cache[path] = module found_in_cache = False try: obj = getattr(self._module_cache[path], self.class_name) except AttributeError as e: display.warning("Skipping plugin (%s) as it seems to be invalid: %s" % (path, to_text(e))) continue if self.base_class: # The import path is hardcoded and should be the right place, # so we are not expecting an ImportError. module = __import__(self.package, fromlist=[self.base_class]) # Check whether this obj has the required base class. try: plugin_class = getattr(module, self.base_class) except AttributeError: continue if not issubclass(obj, plugin_class): continue self._display_plugin_load(self.class_name, basename, self._searched_paths, path, found_in_cache=found_in_cache, class_only=class_only) if not class_only: try: obj = obj(*args, **kwargs) except TypeError as e: display.warning("Skipping plugin (%s) as it seems to be incomplete: %s" % (path, to_text(e))) self._update_object(obj, basename, path) yield obj class Jinja2Loader(PluginLoader): """ PluginLoader optimized for Jinja2 plugins The filter and test plugins are Jinja2 plugins encapsulated inside of our plugin format. The way the calling code is setup, we need to do a few things differently in the all() method """ def find_plugin(self, name, collection_list=None): # Nothing using Jinja2Loader use this method. We can't use the base class version because # we deduplicate differently than the base class if '.' in name: return super(Jinja2Loader, self).find_plugin(name, collection_list=collection_list) raise AnsibleError('No code should call find_plugin for Jinja2Loaders (Not implemented)') def get(self, name, *args, **kwargs): # Nothing using Jinja2Loader use this method. We can't use the base class version because # we deduplicate differently than the base class if '.' in name: return super(Jinja2Loader, self).get(name, *args, **kwargs) raise AnsibleError('No code should call find_plugin for Jinja2Loaders (Not implemented)') def all(self, *args, **kwargs): """ Differences with :meth:`PluginLoader.all`: * We do not deduplicate ansible plugin names. This is because we don't care about our plugin names, here. We care about the names of the actual jinja2 plugins which are inside of our plugins. * We reverse the order of the list of plugins compared to other PluginLoaders. This is because of how calling code chooses to sync the plugins from the list. It adds all the Jinja2 plugins from one of our Ansible plugins into a dict. Then it adds the Jinja2 plugins from the next Ansible plugin, overwriting any Jinja2 plugins that had the same name. This is an encapsulation violation (the PluginLoader should not know about what calling code does with the data) but we're pushing the common code here. We'll fix this in the future by moving more of the common code into this PluginLoader. * We return a list. We could iterate the list instead but that's extra work for no gain because the API receiving this doesn't care. It just needs an iterable """ # We don't deduplicate ansible plugin names. Instead, calling code deduplicates jinja2 # plugin names. kwargs['_dedupe'] = False # We have to instantiate a list of all plugins so that we can reverse it. We reverse it so # that calling code will deduplicate this correctly. plugins = list(super(Jinja2Loader, self).all(*args, **kwargs)) plugins.reverse() return plugins def _load_plugin_filter(): filters = defaultdict(frozenset) user_set = False if C.PLUGIN_FILTERS_CFG is None: filter_cfg = '/etc/ansible/plugin_filters.yml' else: filter_cfg = C.PLUGIN_FILTERS_CFG user_set = True if os.path.exists(filter_cfg): with open(filter_cfg, 'rb') as f: try: filter_data = from_yaml(f.read()) except Exception as e: display.warning(u'The plugin filter file, {0} was not parsable.' u' Skipping: {1}'.format(filter_cfg, to_text(e))) return filters try: version = filter_data['filter_version'] except KeyError: display.warning(u'The plugin filter file, {0} was invalid.' u' Skipping.'.format(filter_cfg)) return filters # Try to convert for people specifying version as a float instead of string version = to_text(version) version = version.strip() if version == u'1.0': # Modules and action plugins share the same blacklist since the difference between the # two isn't visible to the users try: filters['ansible.modules'] = frozenset(filter_data['module_blacklist']) except TypeError: display.warning(u'Unable to parse the plugin filter file {0} as' u' module_blacklist is not a list.' u' Skipping.'.format(filter_cfg)) return filters filters['ansible.plugins.action'] = filters['ansible.modules'] else: display.warning(u'The plugin filter file, {0} was a version not recognized by this' u' version of Ansible. Skipping.'.format(filter_cfg)) else: if user_set: display.warning(u'The plugin filter file, {0} does not exist.' u' Skipping.'.format(filter_cfg)) # Specialcase the stat module as Ansible can run very few things if stat is blacklisted. if 'stat' in filters['ansible.modules']: raise AnsibleError('The stat module was specified in the module blacklist file, {0}, but' ' Ansible will not function without the stat module. Please remove stat' ' from the blacklist.'.format(to_native(filter_cfg))) return filters # since we don't want the actual collection loader understanding metadata, we'll do it in an event handler def _on_collection_load_handler(collection_name, collection_path): display.vvvv(to_text('Loading collection {0} from {1}'.format(collection_name, collection_path))) collection_meta = _get_collection_metadata(collection_name) try: if not _does_collection_support_ansible_version(collection_meta.get('requires_ansible', ''), ansible_version): mismatch_behavior = C.config.get_config_value('COLLECTIONS_ON_ANSIBLE_VERSION_MISMATCH') message = 'Collection {0} does not support Ansible version {1}'.format(collection_name, ansible_version) if mismatch_behavior == 'warning': display.warning(message) elif mismatch_behavior == 'error': raise AnsibleCollectionUnsupportedVersionError(message) except AnsibleError: raise except Exception as ex: display.warning('Error parsing collection metadata requires_ansible value from collection {0}: {1}'.format(collection_name, ex)) def _does_collection_support_ansible_version(requirement_string, ansible_version): if not requirement_string: return True if not SpecifierSet: display.warning('packaging Python module unavailable; unable to validate collection Ansible version requirements') return True ss = SpecifierSet(requirement_string) # ignore prerelease/postrelease/beta/dev flags for simplicity base_ansible_version = Version(ansible_version).base_version return ss.contains(base_ansible_version) def _configure_collection_loader(): if AnsibleCollectionConfig.collection_finder: display.warning('AnsibleCollectionFinder has already been configured') return finder = _AnsibleCollectionFinder(C.config.get_config_value('COLLECTIONS_PATHS'), C.config.get_config_value('COLLECTIONS_SCAN_SYS_PATH')) finder._install() # this should succeed now AnsibleCollectionConfig.on_collection_load += _on_collection_load_handler # TODO: All of the following is initialization code It should be moved inside of an initialization # function which is called at some point early in the ansible and ansible-playbook CLI startup. _PLUGIN_FILTERS = _load_plugin_filter() _configure_collection_loader() # doc fragments first fragment_loader = PluginLoader( 'ModuleDocFragment', 'ansible.plugins.doc_fragments', C.DOC_FRAGMENT_PLUGIN_PATH, 'doc_fragments', ) action_loader = PluginLoader( 'ActionModule', 'ansible.plugins.action', C.DEFAULT_ACTION_PLUGIN_PATH, 'action_plugins', required_base_class='ActionBase', ) cache_loader = PluginLoader( 'CacheModule', 'ansible.plugins.cache', C.DEFAULT_CACHE_PLUGIN_PATH, 'cache_plugins', ) callback_loader = PluginLoader( 'CallbackModule', 'ansible.plugins.callback', C.DEFAULT_CALLBACK_PLUGIN_PATH, 'callback_plugins', ) connection_loader = PluginLoader( 'Connection', 'ansible.plugins.connection', C.DEFAULT_CONNECTION_PLUGIN_PATH, 'connection_plugins', aliases={'paramiko': 'paramiko_ssh'}, required_base_class='ConnectionBase', ) shell_loader = PluginLoader( 'ShellModule', 'ansible.plugins.shell', 'shell_plugins', 'shell_plugins', ) module_loader = PluginLoader( '', 'ansible.modules', C.DEFAULT_MODULE_PATH, 'library', ) module_utils_loader = PluginLoader( '', 'ansible.module_utils', C.DEFAULT_MODULE_UTILS_PATH, 'module_utils', ) # NB: dedicated loader is currently necessary because PS module_utils expects "with subdir" lookup where # regular module_utils doesn't. This can be revisited once we have more granular loaders. ps_module_utils_loader = PluginLoader( '', 'ansible.module_utils', C.DEFAULT_MODULE_UTILS_PATH, 'module_utils', ) lookup_loader = PluginLoader( 'LookupModule', 'ansible.plugins.lookup', C.DEFAULT_LOOKUP_PLUGIN_PATH, 'lookup_plugins', required_base_class='LookupBase', ) filter_loader = Jinja2Loader( 'FilterModule', 'ansible.plugins.filter', C.DEFAULT_FILTER_PLUGIN_PATH, 'filter_plugins', ) test_loader = Jinja2Loader( 'TestModule', 'ansible.plugins.test', C.DEFAULT_TEST_PLUGIN_PATH, 'test_plugins' ) strategy_loader = PluginLoader( 'StrategyModule', 'ansible.plugins.strategy', C.DEFAULT_STRATEGY_PLUGIN_PATH, 'strategy_plugins', required_base_class='StrategyBase', ) terminal_loader = PluginLoader( 'TerminalModule', 'ansible.plugins.terminal', C.DEFAULT_TERMINAL_PLUGIN_PATH, 'terminal_plugins', required_base_class='TerminalBase' ) vars_loader = PluginLoader( 'VarsModule', 'ansible.plugins.vars', C.DEFAULT_VARS_PLUGIN_PATH, 'vars_plugins', ) cliconf_loader = PluginLoader( 'Cliconf', 'ansible.plugins.cliconf', C.DEFAULT_CLICONF_PLUGIN_PATH, 'cliconf_plugins', required_base_class='CliconfBase' ) netconf_loader = PluginLoader( 'Netconf', 'ansible.plugins.netconf', C.DEFAULT_NETCONF_PLUGIN_PATH, 'netconf_plugins', required_base_class='NetconfBase' ) inventory_loader = PluginLoader( 'InventoryModule', 'ansible.plugins.inventory', C.DEFAULT_INVENTORY_PLUGIN_PATH, 'inventory_plugins' ) httpapi_loader = PluginLoader( 'HttpApi', 'ansible.plugins.httpapi', C.DEFAULT_HTTPAPI_PLUGIN_PATH, 'httpapi_plugins', required_base_class='HttpApiBase', ) become_loader = PluginLoader( 'BecomeModule', 'ansible.plugins.become', C.BECOME_PLUGIN_PATH, 'become_plugins' )
tschijnmo/drudge
refs/heads/master
tests/su2_test.py
1
"""Test for the SU2 drudge.""" from sympy import Rational, I, Symbol, symbols, IndexedBase from drudge import SU2LatticeDrudge, Range def test_su2_without_symbolic_index(spark_ctx): """Test SU2 lattice drudge without abstract symbolic lattice index.""" dr = SU2LatticeDrudge(spark_ctx) p = dr.names half = Rational(1, 2) half_i = half / I # Test the basic commutation rules without explicit site or on the same # site. for ops in [ (p.J_, p.J_p, p.J_m), (p.J_[0], p.J_p[0], p.J_m[0]) ]: j_z, j_p, j_m = [dr.sum(i) for i in ops] assert (j_z | j_p).simplify() == j_p assert (j_z | j_m).simplify() == -1 * j_m assert (j_p | j_m).simplify() == 2 * j_z j_x = (j_p + j_m) * half j_y = (j_p - j_m) * half_i assert (j_x | j_y).simplify() == I * j_z assert (j_y | j_z).simplify() == I * j_x assert (j_z | j_x).simplify() == I * j_y j_sq = dr.sum( j_z * j_z + half * j_p * j_m + half * j_m * j_p ) for i in [j_x, j_y, j_z]: assert (j_sq | i).simplify() == 0 continue def test_su2_on_1d_heisenberg_model(spark_ctx): """Test the SU2 drudge on 1D Heisenberg model with abstract lattice indices. This test also acts as the test for the default resolver. """ dr = SU2LatticeDrudge(spark_ctx) l = Range('L') dr.set_dumms(l, symbols('i j k l m n')) dr.add_default_resolver(l) p = dr.names j_z = p.J_ j_p = p.J_p j_m = p.J_m i = p.i half = Rational(1, 2) coupling = Symbol('J') ham = dr.sum( (i, l), j_z[i] * j_z[i + 1] + j_p[i] * j_m[i + 1] / 2 + j_m[i] * j_p[i + 1] / 2 ) * coupling s_sq = dr.sum( (i, l), j_z[i] * j_z[i] + half * j_p[i] * j_m[i] + half * j_m[i] * j_p[i] ) comm = (ham | s_sq).simplify() assert comm == 0 def test_su2_with_deformed_commutation(spark_ctx): """Test SU2 lattice drudge with site-dependent commutation rules.""" raise_ = SU2LatticeDrudge.DEFAULT_RAISE lower = SU2LatticeDrudge.DEFAULT_LOWER cartan = SU2LatticeDrudge.DEFAULT_CARTAN alpha = IndexedBase('alpha') a = Symbol('a') dr = SU2LatticeDrudge(spark_ctx, specials={ (raise_[a], lower[a]): alpha[a] * cartan[a] - 1 }) assert dr.simplify(cartan[a] | raise_[a]) == dr.sum(raise_[a]) assert dr.simplify(cartan[a] | lower[a]) == dr.sum(-lower[a]) assert dr.simplify(raise_[a] | lower[a]) == dr.sum( alpha[a] * cartan[a] - 1 ).simplify() assert dr.simplify(lower[a] | raise_[a]) == dr.sum( 1 - alpha[a] * cartan[a] ).simplify() assert dr.simplify(raise_[1] | lower[2]) == 0
SciencesPo/WebPo
refs/heads/master
__main__.py
1
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys site=None if len(sys.argv) == 1: print "Name of site is missing. usage : $ python WebPo mySite" pass else: site=sys.argv[1] sys.argv.remove(sys.argv[1]) MAIN_GFOLDER = '0BziWsJYs4XsYa0R1Z0UyYjBGcVk' SITEMAPPING = '1G2r5JHioBuV3otbZO5KVurKfhHY5b7EmDafoc3WjB0E' if site: from gooThon.gsettings import gsettings import gooThon.goo #get Gdrive folder ID folderId = gsettings(SITEMAPPING, site).getId() # get list of files inside folder ID files = gooThon.goo.main('list', folderId, None) for f in files: #get the content of the file mime = 'text/plain' if f['mime'] == 'application/vnd.google-apps.spreadsheet': mime = 'text/csv' elif f['mime'] == 'application/vnd.google-apps.document': mime = 'text/html' content = gooThon.goo.main('content', f['id'], mime) # #convert the content to usable html import gooThon.htmlcreator content = gooThon.htmlcreator.main(content, mime, f['name']) print content #push html file to pelican folder import os BASEDIR = os.getcwd() dirfile = BASEDIR + '/WebPo/pelican/content/'+f['name']+'.html' fi = open(dirfile, 'w') fi.write(content) fi.closed print "DONE!!"
goliveirab/odoo
refs/heads/8.0
addons/account/wizard/account_period_close.py
341
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ class account_period_close(osv.osv_memory): """ close period """ _name = "account.period.close" _description = "period close" _columns = { 'sure': fields.boolean('Check this box'), } def data_save(self, cr, uid, ids, context=None): """ This function close period @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: account period close’s ID or list of IDs """ journal_period_pool = self.pool.get('account.journal.period') period_pool = self.pool.get('account.period') account_move_obj = self.pool.get('account.move') mode = 'done' for form in self.read(cr, uid, ids, context=context): if form['sure']: for id in context['active_ids']: account_move_ids = account_move_obj.search(cr, uid, [('period_id', '=', id), ('state', '=', "draft")], context=context) if account_move_ids: raise osv.except_osv(_('Invalid Action!'), _('In order to close a period, you must first post related journal entries.')) cr.execute('update account_journal_period set state=%s where period_id=%s', (mode, id)) cr.execute('update account_period set state=%s where id=%s', (mode, id)) self.invalidate_cache(cr, uid, context=context) return {'type': 'ir.actions.act_window_close'} # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
flyfei/python-for-android
refs/heads/master
python3-alpha/python3-src/Lib/distutils/command/sdist.py
46
"""distutils.command.sdist Implements the Distutils 'sdist' command (create a source distribution).""" import os import string import sys from types import * from glob import glob from warnings import warn from distutils.core import Command from distutils import dir_util, dep_util, file_util, archive_util from distutils.text_file import TextFile from distutils.errors import * from distutils.filelist import FileList from distutils import log from distutils.util import convert_path def show_formats(): """Print all possible values for the 'formats' option (used by the "--help-formats" command-line option). """ from distutils.fancy_getopt import FancyGetopt from distutils.archive_util import ARCHIVE_FORMATS formats = [] for format in ARCHIVE_FORMATS.keys(): formats.append(("formats=" + format, None, ARCHIVE_FORMATS[format][2])) formats.sort() FancyGetopt(formats).print_help( "List of available source distribution formats:") class sdist(Command): description = "create a source distribution (tarball, zip file, etc.)" def checking_metadata(self): """Callable used for the check sub-command. Placed here so user_options can view it""" return self.metadata_check user_options = [ ('template=', 't', "name of manifest template file [default: MANIFEST.in]"), ('manifest=', 'm', "name of manifest file [default: MANIFEST]"), ('use-defaults', None, "include the default file set in the manifest " "[default; disable with --no-defaults]"), ('no-defaults', None, "don't include the default file set"), ('prune', None, "specifically exclude files/directories that should not be " "distributed (build tree, RCS/CVS dirs, etc.) " "[default; disable with --no-prune]"), ('no-prune', None, "don't automatically exclude anything"), ('manifest-only', 'o', "just regenerate the manifest and then stop " "(implies --force-manifest)"), ('force-manifest', 'f', "forcibly regenerate the manifest and carry on as usual. " "Deprecated: now the manifest is always regenerated."), ('formats=', None, "formats for source distribution (comma-separated list)"), ('keep-temp', 'k', "keep the distribution tree around after creating " + "archive file(s)"), ('dist-dir=', 'd', "directory to put the source distribution archive(s) in " "[default: dist]"), ('metadata-check', None, "Ensure that all required elements of meta-data " "are supplied. Warn if any missing. [default]"), ] boolean_options = ['use-defaults', 'prune', 'manifest-only', 'force-manifest', 'keep-temp', 'metadata-check'] help_options = [ ('help-formats', None, "list available distribution formats", show_formats), ] negative_opt = {'no-defaults': 'use-defaults', 'no-prune': 'prune' } default_format = {'posix': 'gztar', 'nt': 'zip' } sub_commands = [('check', checking_metadata)] def initialize_options(self): # 'template' and 'manifest' are, respectively, the names of # the manifest template and manifest file. self.template = None self.manifest = None # 'use_defaults': if true, we will include the default file set # in the manifest self.use_defaults = 1 self.prune = 1 self.manifest_only = 0 self.force_manifest = 0 self.formats = None self.keep_temp = 0 self.dist_dir = None self.archive_files = None self.metadata_check = 1 def finalize_options(self): if self.manifest is None: self.manifest = "MANIFEST" if self.template is None: self.template = "MANIFEST.in" self.ensure_string_list('formats') if self.formats is None: try: self.formats = [self.default_format[os.name]] except KeyError: raise DistutilsPlatformError( "don't know how to create source distributions " "on platform %s" % os.name) bad_format = archive_util.check_archive_formats(self.formats) if bad_format: raise DistutilsOptionError( "unknown archive format '%s'" % bad_format) if self.dist_dir is None: self.dist_dir = "dist" def run(self): # 'filelist' contains the list of files that will make up the # manifest self.filelist = FileList() # Run sub commands for cmd_name in self.get_sub_commands(): self.run_command(cmd_name) # Do whatever it takes to get the list of files to process # (process the manifest template, read an existing manifest, # whatever). File list is accumulated in 'self.filelist'. self.get_file_list() # If user just wanted us to regenerate the manifest, stop now. if self.manifest_only: return # Otherwise, go ahead and create the source distribution tarball, # or zipfile, or whatever. self.make_distribution() def check_metadata(self): """Deprecated API.""" warn("distutils.command.sdist.check_metadata is deprecated, \ use the check command instead", PendingDeprecationWarning) check = self.distribution.get_command_obj('check') check.ensure_finalized() check.run() def get_file_list(self): """Figure out the list of files to include in the source distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all depends on the user's options. """ # new behavior when using a template: # the file list is recalculated everytime because # even if MANIFEST.in or setup.py are not changed # the user might have added some files in the tree that # need to be included. # # This makes --force the default and only behavior with templates. template_exists = os.path.isfile(self.template) if not template_exists and self._manifest_is_not_generated(): self.read_manifest() self.filelist.sort() self.filelist.remove_duplicates() return if not template_exists: self.warn(("manifest template '%s' does not exist " + "(using default file list)") % self.template) self.filelist.findall() if self.use_defaults: self.add_defaults() if template_exists: self.read_template() if self.prune: self.prune_file_list() self.filelist.sort() self.filelist.remove_duplicates() self.write_manifest() def add_defaults(self): """Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all files pointed by package_data (build_py) - all files defined in data_files. - all files defined as scripts. - all C sources listed as part of extensions or C libraries in the setup script (doesn't catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional. """ standards = [('README', 'README.txt'), self.distribution.script_name] for fn in standards: if isinstance(fn, tuple): alts = fn got_it = False for fn in alts: if os.path.exists(fn): got_it = True self.filelist.append(fn) break if not got_it: self.warn("standard file not found: should have one of " + ', '.join(alts)) else: if os.path.exists(fn): self.filelist.append(fn) else: self.warn("standard file '%s' not found" % fn) optional = ['test/test*.py', 'setup.cfg'] for pattern in optional: files = filter(os.path.isfile, glob(pattern)) self.filelist.extend(files) # build_py is used to get: # - python modules # - files defined in package_data build_py = self.get_finalized_command('build_py') # getting python files if self.distribution.has_pure_modules(): self.filelist.extend(build_py.get_source_files()) # getting package_data files # (computed in build_py.data_files by build_py.finalize_options) for pkg, src_dir, build_dir, filenames in build_py.data_files: for filename in filenames: self.filelist.append(os.path.join(src_dir, filename)) # getting distribution.data_files if self.distribution.has_data_files(): for item in self.distribution.data_files: if isinstance(item, str): # plain file item = convert_path(item) if os.path.isfile(item): self.filelist.append(item) else: # a (dirname, filenames) tuple dirname, filenames = item for f in filenames: f = convert_path(f) if os.path.isfile(f): self.filelist.append(f) if self.distribution.has_ext_modules(): build_ext = self.get_finalized_command('build_ext') self.filelist.extend(build_ext.get_source_files()) if self.distribution.has_c_libraries(): build_clib = self.get_finalized_command('build_clib') self.filelist.extend(build_clib.get_source_files()) if self.distribution.has_scripts(): build_scripts = self.get_finalized_command('build_scripts') self.filelist.extend(build_scripts.get_source_files()) def read_template(self): """Read and parse manifest template file named by self.template. (usually "MANIFEST.in") The parsing and processing is done by 'self.filelist', which updates itself accordingly. """ log.info("reading manifest template '%s'", self.template) template = TextFile(self.template, strip_comments=1, skip_blanks=1, join_lines=1, lstrip_ws=1, rstrip_ws=1, collapse_join=1) try: while True: line = template.readline() if line is None: # end of file break try: self.filelist.process_template_line(line) except DistutilsTemplateError as msg: self.warn("%s, line %d: %s" % (template.filename, template.current_line, msg)) finally: template.close() def prune_file_list(self): """Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-temp, or it aborted) * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories """ build = self.get_finalized_command('build') base_dir = self.distribution.get_fullname() self.filelist.exclude_pattern(None, prefix=build.build_base) self.filelist.exclude_pattern(None, prefix=base_dir) if sys.platform == 'win32': seps = r'/|\\' else: seps = '/' vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', '_darcs'] vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps) self.filelist.exclude_pattern(vcs_ptrn, is_regex=1) def write_manifest(self): """Write the file list in 'self.filelist' (presumably as filled in by 'add_defaults()' and 'read_template()') to the manifest file named by 'self.manifest'. """ if self._manifest_is_not_generated(): log.info("not writing to manually maintained " "manifest file '%s'" % self.manifest) return content = self.filelist.files[:] content.insert(0, '# file GENERATED by distutils, do NOT edit') self.execute(file_util.write_file, (self.manifest, content), "writing manifest file '%s'" % self.manifest) def _manifest_is_not_generated(self): # check for special comment used in 3.1.3 and higher if not os.path.isfile(self.manifest): return False fp = open(self.manifest) try: first_line = fp.readline() finally: fp.close() return first_line != '# file GENERATED by distutils, do NOT edit\n' def read_manifest(self): """Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution. """ log.info("reading manifest file '%s'", self.manifest) manifest = open(self.manifest) for line in manifest: # ignore comments and blank lines line = line.strip() if line.startswith('#') or not line: continue self.filelist.append(line) manifest.close() def make_release_tree(self, base_dir, files): """Create the directory tree that will become the source distribution archive. All directories implied by the filenames in 'files' are created under 'base_dir', and then we hard link or copy (if hard linking is unavailable) those files into place. Essentially, this duplicates the developer's source tree, but in a directory named after the distribution, containing only the files to be distributed. """ # Create all the directories under 'base_dir' necessary to # put 'files' there; the 'mkpath()' is just so we don't die # if the manifest happens to be empty. self.mkpath(base_dir) dir_util.create_tree(base_dir, files, dry_run=self.dry_run) # And walk over the list of files, either making a hard link (if # os.link exists) to each one that doesn't already exist in its # corresponding location under 'base_dir', or copying each file # that's out-of-date in 'base_dir'. (Usually, all files will be # out-of-date, because by default we blow away 'base_dir' when # we're done making the distribution archives.) if hasattr(os, 'link'): # can make hard links on this system link = 'hard' msg = "making hard links in %s..." % base_dir else: # nope, have to copy link = None msg = "copying files to %s..." % base_dir if not files: log.warn("no files to distribute -- empty manifest?") else: log.info(msg) for file in files: if not os.path.isfile(file): log.warn("'%s' not a regular file -- skipping" % file) else: dest = os.path.join(base_dir, file) self.copy_file(file, dest, link=link) self.distribution.metadata.write_pkg_info(base_dir) def make_distribution(self): """Create the source distribution(s). First, we create the release tree with 'make_release_tree()'; then, we create all required archive files (according to 'self.formats') from the release tree. Finally, we clean up by blowing away the release tree (unless 'self.keep_temp' is true). The list of archive files created is stored so it can be retrieved later by 'get_archive_files()'. """ # Don't warn about missing meta-data here -- should be (and is!) # done elsewhere. base_dir = self.distribution.get_fullname() base_name = os.path.join(self.dist_dir, base_dir) self.make_release_tree(base_dir, self.filelist.files) archive_files = [] # remember names of files we create # tar archive must be created last to avoid overwrite and remove if 'tar' in self.formats: self.formats.append(self.formats.pop(self.formats.index('tar'))) for fmt in self.formats: file = self.make_archive(base_name, fmt, base_dir=base_dir) archive_files.append(file) self.distribution.dist_files.append(('sdist', '', file)) self.archive_files = archive_files if not self.keep_temp: dir_util.remove_tree(base_dir, dry_run=self.dry_run) def get_archive_files(self): """Return the list of archive files created when the command was run, or None if the command hasn't run yet. """ return self.archive_files
viewfinderco/viewfinder
refs/heads/master
backend/services/email_mgr.py
13
# -*- coding: utf-8 -*- # Copyright 2012 Viewfinder Inc. All Rights Reserved. """Viewfinder email send manager. Example:: email_mgr = EmailManager() email_mgr.SendEmail(from=u'朋友你好 <john@doe.com>', to='blah@blah.com', subject='Hello friend', text='Just a message', html='<b>Just a message</b>', replyto='Ascii Sender <no_reply@wedoist.com>') """ __author__ = 'spencer@emailscrubbed.com (Spencer Kimball)' import base64 import logging import os import pprint import types from collections import defaultdict from copy import deepcopy from tornado import escape, gen, httpclient, options from viewfinder.backend.base import secrets from viewfinder.backend.base.exceptions import EmailError options.define('mailer_domain', default='mailer.viewfinder.co', help='domain from which system mail originates; this domain is setup in ' 'conjunction with sendgrid and AWS DNS records so that email sent from ' 'it is signed via DKIM, proving the origin is in fact the stated domain.') options.define('info', default='info', help='account name for system informational emails') class EmailManager(object): """Abstract email interface. Subclasses should override SendEmail. """ _instance = None _ATTRS = frozenset(['toname', 'x-smtpapi', 'fromname', 'replyto', 'date', 'files']) _REQUIRED_ATTRS = frozenset(['to', 'subject', 'from']) def SendEmail(self, callback, description=None, **kwargs): """Sends an email message. Invokes 'callback' on successful completion. All Unicode strings will be encoded. Subclasses should call self._ValidateArgs. """ raise NotImplementedError() def _ValidateArgs(self, kwargs): if 'text' not in kwargs and 'html' not in kwargs: raise EmailError('message not sent; \'text\' or \'html\' fields required') for required in self._REQUIRED_ATTRS: if required not in kwargs: raise EmailError('message not sent; missing required argument %s' % required) def GetInfoAddress(self): """Returns the address for system informational emails (e.g. info@mailer.viewfinder.co). """ return '%s@%s' % (options.options.info, options.options.mailer_domain) @staticmethod def Instance(): assert hasattr(EmailManager, '_instance'), 'instance not initialized' return EmailManager._instance @staticmethod def SetInstance(email_mgr): """Sets a new instance for testing.""" EmailManager._instance = email_mgr class SendGridEmailManager(EmailManager): """Sends email via the send grid web API.""" _BASE_URL = 'https://sendgrid.com/api/mail.send' _FORMAT = 'json' def __init__(self): self._api_user = secrets.GetSecret('sendgrid_api_user') self._api_key = secrets.GetSecret('sendgrid_api_key') def SendEmail(self, callback, description=None, **kwargs): """Sends an email message through SendGrid. Returns 'callback' on successful completion. All unicode strings are encoded before being sent to SendGrid. """ self._ValidateArgs(kwargs) def _OnSend(response): """Parses JSON response.""" if response.error: raise EmailError('SendGrid API error: %d %.1024s [%s]' % (response.code, response.error, response.body)) result = escape.json_decode(response.body) if result.get('errors', None): raise EmailError('SendGrid API error: %s' % result['errors']) logging.info('sent email to: %s, from: %s, description: %s' % (kwargs['to'], kwargs['from'], description or '')) callback() # Add SendGrid user and key to args. kwargs = deepcopy(kwargs) kwargs.update({'api_user': self._api_user, 'api_key': self._api_key}) url = '%s.%s' % (self._BASE_URL, self._FORMAT) # Construct multi-part MIME message body. boundary = base64.urlsafe_b64encode(os.urandom(16)) body = '' for k, v in kwargs.items(): body += '--%s\r\n' % boundary body += 'Content-Disposition: form-data; name="%s"\r\n\r\n' % k body += '%s\r\n' % escape.utf8(v) body += '--%s--\r\n' % boundary # Construct the HTTP request. headers = {'Content-Type' : 'multipart/form-data; boundary=%s' % boundary} request = httpclient.HTTPRequest(url, method='POST', headers=headers, body=body) http_client = httpclient.AsyncHTTPClient() http_client.fetch(request, _OnSend) class LoggingEmailManager(EmailManager): """Dummy email API that just writes its messages to the logs.""" @gen.coroutine def SendEmail(self, description=None, **kwargs): self._ValidateArgs(kwargs) body = kwargs.pop('text') kwargs.pop('html', None) logging.info('SENDING EMAIL: %s\n%s' % (description or '', pprint.pformat(kwargs))) logging.info('MESSAGE BODY:\n%s' % body) class TestEmailManager(EmailManager): """Dummy email API that just pushes messages into a dictionary keyed by the destination email address. """ def __init__(self): self.emails = defaultdict(list) @gen.coroutine def SendEmail(self, description=None, **kwargs): self._ValidateArgs(kwargs) self.emails[kwargs['to']].append(kwargs)
biomodels/MODEL1310110034
refs/heads/master
setup.py
1
from setuptools import setup, find_packages setup(name='MODEL1310110034', version=20140916, description='MODEL1310110034 from BioModels', url='http://www.ebi.ac.uk/biomodels-main/MODEL1310110034', maintainer='Stanley Gu', maintainer_url='stanleygu@gmail.com', packages=find_packages(), package_data={'': ['*.xml', 'README.md']}, )
qisanstudio/qsapp-express
refs/heads/master
src/express/panel/account.py
1
# -*- coding: utf-8 -*- from __future__ import unicode_literals from flask import request, url_for, flash, redirect from flask.ext.admin import expose from flask.ext.admin.babel import gettext from flask.ext.admin.actions import action from studio.core.engines import db from express.models.account import (RoleModel, PrivilegeModel, AccountModel, EmailModel) from express.panel.base import BaseView class Role(BaseView): perm = 'role' column_list = ['id', 'title'] column_default_sort = ('id', True) def __init__(self, **kwargs): super(Role, self).__init__(RoleModel, db.session, **kwargs) def create_form(self, obj=None): form = super(Role, self).create_form(obj=obj) delattr(form, 'accounts') return form def edit_form(self, obj=None): form = super(Role, self).edit_form(obj=obj) delattr(form, 'accounts') return form class Privilege(BaseView): perm = 'role' column_list = ['id', 'code', 'description', 'date_created'] column_default_sort = ('date_created', True) def __init__(self, **kwargs): super(Privilege, self).__init__(PrivilegeModel, db.session, **kwargs) def create_form(self, obj=None): form = super(Privilege, self).create_form(obj=obj) delattr(form, 'date_created') return form def edit_form(self, obj=None): form = super(Privilege, self).edit_form(obj=obj) delattr(form, 'date_created') return form class Account(BaseView): perm = 'account' can_create = False column_list = ['uid', 'nickname', 'date_created'] column_default_sort = ('date_created', True) def __init__(self, **kwargs): super(Account, self).__init__(AccountModel, db.session, **kwargs) def edit_form(self, obj=None): form = super(Account, self).edit_form(obj=obj) delattr(form, 'addresses') delattr(form, 'bills') delattr(form, 'date_created') return form class Email(BaseView): perm = 'account' can_create = False can_edit = False column_list = ['uid', 'email', 'date_last_signed_in', 'date_created'] column_default_sort = ('date_last_signed_in', True) def __init__(self, **kwargs): super(Email, self).__init__(EmailModel, db.session, **kwargs)
RiccardoPecora/MP
refs/heads/master
Lib/site-packages/scipy/stats/__init__.py
58
# # stats - Statistical Functions # from info import __doc__ from stats import * from distributions import * from rv import * from morestats import * from kde import gaussian_kde import mstats #remove vonmises_cython from __all__, I don't know why it is included __all__ = filter(lambda s:not (s.startswith('_') or s.endswith('cython')),dir()) from numpy.testing import Tester test = Tester().test
meduz/NeuroTools
refs/heads/master
examples/sfn2008/sfn_example_spike2.py
3
import NeuroTools.spike2.spike2channels as spike2 import pylab, numpy """ Example to show off some capabilities of the spike2 module and the SpikeTrain and AnalogSignal class. - loads content from a CED Son file which contains data from a IF-curve experiment - then the data is processed and a IF-Curve is plotted Performed at the NeuroTools demo session, INCF booth, SfN annual meeting 2008, Washington. DC. """ # IF-curve filename = 'IF-Curve-example-data-provided-by-Florian-Rau-University-of-Freiburg-2008.smr' # load all channels in the file #all_channels = spike2.load(filename) # or only selected channels all_channels = spike2.load(filename,channels=[1,2,32]) # seperate the channels, just for better reading vm = all_channels[2] dc = all_channels[1] dc_onset_marker = all_channels[32] pylab.close('all') # show original data # vm pylab.figure() pylab.plot(vm.time_axis(),vm.signal()) # currents pylab.figure() pylab.plot(dc.time_axis(),dc.signal()) # dc_onset_markers # cutout the dc and vm around a dc step, markers are in seconds, we need them in milliseonds dc_sequence = dc.slice_by_events(dc_onset_marker.times*1000,t_min=500,t_max=1000) vm_sequence = vm.slice_by_events(dc_onset_marker.times*1000,t_min=500,t_max=1000) xlim = [1000,27000] # first figure shows the data pylab.rcParams['figure.figsize'] = [15.,10.] pylab.figure() # plot dc signal with real time subplot = pylab.subplot(2,2,1) for dc_slice in dc_sequence.values(): # we plot each dc_slice with its real time pylab.plot(dc_slice.time_axis(),dc_slice.signal) # we show only part of the data pylab.xlim(xlim) pylab.ylabel('current (pA)') pylab.title('current with real time') xmin,xmax,ymin,ymax = subplot.axis() # plot dc signal with normalized time, such that each dc_slice starts at time 0.0 pylab.subplot(2,2,2) for index, dc_slice in dc_sequence.items(): # we plot each dc_slice with its normalized time --> start at 0.0 ms if index <= 4: # only 5 slices are plotted pylab.plot(dc_slice.time_axis(normalized=True),dc_slice.signal) pylab.ylim([ymin,ymax]) pylab.title('current with normalized time') # plot vm signal with real time subplot = pylab.subplot(2,2,3) for vm_slice in vm_sequence.values(): pylab.plot(vm_slice.time_axis(),vm_slice.signal) pylab.xlim(xlim) pylab.xlabel('Time (ms)') pylab.ylabel('mp (mV)') pylab.title('mp with real time') xmin,xmax,ymin,ymax = subplot.axis() # plot vm signal with normalized time, such that each dc_slice starts at time 0.0 pylab.subplot(2,2,4) for index, vm_slice in vm_sequence.items(): if index <= 4: pylab.plot(vm_slice.time_axis(normalized=True),vm_slice.signal) pylab.xlabel('Time (ms)') pylab.title('mp with normalized time') pylab.ylim([ymin,ymax]) pylab.savefig('IF_curve_data.png') pylab.close('all') # second figure shows the IF-curve pylab.rcParams['figure.figsize'] = [6.,5.] pylab.figure() dc_inputs = [] frs = [] # calculate the actual IF-curve for dc_slice, vm_slice in zip(dc_sequence.values(), vm_sequence.values()): # we calculate the max of the dc_slice input_dc = dc_slice.max() # we perform a threshold detection on the vm slice, which returns a SpikeTrain object, this knows its mean_rate (Hz) fr = vm_slice.threshold_detection(0.0).mean_rate() # we append the values dc_inputs.append(input_dc) frs.append(fr) # and plot them pylab.plot(dc_inputs,frs,'ok',label='data') pylab.xlabel('I (pA)') pylab.ylabel('spikes/s') pylab.title('IF-curve') pylab.savefig('IF_curve_curve.png')
srgblnch/Rijndael
refs/heads/master
gRijndael/version.py
1
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### __author__ = "Sergi Blanch-Torne" __email__ = "srgblnchtrn@protonmail.ch" __copyright__ = "Copyright 2013 Sergi Blanch-Torne" __license__ = "GPLv3+" __status__ = "development" _MAJOR_VERSION = 0 _MINOR_VERSION = 4 _BUILD_VERSION = 0 _REVISION_VERSION = 0 def VERSION(): return (_MAJOR_VERSION, _MINOR_VERSION, _BUILD_VERSION, _REVISION_VERSION) def version(): return '%d.%d.%d-%d' % (_MAJOR_VERSION, _MINOR_VERSION, _BUILD_VERSION, _REVISION_VERSION)
mdworks2016/work_development
refs/heads/master
Python/20_Third_Certification/venv/lib/python3.7/site-packages/pip/_vendor/urllib3/exceptions.py
20
from __future__ import absolute_import from .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead # Base Exceptions class HTTPError(Exception): "Base exception used by this module." pass class HTTPWarning(Warning): "Base warning used by this module." pass class PoolError(HTTPError): "Base exception for errors caused within a pool." def __init__(self, pool, message): self.pool = pool HTTPError.__init__(self, "%s: %s" % (pool, message)) def __reduce__(self): # For pickling purposes. return self.__class__, (None, None) class RequestError(PoolError): "Base exception for PoolErrors that have associated URLs." def __init__(self, pool, url, message): self.url = url PoolError.__init__(self, pool, message) def __reduce__(self): # For pickling purposes. return self.__class__, (None, self.url, None) class SSLError(HTTPError): "Raised when SSL certificate fails in an HTTPS connection." pass class ProxyError(HTTPError): "Raised when the connection to a proxy fails." pass class DecodeError(HTTPError): "Raised when automatic decoding based on Content-Type fails." pass class ProtocolError(HTTPError): "Raised when something unexpected happens mid-request/response." pass #: Renamed to ProtocolError but aliased for backwards compatibility. ConnectionError = ProtocolError # Leaf Exceptions class MaxRetryError(RequestError): """Raised when the maximum number of retries is exceeded. :param pool: The connection pool :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool` :param string url: The requested Url :param exceptions.Exception reason: The underlying error """ def __init__(self, pool, url, reason=None): self.reason = reason message = "Max retries exceeded with url: %s (Caused by %r)" % (url, reason) RequestError.__init__(self, pool, url, message) class HostChangedError(RequestError): "Raised when an existing pool gets a request for a foreign host." def __init__(self, pool, url, retries=3): message = "Tried to open a foreign host with url: %s" % url RequestError.__init__(self, pool, url, message) self.retries = retries class TimeoutStateError(HTTPError): """ Raised when passing an invalid state to a timeout """ pass class TimeoutError(HTTPError): """ Raised when a socket timeout error occurs. Catching this error will catch both :exc:`ReadTimeoutErrors <ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`. """ pass class ReadTimeoutError(TimeoutError, RequestError): "Raised when a socket timeout occurs while receiving data from a server" pass # This timeout error does not have a URL attached and needs to inherit from the # base HTTPError class ConnectTimeoutError(TimeoutError): "Raised when a socket timeout occurs while connecting to a server" pass class NewConnectionError(ConnectTimeoutError, PoolError): "Raised when we fail to establish a new connection. Usually ECONNREFUSED." pass class EmptyPoolError(PoolError): "Raised when a pool runs out of connections and no more are allowed." pass class ClosedPoolError(PoolError): "Raised when a request enters a pool after the pool has been closed." pass class LocationValueError(ValueError, HTTPError): "Raised when there is something wrong with a given URL input." pass class LocationParseError(LocationValueError): "Raised when get_host or similar fails to parse the URL input." def __init__(self, location): message = "Failed to parse: %s" % location HTTPError.__init__(self, message) self.location = location class ResponseError(HTTPError): "Used as a container for an error reason supplied in a MaxRetryError." GENERIC_ERROR = "too many error responses" SPECIFIC_ERROR = "too many {status_code} error responses" class SecurityWarning(HTTPWarning): "Warned when performing security reducing actions" pass class SubjectAltNameWarning(SecurityWarning): "Warned when connecting to a host with a certificate missing a SAN." pass class InsecureRequestWarning(SecurityWarning): "Warned when making an unverified HTTPS request." pass class SystemTimeWarning(SecurityWarning): "Warned when system time is suspected to be wrong" pass class InsecurePlatformWarning(SecurityWarning): "Warned when certain SSL configuration is not available on a platform." pass class SNIMissingWarning(HTTPWarning): "Warned when making a HTTPS request without SNI available." pass class DependencyWarning(HTTPWarning): """ Warned when an attempt is made to import a module with missing optional dependencies. """ pass class ResponseNotChunked(ProtocolError, ValueError): "Response needs to be chunked in order to read it as chunks." pass class BodyNotHttplibCompatible(HTTPError): """ Body should be httplib.HTTPResponse like (have an fp attribute which returns raw chunks) for read_chunked(). """ pass class IncompleteRead(HTTPError, httplib_IncompleteRead): """ Response length doesn't match expected Content-Length Subclass of http_client.IncompleteRead to allow int value for `partial` to avoid creating large objects on streamed reads. """ def __init__(self, partial, expected): super(IncompleteRead, self).__init__(partial, expected) def __repr__(self): return "IncompleteRead(%i bytes read, %i more expected)" % ( self.partial, self.expected, ) class InvalidHeader(HTTPError): "The header provided was somehow invalid." pass class ProxySchemeUnknown(AssertionError, ValueError): "ProxyManager does not support the supplied scheme" # TODO(t-8ch): Stop inheriting from AssertionError in v2.0. def __init__(self, scheme): message = "Not supported proxy scheme %s" % scheme super(ProxySchemeUnknown, self).__init__(message) class HeaderParsingError(HTTPError): "Raised by assert_header_parsing, but we convert it to a log.warning statement." def __init__(self, defects, unparsed_data): message = "%s, unparsed data: %r" % (defects or "Unknown", unparsed_data) super(HeaderParsingError, self).__init__(message) class UnrewindableBodyError(HTTPError): "urllib3 encountered an error when trying to rewind a body" pass
jaingaurav/ansible
refs/heads/devel
test/units/errors/__init__.py
267
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type
gchp/django
refs/heads/master
tests/lookup/models.py
235
""" The lookup API This demonstrates features of the database API. """ from __future__ import unicode_literals from django.db import models from django.utils import six from django.utils.encoding import python_2_unicode_compatible class Alarm(models.Model): desc = models.CharField(max_length=100) time = models.TimeField() def __str__(self): return '%s (%s)' % (self.time, self.desc) class Author(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ('name', ) @python_2_unicode_compatible class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() author = models.ForeignKey(Author, models.SET_NULL, blank=True, null=True) class Meta: ordering = ('-pub_date', 'headline') def __str__(self): return self.headline class Tag(models.Model): articles = models.ManyToManyField(Article) name = models.CharField(max_length=100) class Meta: ordering = ('name', ) @python_2_unicode_compatible class Season(models.Model): year = models.PositiveSmallIntegerField() gt = models.IntegerField(null=True, blank=True) def __str__(self): return six.text_type(self.year) @python_2_unicode_compatible class Game(models.Model): season = models.ForeignKey(Season, models.CASCADE, related_name='games') home = models.CharField(max_length=100) away = models.CharField(max_length=100) def __str__(self): return "%s at %s" % (self.away, self.home) @python_2_unicode_compatible class Player(models.Model): name = models.CharField(max_length=100) games = models.ManyToManyField(Game, related_name='players') def __str__(self): return self.name # To test __search lookup a fulltext index is needed. This # is only available when using MySQL 5.6, or when using MyISAM # tables. As 5.6 isn't common yet, lets use MyISAM table for # testing. The table is manually created by the test method. class MyISAMArticle(models.Model): headline = models.CharField(max_length=100) class Meta: db_table = 'myisam_article' managed = False
domix/FrameworkBenchmarks
refs/heads/master
falcon/setup_pypy.py
2
import subprocess import setup_util import multiprocessing import os bin_dir = os.path.expanduser('~/FrameworkBenchmarks/installs/pypy/bin') NCPU = multiprocessing.cpu_count() proc = None def start(args): global proc proc = subprocess.Popen([ bin_dir + "/gunicorn", "app:app", '-k', 'tornado', "-b", "0.0.0.0:8080", '-w', str(NCPU*3), "--log-level=critical"], cwd="falcon") return 0 def stop(): global proc if proc is None: return 0 proc.terminate() proc = None return 0
uglyboxer/linear_neuron
refs/heads/master
net-p3/lib/python3.5/site-packages/matplotlib/tests/test_dates.py
9
from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six.moves import map import datetime import warnings import tempfile import dateutil try: # mock in python 3.3+ from unittest import mock except ImportError: import mock from nose.tools import assert_raises, assert_equal from matplotlib.testing.decorators import image_comparison, cleanup import matplotlib.pyplot as plt import matplotlib.dates as mdates @image_comparison(baseline_images=['date_empty'], extensions=['png']) def test_date_empty(): # make sure mpl does the right thing when told to plot dates even # if no date data has been presented, cf # http://sourceforge.net/tracker/?func=detail&aid=2850075&group_id=80706&atid=560720 fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.xaxis_date() @image_comparison(baseline_images=['date_axhspan'], extensions=['png']) def test_date_axhspan(): # test ax hspan with date inputs t0 = datetime.datetime(2009, 1, 20) tf = datetime.datetime(2009, 1, 21) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axhspan(t0, tf, facecolor="blue", alpha=0.25) ax.set_ylim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) fig.subplots_adjust(left=0.25) @image_comparison(baseline_images=['date_axvspan'], extensions=['png']) def test_date_axvspan(): # test ax hspan with date inputs t0 = datetime.datetime(2000, 1, 20) tf = datetime.datetime(2010, 1, 21) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axvspan(t0, tf, facecolor="blue", alpha=0.25) ax.set_xlim(t0 - datetime.timedelta(days=720), tf + datetime.timedelta(days=720)) fig.autofmt_xdate() @image_comparison(baseline_images=['date_axhline'], extensions=['png']) def test_date_axhline(): # test ax hline with date inputs t0 = datetime.datetime(2009, 1, 20) tf = datetime.datetime(2009, 1, 31) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axhline(t0, color="blue", lw=3) ax.set_ylim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) fig.subplots_adjust(left=0.25) @image_comparison(baseline_images=['date_axvline'], tol=16, extensions=['png']) def test_date_axvline(): # test ax hline with date inputs t0 = datetime.datetime(2000, 1, 20) tf = datetime.datetime(2000, 1, 21) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axvline(t0, color="red", lw=3) ax.set_xlim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) fig.autofmt_xdate() @cleanup def test_too_many_date_ticks(): # Attempt to test SF 2715172, see # https://sourceforge.net/tracker/?func=detail&aid=2715172&group_id=80706&atid=560720 # setting equal datetimes triggers and expander call in # transforms.nonsingular which results in too many ticks in the # DayLocator. This should trigger a Locator.MAXTICKS RuntimeError warnings.filterwarnings( 'ignore', 'Attempting to set identical left==right results\\nin singular ' 'transformations; automatically expanding.\\nleft=\d*\.\d*, ' 'right=\d*\.\d*', UserWarning, module='matplotlib.axes') t0 = datetime.datetime(2000, 1, 20) tf = datetime.datetime(2000, 1, 20) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim((t0, tf), auto=True) ax.plot([], []) ax.xaxis.set_major_locator(mdates.DayLocator()) assert_raises(RuntimeError, fig.savefig, 'junk.png') @image_comparison(baseline_images=['RRuleLocator_bounds'], extensions=['png']) def test_RRuleLocator(): import matplotlib.testing.jpl_units as units units.register() # This will cause the RRuleLocator to go out of bounds when it tries # to add padding to the limits, so we make sure it caps at the correct # boundary values. t0 = datetime.datetime(1000, 1, 1) tf = datetime.datetime(6000, 1, 1) fig = plt.figure() ax = plt.subplot(111) ax.set_autoscale_on(True) ax.plot([t0, tf], [0.0, 1.0], marker='o') rrule = mdates.rrulewrapper(dateutil.rrule.YEARLY, interval=500) locator = mdates.RRuleLocator(rrule) ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator)) ax.autoscale_view() fig.autofmt_xdate() @image_comparison(baseline_images=['DateFormatter_fractionalSeconds'], extensions=['png']) def test_DateFormatter(): import matplotlib.testing.jpl_units as units units.register() # Lets make sure that DateFormatter will allow us to have tick marks # at intervals of fractional seconds. t0 = datetime.datetime(2001, 1, 1, 0, 0, 0) tf = datetime.datetime(2001, 1, 1, 0, 0, 1) fig = plt.figure() ax = plt.subplot(111) ax.set_autoscale_on(True) ax.plot([t0, tf], [0.0, 1.0], marker='o') # rrule = mpldates.rrulewrapper( dateutil.rrule.YEARLY, interval=500 ) # locator = mpldates.RRuleLocator( rrule ) # ax.xaxis.set_major_locator( locator ) # ax.xaxis.set_major_formatter( mpldates.AutoDateFormatter(locator) ) ax.autoscale_view() fig.autofmt_xdate() def test_date_formatter_callable(): scale = -11 locator = mock.Mock(_get_unit=mock.Mock(return_value=scale)) callable_formatting_function = (lambda dates, _: [dt.strftime('%d-%m//%Y') for dt in dates]) formatter = mdates.AutoDateFormatter(locator) formatter.scaled[-10] = callable_formatting_function assert_equal(formatter([datetime.datetime(2014, 12, 25)]), ['25-12//2014']) def test_drange(): """ This test should check if drange works as expected, and if all the rounding errors are fixed """ start = datetime.datetime(2011, 1, 1, tzinfo=mdates.UTC) end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC) delta = datetime.timedelta(hours=1) # We expect 24 values in drange(start, end, delta), because drange returns # dates from an half open interval [start, end) assert_equal(24, len(mdates.drange(start, end, delta))) # if end is a little bit later, we expect the range to contain one element # more end = end + datetime.timedelta(microseconds=1) assert_equal(25, len(mdates.drange(start, end, delta))) # reset end end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC) # and tst drange with "complicated" floats: # 4 hours = 1/6 day, this is an "dangerous" float delta = datetime.timedelta(hours=4) daterange = mdates.drange(start, end, delta) assert_equal(6, len(daterange)) assert_equal(mdates.num2date(daterange[-1]), end - delta) @cleanup def test_empty_date_with_year_formatter(): # exposes sf bug 2861426: # https://sourceforge.net/tracker/?func=detail&aid=2861426&group_id=80706&atid=560720 # update: I am no longer believe this is a bug, as I commented on # the tracker. The question is now: what to do with this test import matplotlib.dates as dates fig = plt.figure() ax = fig.add_subplot(111) yearFmt = dates.DateFormatter('%Y') ax.xaxis.set_major_formatter(yearFmt) with tempfile.TemporaryFile() as fh: assert_raises(ValueError, fig.savefig, fh) def test_auto_date_locator(): def _create_auto_date_locator(date1, date2): locator = mdates.AutoDateLocator() locator.create_dummy_axis() locator.set_view_interval(mdates.date2num(date1), mdates.date2num(date2)) return locator d1 = datetime.datetime(1990, 1, 1) results = ([datetime.timedelta(weeks=52 * 200), ['1990-01-01 00:00:00+00:00', '2010-01-01 00:00:00+00:00', '2030-01-01 00:00:00+00:00', '2050-01-01 00:00:00+00:00', '2070-01-01 00:00:00+00:00', '2090-01-01 00:00:00+00:00', '2110-01-01 00:00:00+00:00', '2130-01-01 00:00:00+00:00', '2150-01-01 00:00:00+00:00', '2170-01-01 00:00:00+00:00'] ], [datetime.timedelta(weeks=52), ['1990-01-01 00:00:00+00:00', '1990-02-01 00:00:00+00:00', '1990-03-01 00:00:00+00:00', '1990-04-01 00:00:00+00:00', '1990-05-01 00:00:00+00:00', '1990-06-01 00:00:00+00:00', '1990-07-01 00:00:00+00:00', '1990-08-01 00:00:00+00:00', '1990-09-01 00:00:00+00:00', '1990-10-01 00:00:00+00:00', '1990-11-01 00:00:00+00:00', '1990-12-01 00:00:00+00:00'] ], [datetime.timedelta(days=140), ['1990-01-06 00:00:00+00:00', '1990-01-27 00:00:00+00:00', '1990-02-17 00:00:00+00:00', '1990-03-10 00:00:00+00:00', '1990-03-31 00:00:00+00:00', '1990-04-21 00:00:00+00:00', '1990-05-12 00:00:00+00:00'] ], [datetime.timedelta(days=40), ['1990-01-03 00:00:00+00:00', '1990-01-10 00:00:00+00:00', '1990-01-17 00:00:00+00:00', '1990-01-24 00:00:00+00:00', '1990-01-31 00:00:00+00:00', '1990-02-07 00:00:00+00:00'] ], [datetime.timedelta(hours=40), ['1990-01-01 00:00:00+00:00', '1990-01-01 04:00:00+00:00', '1990-01-01 08:00:00+00:00', '1990-01-01 12:00:00+00:00', '1990-01-01 16:00:00+00:00', '1990-01-01 20:00:00+00:00', '1990-01-02 00:00:00+00:00', '1990-01-02 04:00:00+00:00', '1990-01-02 08:00:00+00:00', '1990-01-02 12:00:00+00:00', '1990-01-02 16:00:00+00:00'] ], [datetime.timedelta(minutes=20), ['1990-01-01 00:00:00+00:00', '1990-01-01 00:05:00+00:00', '1990-01-01 00:10:00+00:00', '1990-01-01 00:15:00+00:00', '1990-01-01 00:20:00+00:00'] ], [datetime.timedelta(seconds=40), ['1990-01-01 00:00:00+00:00', '1990-01-01 00:00:05+00:00', '1990-01-01 00:00:10+00:00', '1990-01-01 00:00:15+00:00', '1990-01-01 00:00:20+00:00', '1990-01-01 00:00:25+00:00', '1990-01-01 00:00:30+00:00', '1990-01-01 00:00:35+00:00', '1990-01-01 00:00:40+00:00'] ], [datetime.timedelta(microseconds=1500), ['1989-12-31 23:59:59.999507+00:00', '1990-01-01 00:00:00+00:00', '1990-01-01 00:00:00.000502+00:00', '1990-01-01 00:00:00.001005+00:00', '1990-01-01 00:00:00.001508+00:00'] ], ) for t_delta, expected in results: d2 = d1 + t_delta locator = _create_auto_date_locator(d1, d2) assert_equal(list(map(str, mdates.num2date(locator()))), expected) @image_comparison(baseline_images=['date_inverted_limit'], extensions=['png']) def test_date_inverted_limit(): # test ax hline with date inputs t0 = datetime.datetime(2009, 1, 20) tf = datetime.datetime(2009, 1, 31) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.axhline(t0, color="blue", lw=3) ax.set_ylim(t0 - datetime.timedelta(days=5), tf + datetime.timedelta(days=5)) ax.invert_yaxis() fig.subplots_adjust(left=0.25) if __name__ == '__main__': import nose nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
GoogleCloudPlatform/PerfKitBenchmarker
refs/heads/master
perfkitbenchmarker/linux_benchmarks/gpu_pingpong_benchmark.py
1
# Copyright 2021 PerfKitBenchmarker 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. """Run GPU PingPong benchmarks. This GPU pingpong benchmark aims to test the latency between 2 GPU in 2 VMs which run TensorFlow gPRC servers. The latency contains the ping phrase time and pong phase time. """ from typing import Any, Dict, List, Tuple from absl import flags from perfkitbenchmarker import benchmark_spec from perfkitbenchmarker import configs from perfkitbenchmarker import data from perfkitbenchmarker import regex_util from perfkitbenchmarker import sample from perfkitbenchmarker import virtual_machine from perfkitbenchmarker.linux_packages import cuda_toolkit _ENV = flags.DEFINE_string( 'gpu_pingpong_env', 'PATH=/opt/conda/bin:$PATH', 'Env') FLAGS = flags.FLAGS BENCHMARK_NAME = 'gpu_pingpong' BENCHMARK_CONFIG = """ gpu_pingpong: description: Runs GPU PingPong Benchmark. vm_groups: default: vm_count: 2 vm_spec: GCP: machine_type: a2-highgpu-8g zone: us-central1-c image_family: tf2-2-4-cu110-debian-10 image_project: deeplearning-platform-release AWS: machine_type: p4d.24xlarge zone: us-east-1a image: ami-0e956fe81fa11d0a9 Azure: machine_type: Standard_ND40rs_v2 zone: eastus image: microsoft-dsvm:ubuntu-1804:1804-gen2:21.01.21 """ _TEST_SCRIPT = 'gpu_pingpong_test.py' _SERVER_SCRIPT = 'gpu_pingpong_server.py' _SERVER_ADDR = '{hostname}:{port}' _PORT = '2000' _TIMELINE_PING = (r'timeline_label: "\[4B\] \[([\d\.]+)Mb/s\] \S+ from ' '/job:worker/replica:0/task:0/device:GPU:0 to ' '/job:worker/replica:0/task:1/device:GPU:0"') _TIMELINE_PONG = (r'timeline_label: "\[4B\] \[([\d\.]+)Mb/s\] \S+ from ' '/job:worker/replica:0/task:1/device:GPU:0 to ' '/job:worker/replica:0/task:0/device:GPU:0"') def GetConfig(user_config: Dict[str, Any]) -> Dict[str, Any]: """Load and return benchmark config. Args: user_config: user supplied configuration (flags and config file) Returns: loaded benchmark configuration """ return configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME) def Prepare(bm_spec: benchmark_spec.BenchmarkSpec) -> None: """Install and set up GPU PingPong on the target vm. Args: bm_spec: The benchmark specification """ for vm in bm_spec.vms: vm.RemoteCommand(f'{_ENV.value} pip install absl-py') vm.AuthenticateVm() for script in [_TEST_SCRIPT, _SERVER_SCRIPT]: vm.PushFile(data.ResourcePath(script), script) server1, server2 = bm_spec.vms[0], bm_spec.vms[1] server1_addr = _SERVER_ADDR.format( hostname=server1.hostname, port=_PORT) server2_addr = _SERVER_ADDR.format( hostname=server2.hostname, port=_PORT) server1.RemoteCommand(f'{_ENV.value} nohup python {_SERVER_SCRIPT} ' f'{server1_addr} {server2_addr} 0 ' '1> /tmp/stdout.log 2> /tmp/stderr.log &') server2.RemoteCommand(f'{_ENV.value} nohup python {_SERVER_SCRIPT} ' f'{server1_addr} {server2_addr} 1 ' '1> /tmp/stdout.log 2> /tmp/stderr.log &') def _RunGpuPingpong(vm: virtual_machine.BaseVirtualMachine, addr: str) -> List[Tuple[float, float]]: """Returns the Ping and Pong latency times.""" stdout, stderr = vm.RemoteCommand( f'{_ENV.value} python {_TEST_SCRIPT} {addr}') ping_bws = [float(bw) for bw in regex_util.ExtractAllMatches(_TIMELINE_PING, stdout + stderr)] pong_bws = [float(bw) for bw in regex_util.ExtractAllMatches(_TIMELINE_PONG, stdout + stderr)] return list(zip(ping_bws, pong_bws)) def Run(bm_spec: benchmark_spec.BenchmarkSpec) -> List[sample.Sample]: """Run GPU PingPong test. It tests the latency between 2 GPU in 2 VMs using TensorFlow gPRC server which were started during prepare phrase. Args: bm_spec: The benchmark specification Returns: A list of sample.Sample objects. """ client_vm, server_vm = bm_spec.vms server_address = _SERVER_ADDR.format(hostname=server_vm.hostname, port=_PORT) base_metadata = cuda_toolkit.GetMetadata(client_vm) samples = [] bws = _RunGpuPingpong(client_vm, server_address) for ping_bw, pong_bw in bws[1:]: metadata = {'ping': 32 / ping_bw, 'pong': 32 / pong_bw} metadata.update(base_metadata) samples.append(sample.Sample( 'latency', 32 / ping_bw + 32 / pong_bw, 'microseconds', metadata)) return samples def Cleanup(bm_spec: benchmark_spec.BenchmarkSpec) -> None: """Cleanup GPU PingPong on the cluster. Args: bm_spec: The benchmark specification. Contains all data that is required to run the benchmark. """ del bm_spec
savanu/servo
refs/heads/master
tests/wpt/web-platform-tests/webdriver/tests/user_prompts/accept_alert.py
8
from tests.support.asserts import assert_error, assert_success def accept_alert(session): return session.transport.send("POST", "session/{session_id}/alert/accept" .format(session_id=session.session_id)) # 18.2 Accept Alert def test_no_browsing_context(session, create_window): # 18.2 step 1 session.window_handle = create_window() session.close() response = accept_alert(session) assert_error(response, "no such window") def test_no_user_prompt(session): # 18.2 step 2 response = accept_alert(session) assert_error(response, "no such alert") def test_accept_alert(session): # 18.2 step 3 session.execute_script("window.alert(\"Hello\");") response = accept_alert(session) assert_success(response) def test_accept_confirm(session): # 18.2 step 3 session.execute_script("window.result = window.confirm(\"Hello\");") response = accept_alert(session) assert_success(response) assert session.execute_script("return window.result") is True def test_accept_prompt(session): # 18.2 step 3 session.execute_script("window.result = window.prompt(\"Enter Your Name: \", \"Federer\");") response = accept_alert(session) assert_success(response) assert session.execute_script("return window.result") == "Federer"
altai/focus
refs/heads/master
focus/models/__init__.py
5
# -*- coding: utf-8 -*- # Focus # Copyright (C) 2010-2012 Grid Dynamics Consulting Services, Inc # All Rights Reserved # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program. If not, see # <http://www.gnu.org/licenses/>.
danithaca/mxnet
refs/heads/master
python/mxnet/model.py
4
# pylint: disable=fixme, invalid-name, too-many-arguments, too-many-locals, too-many-lines # pylint: disable=too-many-branches, too-many-statements """MXNet model module""" from __future__ import absolute_import, print_function import time import logging import warnings from collections import namedtuple import numpy as np from . import io from . import nd from . import symbol as sym from . import optimizer as opt from . import metric from . import kvstore as kvs from .context import Context, cpu from .initializer import Uniform from .optimizer import get_updater from .executor_manager import DataParallelExecutorManager, _check_arguments, _load_data from .io import DataDesc from .base import mx_real_t BASE_ESTIMATOR = object try: from sklearn.base import BaseEstimator BASE_ESTIMATOR = BaseEstimator except ImportError: SKLEARN_INSTALLED = False # Parameter to pass to batch_end_callback BatchEndParam = namedtuple('BatchEndParams', ['epoch', 'nbatch', 'eval_metric', 'locals']) def _create_kvstore(kvstore, num_device, arg_params): """Create kvstore This function select and create a proper kvstore if given the kvstore type. Parameters ---------- kvstore : KVStore or str The kvstore. num_device : int The number of devices arg_params : dict of str to `NDArray`. Model parameter, dict of name to `NDArray` of net's weights. """ update_on_kvstore = True if kvstore is None: kv = None elif isinstance(kvstore, kvs.KVStore): kv = kvstore elif isinstance(kvstore, str): # create kvstore using the string type if num_device is 1 and 'dist' not in kvstore: # no need to use kv for single device and single machine kv = None else: kv = kvs.create(kvstore) if kvstore == 'local': # automatically select a proper local max_size = max(np.prod(param.shape) for param in arg_params.values()) if max_size > 1024 * 1024 * 16: update_on_kvstore = False else: raise TypeError('kvstore must be KVStore, str or None') if kv is None: update_on_kvstore = False return (kv, update_on_kvstore) def _initialize_kvstore(kvstore, param_arrays, arg_params, param_names, update_on_kvstore): """Initialize kvstore""" for idx, param_on_devs in enumerate(param_arrays): kvstore.init(idx, arg_params[param_names[idx]]) if update_on_kvstore: kvstore.pull(idx, param_on_devs, priority=-idx) def _update_params_on_kvstore(param_arrays, grad_arrays, kvstore): """Perform update of param_arrays from grad_arrays on kvstore.""" for index, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, grad_list = pair if grad_list[0] is None: continue # push gradient, priority is negative index kvstore.push(index, grad_list, priority=-index) # pull back the weights kvstore.pull(index, arg_list, priority=-index) def _update_params(param_arrays, grad_arrays, updater, num_device, kvstore=None): """Perform update of param_arrays from grad_arrays not on kvstore.""" for index, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, grad_list = pair if grad_list[0] is None: continue if kvstore: # push gradient, priority is negative index kvstore.push(index, grad_list, priority=-index) # pull back the sum gradients, to the same locations. kvstore.pull(index, grad_list, priority=-index) for k, p in enumerate(zip(arg_list, grad_list)): # faked an index here, to make optimizer create diff # state for the same index but on diff devs, TODO(mli) # use a better solution latter w, g = p updater(index*num_device+k, g, w) def _multiple_callbacks(callbacks, *args, **kwargs): """Sends args and kwargs to any configured callbacks. This handles the cases where the 'callbacks' variable is ``None``, a single function, or a list. """ if isinstance(callbacks, list): for cb in callbacks: cb(*args, **kwargs) return if callbacks: callbacks(*args, **kwargs) def _train_multi_device(symbol, ctx, arg_names, param_names, aux_names, arg_params, aux_params, begin_epoch, end_epoch, epoch_size, optimizer, kvstore, update_on_kvstore, train_data, eval_data=None, eval_metric=None, epoch_end_callback=None, batch_end_callback=None, logger=None, work_load_list=None, monitor=None, eval_end_callback=None, eval_batch_end_callback=None, sym_gen=None): """Internal training function on multiple devices. This function will also work for single device as well. Parameters ---------- symbol : Symbol The network configuration. ctx : list of Context The training devices. arg_names: list of str Name of all arguments of the network. param_names: list of str Name of all trainable parameters of the network. aux_names: list of str Name of all auxiliary states of the network. arg_params : dict of str to NDArray Model parameter, dict of name to NDArray of net's weights. aux_params : dict of str to NDArray Model parameter, dict of name to NDArray of net's auxiliary states. begin_epoch : int The begining training epoch. end_epoch : int The end training epoch. epoch_size : int, optional Number of batches in a epoch. In default, it is set to ``ceil(num_train_examples / batch_size)``. optimizer : Optimizer The optimization algorithm train_data : DataIter Training data iterator. eval_data : DataIter Validation data iterator. eval_metric : EvalMetric An evaluation function or a list of evaluation functions. epoch_end_callback : callable(epoch, symbol, arg_params, aux_states) A callback that is invoked at end of each epoch. This can be used to checkpoint model each epoch. batch_end_callback : callable(BatchEndParams) A callback that is invoked at end of each batch. This can be used to measure speed, get result from evaluation metric. etc. kvstore : KVStore The KVStore. update_on_kvstore : bool Whether or not perform weight updating on kvstore. logger : logging logger When not specified, default logger will be used. work_load_list : list of float or int, optional The list of work load for different devices, in the same order as ``ctx``. monitor : Monitor, optional Monitor installed to executor, for monitoring outputs, weights, and gradients for debugging. Notes ----- - This function will inplace update the NDArrays in `arg_params` and `aux_states`. """ if logger is None: logger = logging executor_manager = DataParallelExecutorManager(symbol=symbol, sym_gen=sym_gen, ctx=ctx, train_data=train_data, param_names=param_names, arg_names=arg_names, aux_names=aux_names, work_load_list=work_load_list, logger=logger) if monitor: executor_manager.install_monitor(monitor) executor_manager.set_params(arg_params, aux_params) if not update_on_kvstore: updater = get_updater(optimizer) if kvstore: _initialize_kvstore(kvstore=kvstore, param_arrays=executor_manager.param_arrays, arg_params=arg_params, param_names=executor_manager.param_names, update_on_kvstore=update_on_kvstore) if update_on_kvstore: kvstore.set_optimizer(optimizer) # Now start training train_data.reset() for epoch in range(begin_epoch, end_epoch): # Training phase tic = time.time() eval_metric.reset() nbatch = 0 # Iterate over training data. while True: do_reset = True for data_batch in train_data: executor_manager.load_data_batch(data_batch) if monitor is not None: monitor.tic() executor_manager.forward(is_train=True) executor_manager.backward() if update_on_kvstore: _update_params_on_kvstore(executor_manager.param_arrays, executor_manager.grad_arrays, kvstore) else: _update_params(executor_manager.param_arrays, executor_manager.grad_arrays, updater=updater, num_device=len(ctx), kvstore=kvstore) if monitor is not None: monitor.toc_print() # evaluate at end, so we can lazy copy executor_manager.update_metric(eval_metric, data_batch.label) nbatch += 1 # batch callback (for print purpose) if batch_end_callback is not None: batch_end_params = BatchEndParam(epoch=epoch, nbatch=nbatch, eval_metric=eval_metric, locals=locals()) _multiple_callbacks(batch_end_callback, batch_end_params) # this epoch is done possibly earlier if epoch_size is not None and nbatch >= epoch_size: do_reset = False break if do_reset: logger.info('Epoch[%d] Resetting Data Iterator', epoch) train_data.reset() # this epoch is done if epoch_size is None or nbatch >= epoch_size: break toc = time.time() logger.info('Epoch[%d] Time cost=%.3f', epoch, (toc - tic)) if epoch_end_callback or epoch + 1 == end_epoch: executor_manager.copy_to(arg_params, aux_params) _multiple_callbacks(epoch_end_callback, epoch, symbol, arg_params, aux_params) # evaluation if eval_data: eval_metric.reset() eval_data.reset() total_num_batch = 0 for i, eval_batch in enumerate(eval_data): executor_manager.load_data_batch(eval_batch) executor_manager.forward(is_train=False) executor_manager.update_metric(eval_metric, eval_batch.label) if eval_batch_end_callback is not None: batch_end_params = BatchEndParam(epoch=epoch, nbatch=i, eval_metric=eval_metric, locals=locals()) _multiple_callbacks(eval_batch_end_callback, batch_end_params) total_num_batch += 1 if eval_end_callback is not None: eval_end_params = BatchEndParam(epoch=epoch, nbatch=total_num_batch, eval_metric=eval_metric, locals=locals()) _multiple_callbacks(eval_end_callback, eval_end_params) eval_data.reset() # end of all epochs return def save_checkpoint(prefix, epoch, symbol, arg_params, aux_params): """Checkpoint the model data into file. Parameters ---------- prefix : str Prefix of model name. epoch : int The epoch number of the model. symbol : Symbol The input Symbol. arg_params : dict of str to NDArray Model parameter, dict of name to NDArray of net's weights. aux_params : dict of str to NDArray Model parameter, dict of name to NDArray of net's auxiliary states. Notes ----- - ``prefix-symbol.json`` will be saved for symbol. - ``prefix-epoch.params`` will be saved for parameters. """ if symbol is not None: symbol.save('%s-symbol.json' % prefix) save_dict = {('arg:%s' % k) : v.as_in_context(cpu()) for k, v in arg_params.items()} save_dict.update({('aux:%s' % k) : v.as_in_context(cpu()) for k, v in aux_params.items()}) param_name = '%s-%04d.params' % (prefix, epoch) nd.save(param_name, save_dict) logging.info('Saved checkpoint to \"%s\"', param_name) def load_checkpoint(prefix, epoch): """Load model checkpoint from file. Parameters ---------- prefix : str Prefix of model name. epoch : int Epoch number of model we would like to load. Returns ------- symbol : Symbol The symbol configuration of computation network. arg_params : dict of str to NDArray Model parameter, dict of name to NDArray of net's weights. aux_params : dict of str to NDArray Model parameter, dict of name to NDArray of net's auxiliary states. Notes ----- - Symbol will be loaded from ``prefix-symbol.json``. - Parameters will be loaded from ``prefix-epoch.params``. """ symbol = sym.load('%s-symbol.json' % prefix) save_dict = nd.load('%s-%04d.params' % (prefix, epoch)) arg_params = {} aux_params = {} for k, v in save_dict.items(): tp, name = k.split(':', 1) if tp == 'arg': arg_params[name] = v if tp == 'aux': aux_params[name] = v return (symbol, arg_params, aux_params) from .callback import LogValidationMetricsCallback # pylint: disable=wrong-import-position class FeedForward(BASE_ESTIMATOR): """Model class of MXNet for training and predicting feedforward nets. This class is designed for a single-data single output supervised network. Parameters ---------- symbol : Symbol The symbol configuration of computation network. ctx : Context or list of Context, optional The device context of training and prediction. To use multi GPU training, pass in a list of gpu contexts. num_epoch : int, optional Training parameter, number of training epochs(epochs). epoch_size : int, optional Number of batches in a epoch. In default, it is set to ``ceil(num_train_examples / batch_size)``. optimizer : str or Optimizer, optional Training parameter, name or optimizer object for training. initializer : initializer function, optional Training parameter, the initialization scheme used. numpy_batch_size : int, optional The batch size of training data. Only needed when input array is numpy. arg_params : dict of str to NDArray, optional Model parameter, dict of name to NDArray of net's weights. aux_params : dict of str to NDArray, optional Model parameter, dict of name to NDArray of net's auxiliary states. allow_extra_params : boolean, optional Whether allow extra parameters that are not needed by symbol to be passed by aux_params and ``arg_params``. If this is True, no error will be thrown when ``aux_params`` and ``arg_params`` contain more parameters than needed. begin_epoch : int, optional The begining training epoch. kwargs : dict The additional keyword arguments passed to optimizer. """ def __init__(self, symbol, ctx=None, num_epoch=None, epoch_size=None, optimizer='sgd', initializer=Uniform(0.01), numpy_batch_size=128, arg_params=None, aux_params=None, allow_extra_params=False, begin_epoch=0, **kwargs): warnings.warn( '\033[91mmxnet.model.FeedForward has been deprecated. ' + \ 'Please use mxnet.mod.Module instead.\033[0m', DeprecationWarning, stacklevel=2) if isinstance(symbol, sym.Symbol): self.symbol = symbol self.sym_gen = None else: assert(callable(symbol)) self.symbol = None self.sym_gen = symbol # model parameters self.arg_params = arg_params self.aux_params = aux_params self.allow_extra_params = allow_extra_params self.argument_checked = False if self.sym_gen is None: self._check_arguments() # basic configuration if ctx is None: ctx = [cpu()] elif isinstance(ctx, Context): ctx = [ctx] self.ctx = ctx # training parameters self.num_epoch = num_epoch self.epoch_size = epoch_size self.kwargs = kwargs.copy() self.optimizer = optimizer self.initializer = initializer self.numpy_batch_size = numpy_batch_size # internal helper state self._pred_exec = None self.begin_epoch = begin_epoch def _check_arguments(self): """verify the argument of the default symbol and user provided parameters""" if self.argument_checked: return assert(self.symbol is not None) self.argument_checked = True # check if symbol contain duplicated names. _check_arguments(self.symbol) # rematch parameters to delete useless ones if self.allow_extra_params: if self.arg_params: arg_names = set(self.symbol.list_arguments()) self.arg_params = {k : v for k, v in self.arg_params.items() if k in arg_names} if self.aux_params: aux_names = set(self.symbol.list_auxiliary_states()) self.aux_params = {k : v for k, v in self.aux_params.items() if k in aux_names} @staticmethod def _is_data_arg(name): """Check if name is a data argument.""" return name.endswith('data') or name.endswith('label') def _init_params(self, inputs, overwrite=False): """Initialize weight parameters and auxiliary states.""" inputs = [x if isinstance(x, DataDesc) else DataDesc(*x) for x in inputs] input_shapes = {item.name: item.shape for item in inputs} arg_shapes, _, aux_shapes = self.symbol.infer_shape(**input_shapes) assert arg_shapes is not None input_dtypes = {item.name: item.dtype for item in inputs} arg_dtypes, _, aux_dtypes = self.symbol.infer_type(**input_dtypes) assert arg_dtypes is not None arg_names = self.symbol.list_arguments() input_names = input_shapes.keys() param_names = [key for key in arg_names if key not in input_names] aux_names = self.symbol.list_auxiliary_states() param_name_attrs = [x for x in zip(arg_names, arg_shapes, arg_dtypes) if x[0] in param_names] arg_params = {k : nd.zeros(shape=s, dtype=t) for k, s, t in param_name_attrs} aux_name_attrs = [x for x in zip(aux_names, aux_shapes, aux_dtypes) if x[0] in aux_names] aux_params = {k : nd.zeros(shape=s, dtype=t) for k, s, t in aux_name_attrs} for k, v in arg_params.items(): if self.arg_params and k in self.arg_params and (not overwrite): arg_params[k][:] = self.arg_params[k][:] else: self.initializer(k, v) for k, v in aux_params.items(): if self.aux_params and k in self.aux_params and (not overwrite): aux_params[k][:] = self.aux_params[k][:] else: self.initializer(k, v) self.arg_params = arg_params self.aux_params = aux_params return (arg_names, list(param_names), aux_names) def __getstate__(self): this = self.__dict__.copy() this['_pred_exec'] = None return this def __setstate__(self, state): self.__dict__.update(state) def _init_predictor(self, input_shapes, type_dict=None): """Initialize the predictor module for running prediction.""" if self._pred_exec is not None: arg_shapes, _, _ = self.symbol.infer_shape(**dict(input_shapes)) assert arg_shapes is not None, "Incomplete input shapes" pred_shapes = [x.shape for x in self._pred_exec.arg_arrays] if arg_shapes == pred_shapes: return # for now only use the first device pred_exec = self.symbol.simple_bind( self.ctx[0], grad_req='null', type_dict=type_dict, **dict(input_shapes)) pred_exec.copy_params_from(self.arg_params, self.aux_params) _check_arguments(self.symbol) self._pred_exec = pred_exec def _init_iter(self, X, y, is_train): """Initialize the iterator given input.""" if isinstance(X, (np.ndarray, nd.NDArray)): if y is None: if is_train: raise ValueError('y must be specified when X is numpy.ndarray') else: y = np.zeros(X.shape[0]) if not isinstance(y, (np.ndarray, nd.NDArray)): raise TypeError('y must be ndarray when X is numpy.ndarray') if X.shape[0] != y.shape[0]: raise ValueError("The numbers of data points and labels not equal") if y.ndim == 2 and y.shape[1] == 1: y = y.flatten() if y.ndim != 1: raise ValueError("Label must be 1D or 2D (with 2nd dimension being 1)") if is_train: return io.NDArrayIter(X, y, min(X.shape[0], self.numpy_batch_size), shuffle=is_train, last_batch_handle='roll_over') else: return io.NDArrayIter(X, y, min(X.shape[0], self.numpy_batch_size), shuffle=False) if not isinstance(X, io.DataIter): raise TypeError('X must be DataIter, NDArray or numpy.ndarray') return X def _init_eval_iter(self, eval_data): """Initialize the iterator given eval_data.""" if eval_data is None: return eval_data if isinstance(eval_data, (tuple, list)) and len(eval_data) == 2: if eval_data[0] is not None: if eval_data[1] is None and isinstance(eval_data[0], io.DataIter): return eval_data[0] input_data = (np.array(eval_data[0]) if isinstance(eval_data[0], list) else eval_data[0]) input_label = (np.array(eval_data[1]) if isinstance(eval_data[1], list) else eval_data[1]) return self._init_iter(input_data, input_label, is_train=True) else: raise ValueError("Eval data is NONE") if not isinstance(eval_data, io.DataIter): raise TypeError('Eval data must be DataIter, or ' \ 'NDArray/numpy.ndarray/list pair (i.e. tuple/list of length 2)') return eval_data def predict(self, X, num_batch=None, return_data=False, reset=True): """Run the prediction, always only use one device. Parameters ---------- X : mxnet.DataIter num_batch : int or None The number of batch to run. Go though all batches if ``None``. Returns ------- y : numpy.ndarray or a list of numpy.ndarray if the network has multiple outputs. The predicted value of the output. """ X = self._init_iter(X, None, is_train=False) if reset: X.reset() data_shapes = X.provide_data data_names = [x[0] for x in data_shapes] type_dict = dict((key, value.dtype) for (key, value) in self.arg_params.items()) for x in X.provide_data: if isinstance(x, DataDesc): type_dict[x.name] = x.dtype else: type_dict[x[0]] = mx_real_t self._init_predictor(data_shapes, type_dict) batch_size = X.batch_size data_arrays = [self._pred_exec.arg_dict[name] for name in data_names] output_list = [[] for _ in range(len(self._pred_exec.outputs))] if return_data: data_list = [[] for _ in X.provide_data] label_list = [[] for _ in X.provide_label] i = 0 for batch in X: _load_data(batch, data_arrays) self._pred_exec.forward(is_train=False) padded = batch.pad real_size = batch_size - padded for o_list, o_nd in zip(output_list, self._pred_exec.outputs): o_list.append(o_nd[0:real_size].asnumpy()) if return_data: for j, x in enumerate(batch.data): data_list[j].append(x[0:real_size].asnumpy()) for j, x in enumerate(batch.label): label_list[j].append(x[0:real_size].asnumpy()) i += 1 if num_batch is not None and i == num_batch: break outputs = [np.concatenate(x) for x in output_list] if len(outputs) == 1: outputs = outputs[0] if return_data: data = [np.concatenate(x) for x in data_list] label = [np.concatenate(x) for x in label_list] if len(data) == 1: data = data[0] if len(label) == 1: label = label[0] return outputs, data, label else: return outputs def score(self, X, eval_metric='acc', num_batch=None, batch_end_callback=None, reset=True): """Run the model given an input and calculate the score as assessed by an evaluation metric. Parameters ---------- X : mxnet.DataIter eval_metric : metric.metric The metric for calculating score. num_batch : int or None The number of batches to run. Go though all batches if ``None``. Returns ------- s : float The final score. """ # setup metric if not isinstance(eval_metric, metric.EvalMetric): eval_metric = metric.create(eval_metric) X = self._init_iter(X, None, is_train=False) if reset: X.reset() data_shapes = X.provide_data data_names = [x[0] for x in data_shapes] type_dict = dict((key, value.dtype) for (key, value) in self.arg_params.items()) for x in X.provide_data: if isinstance(x, DataDesc): type_dict[x.name] = x.dtype else: type_dict[x[0]] = mx_real_t self._init_predictor(data_shapes, type_dict) data_arrays = [self._pred_exec.arg_dict[name] for name in data_names] for i, batch in enumerate(X): if num_batch is not None and i == num_batch: break _load_data(batch, data_arrays) self._pred_exec.forward(is_train=False) eval_metric.update(batch.label, self._pred_exec.outputs) if batch_end_callback is not None: batch_end_params = BatchEndParam(epoch=0, nbatch=i, eval_metric=eval_metric, locals=locals()) _multiple_callbacks(batch_end_callback, batch_end_params) return eval_metric.get()[1] def fit(self, X, y=None, eval_data=None, eval_metric='acc', epoch_end_callback=None, batch_end_callback=None, kvstore='local', logger=None, work_load_list=None, monitor=None, eval_end_callback=LogValidationMetricsCallback(), eval_batch_end_callback=None): """Fit the model. Parameters ---------- X : DataIter, or numpy.ndarray/NDArray Training data. If `X` is a `DataIter`, the name or (if name not available) the position of its outputs should match the corresponding variable names defined in the symbolic graph. y : numpy.ndarray/NDArray, optional Training set label. If X is ``numpy.ndarray`` or `NDArray`, `y` is required to be set. While y can be 1D or 2D (with 2nd dimension as 1), its first dimension must be the same as `X`, i.e. the number of data points and labels should be equal. eval_data : DataIter or numpy.ndarray/list/NDArray pair If eval_data is numpy.ndarray/list/NDArray pair, it should be ``(valid_data, valid_label)``. eval_metric : metric.EvalMetric or str or callable The evaluation metric. This could be the name of evaluation metric or a custom evaluation function that returns statistics based on a minibatch. epoch_end_callback : callable(epoch, symbol, arg_params, aux_states) A callback that is invoked at end of each epoch. This can be used to checkpoint model each epoch. batch_end_callback: callable(epoch) A callback that is invoked at end of each batch for purposes of printing. kvstore: KVStore or str, optional The KVStore or a string kvstore type: 'local', 'dist_sync', 'dist_async' In default uses 'local', often no need to change for single machiine. logger : logging logger, optional When not specified, default logger will be used. work_load_list : float or int, optional The list of work load for different devices, in the same order as `ctx`. Note ---- KVStore behavior - 'local', multi-devices on a single machine, will automatically choose best type. - 'dist_sync', multiple machines communicating via BSP. - 'dist_async', multiple machines with asynchronous communication. """ data = self._init_iter(X, y, is_train=True) eval_data = self._init_eval_iter(eval_data) if self.sym_gen: self.symbol = self.sym_gen(data.default_bucket_key) # pylint: disable=no-member self._check_arguments() self.kwargs["sym"] = self.symbol arg_names, param_names, aux_names = \ self._init_params(data.provide_data+data.provide_label) # setup metric if not isinstance(eval_metric, metric.EvalMetric): eval_metric = metric.create(eval_metric) # create kvstore (kvstore, update_on_kvstore) = _create_kvstore( kvstore, len(self.ctx), self.arg_params) param_idx2name = {} if update_on_kvstore: param_idx2name.update(enumerate(param_names)) else: for i, n in enumerate(param_names): for k in range(len(self.ctx)): param_idx2name[i*len(self.ctx)+k] = n self.kwargs["param_idx2name"] = param_idx2name # init optmizer if isinstance(self.optimizer, str): batch_size = data.batch_size if kvstore and 'dist' in kvstore.type and not '_async' in kvstore.type: batch_size *= kvstore.num_workers optimizer = opt.create(self.optimizer, rescale_grad=(1.0/batch_size), **(self.kwargs)) elif isinstance(self.optimizer, opt.Optimizer): optimizer = self.optimizer # do training _train_multi_device(self.symbol, self.ctx, arg_names, param_names, aux_names, self.arg_params, self.aux_params, begin_epoch=self.begin_epoch, end_epoch=self.num_epoch, epoch_size=self.epoch_size, optimizer=optimizer, train_data=data, eval_data=eval_data, eval_metric=eval_metric, epoch_end_callback=epoch_end_callback, batch_end_callback=batch_end_callback, kvstore=kvstore, update_on_kvstore=update_on_kvstore, logger=logger, work_load_list=work_load_list, monitor=monitor, eval_end_callback=eval_end_callback, eval_batch_end_callback=eval_batch_end_callback, sym_gen=self.sym_gen) def save(self, prefix, epoch=None): """Checkpoint the model checkpoint into file. You can also use `pickle` to do the job if you only work on Python. The advantage of `load` and `save` (as compared to `pickle`) is that the resulting file can be loaded from other MXNet language bindings. One can also directly `load`/`save` from/to cloud storage(S3, HDFS) Parameters ---------- prefix : str Prefix of model name. Notes ----- - ``prefix-symbol.json`` will be saved for symbol. - ``prefix-epoch.params`` will be saved for parameters. """ if epoch is None: epoch = self.num_epoch assert epoch is not None save_checkpoint(prefix, epoch, self.symbol, self.arg_params, self.aux_params) @staticmethod def load(prefix, epoch, ctx=None, **kwargs): """Load model checkpoint from file. Parameters ---------- prefix : str Prefix of model name. epoch : int epoch number of model we would like to load. ctx : Context or list of Context, optional The device context of training and prediction. kwargs : dict Other parameters for model, including `num_epoch`, optimizer and `numpy_batch_size`. Returns ------- model : FeedForward The loaded model that can be used for prediction. Notes ----- - ``prefix-symbol.json`` will be saved for symbol. - ``prefix-epoch.params`` will be saved for parameters. """ symbol, arg_params, aux_params = load_checkpoint(prefix, epoch) return FeedForward(symbol, ctx=ctx, arg_params=arg_params, aux_params=aux_params, begin_epoch=epoch, **kwargs) @staticmethod def create(symbol, X, y=None, ctx=None, num_epoch=None, epoch_size=None, optimizer='sgd', initializer=Uniform(0.01), eval_data=None, eval_metric='acc', epoch_end_callback=None, batch_end_callback=None, kvstore='local', logger=None, work_load_list=None, eval_end_callback=LogValidationMetricsCallback(), eval_batch_end_callback=None, **kwargs): """Functional style to create a model. This function is more consistent with functional languages such as R, where mutation is not allowed. Parameters ---------- symbol : Symbol The symbol configuration of a computation network. X : DataIter Training data. y : numpy.ndarray, optional If `X` is a ``numpy.ndarray``, `y` must be set. ctx : Context or list of Context, optional The device context of training and prediction. To use multi-GPU training, pass in a list of GPU contexts. num_epoch : int, optional The number of training epochs(epochs). epoch_size : int, optional Number of batches in a epoch. In default, it is set to ``ceil(num_train_examples / batch_size)``. optimizer : str or Optimizer, optional The name of the chosen optimizer, or an optimizer object, used for training. initializier : initializer function, optional The initialization scheme used. eval_data : DataIter or numpy.ndarray pair If `eval_set` is ``numpy.ndarray`` pair, it should be (`valid_data`, `valid_label`). eval_metric : metric.EvalMetric or str or callable The evaluation metric. Can be the name of an evaluation metric or a custom evaluation function that returns statistics based on a minibatch. epoch_end_callback : callable(epoch, symbol, arg_params, aux_states) A callback that is invoked at end of each epoch. This can be used to checkpoint model each epoch. batch_end_callback: callable(epoch) A callback that is invoked at end of each batch for print purposes. kvstore: KVStore or str, optional The KVStore or a string kvstore type: 'local', 'dist_sync', 'dis_async'. Defaults to 'local', often no need to change for single machiine. logger : logging logger, optional When not specified, default logger will be used. work_load_list : list of float or int, optional The list of work load for different devices, in the same order as `ctx`. """ model = FeedForward(symbol, ctx=ctx, num_epoch=num_epoch, epoch_size=epoch_size, optimizer=optimizer, initializer=initializer, **kwargs) model.fit(X, y, eval_data=eval_data, eval_metric=eval_metric, epoch_end_callback=epoch_end_callback, batch_end_callback=batch_end_callback, kvstore=kvstore, logger=logger, work_load_list=work_load_list, eval_end_callback=eval_end_callback, eval_batch_end_callback=eval_batch_end_callback) return model
uberamd/NGECore2
refs/heads/master
scripts/object/tangible/food/generic/dish_cho_nor_hoola.py
85615
import sys def setup(core, object): return
ProjectSWGCore/NGECore2
refs/heads/master
scripts/object/tangible/loot/npc_loot/prop_jacket_generic.py
85615
import sys def setup(core, object): return
mashuai/Cassandra-Research
refs/heads/trunk
pylib/cqlshlib/test/__init__.py
146
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .cassconnect import create_test_db, remove_test_db setUp = create_test_db tearDown = remove_test_db
smillerpy/timeline
refs/heads/master
timeline/users/models.py
1
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username})
xkcd1253/SocialNetworkforTwo
refs/heads/master
db_upgrade.py
66
#!flask/bin/python from migrate.versioning import api from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) print 'Current database version: ' + str(api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO))
DataIsTheNewBlack/Django-GestionPatrimoine
refs/heads/master
sifac_landing/admin.py
47
# -*- coding: utf-8 -*- from django.contrib import admin # Register your models here.
adkerr/tempest
refs/heads/netapp/akerr
tempest/api/compute/volumes/test_volumes_negative.py
3
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import uuid from tempest.api.compute import base from tempest.common.utils import data_utils from tempest import exceptions from tempest.test import attr class VolumesNegativeTest(base.BaseV2ComputeTest): _interface = 'json' @classmethod def setUpClass(cls): super(VolumesNegativeTest, cls).setUpClass() cls.client = cls.volumes_extensions_client if not cls.config.service_available.cinder: skip_msg = ("%s skipped as Cinder is not available" % cls.__name__) raise cls.skipException(skip_msg) @attr(type=['negative', 'gate']) def test_volume_get_nonexistant_volume_id(self): # Negative: Should not be able to get details of nonexistant volume # Creating a nonexistant volume id # Trying to GET a non existant volume self.assertRaises(exceptions.NotFound, self.client.get_volume, str(uuid.uuid4())) @attr(type=['negative', 'gate']) def test_volume_delete_nonexistant_volume_id(self): # Negative: Should not be able to delete nonexistant Volume # Creating nonexistant volume id # Trying to DELETE a non existant volume self.assertRaises(exceptions.NotFound, self.client.delete_volume, str(uuid.uuid4())) @attr(type=['negative', 'gate']) def test_create_volume_with_invalid_size(self): # Negative: Should not be able to create volume with invalid size # in request v_name = data_utils.rand_name('Volume-') metadata = {'Type': 'work'} self.assertRaises(exceptions.BadRequest, self.client.create_volume, size='#$%', display_name=v_name, metadata=metadata) @attr(type=['negative', 'gate']) def test_create_volume_with_out_passing_size(self): # Negative: Should not be able to create volume without passing size # in request v_name = data_utils.rand_name('Volume-') metadata = {'Type': 'work'} self.assertRaises(exceptions.BadRequest, self.client.create_volume, size='', display_name=v_name, metadata=metadata) @attr(type=['negative', 'gate']) def test_create_volume_with_size_zero(self): # Negative: Should not be able to create volume with size zero v_name = data_utils.rand_name('Volume-') metadata = {'Type': 'work'} self.assertRaises(exceptions.BadRequest, self.client.create_volume, size='0', display_name=v_name, metadata=metadata) @attr(type=['negative', 'gate']) def test_get_invalid_volume_id(self): # Negative: Should not be able to get volume with invalid id self.assertRaises(exceptions.NotFound, self.client.get_volume, '#$%%&^&^') @attr(type=['negative', 'gate']) def test_get_volume_without_passing_volume_id(self): # Negative: Should not be able to get volume when empty ID is passed self.assertRaises(exceptions.NotFound, self.client.get_volume, '') @attr(type=['negative', 'gate']) def test_delete_invalid_volume_id(self): # Negative: Should not be able to delete volume when invalid ID is # passed self.assertRaises(exceptions.NotFound, self.client.delete_volume, '!@#$%^&*()') @attr(type=['negative', 'gate']) def test_delete_volume_without_passing_volume_id(self): # Negative: Should not be able to delete volume when empty ID is passed self.assertRaises(exceptions.NotFound, self.client.delete_volume, '') class VolumesNegativeTestXML(VolumesNegativeTest): _interface = "xml"
datafolklabs/cement
refs/heads/master
cement/utils/test.py
1
"""Cement testing utilities.""" # flake8: noqa import os import shutil from pytest import raises, skip from ..core.foundation import TestApp from ..core.exc import * from ..utils.misc import rando from ..utils import fs, shell
wenchaodudu/SNLDA
refs/heads/master
snlda.py
1
import numpy as np import itertools import pickle from sne import update_theta from lda import update_variables, dtm_update import matplotlib.pyplot as plt from sklearn.manifold import TSNE, MDS from sklearn.decomposition import LatentDirichletAllocation as LDA, PCA import progressbar import pdb import logging TOPIC_NUM = 20 DOC_NUM = 0 VOCAB_SIZE = 0 prior_std = np.sqrt(2) / 2 def admm(X, W, k, C, rho, iter_num, init=None): # initialize variables TOPIC_NUM = k DOC_NUM, VOCAB_SIZE = X.shape theta_1 = np.random.normal(scale=prior_std, size=(DOC_NUM, TOPIC_NUM)) theta_2 = np.copy(theta_1) ''' theta_1 = np.zeros((DOC_NUM, TOPIC_NUM)) theta_2 = np.zeros((DOC_NUM, TOPIC_NUM)) ''' q_z = [[] for x in range(DOC_NUM)] dirichlet_prior = np.full(TOPIC_NUM, 2) beta = np.random.dirichlet(np.full(VOCAB_SIZE, 2), TOPIC_NUM) u = np.zeros((DOC_NUM, TOPIC_NUM)) bar = progressbar.ProgressBar() if init is None: logging.info("Initializing.") for y in bar(range(VOCAB_SIZE)): for x in range(DOC_NUM): if X[x, y] > 0: q_z[x].append([y, X[x, y], np.random.dirichlet(dirichlet_prior, 1)[0]]) else: q_z = init labeled = C != -1 convergence = [] for it in range(iter_num): print it theta_2, obj, g = update_theta(theta_1, theta_2, W, C, 1 / (2 * prior_std**2), u, rho, it) theta_2 -= np.mean(theta_2, axis=1)[:, np.newaxis] theta_1, q_z, beta = update_variables(X, theta_1, theta_2, q_z, beta, C, prior_std**2, rho, u, it) theta_1 -= np.mean(theta_1, axis=1)[:, np.newaxis] u[labeled] += (theta_1[labeled] - theta_2[labeled]) conv = np.linalg.norm(theta_1[labeled] - theta_2[labeled]) convergence.append(conv) logging.info(conv) np.save('theta1', theta_1) np.save('theta2', theta_2) np.save('q_z', q_z) ''' if it % 5 == 4: solution = (theta_1 + theta_2) / 2 low_dim = TSNE().fit_transform(solution) plt.scatter(low_dim[:, 0], low_dim[:, 1], c=colors) plt.show() ''' print convergence def normalize_exp(arr): arr -= np.mean(arr, axis=1)[:, np.newaxis] arr = np.exp(arr) arr /= np.sum(arr, axis=1)[:, np.newaxis] return arr ''' solution_1 = normalize_exp(theta_1) solution_2 = normalize_exp(theta_2) solution_1[labeled] = (solution_1[labeled] + solution_2[labeled]) / 2 ''' theta_1[labeled] = (theta_1[labeled] + theta_2[labeled]) / 2 solution = theta_1 - np.mean(theta_1, axis=1)[:, np.newaxis] return theta_1 def DTM(X, C, k, iter_num, init=None): # initialize variables DOC_NUM, VOCAB_SIZE = X.shape theta = np.random.uniform(low=0, high=1, size=(DOC_NUM, TOPIC_NUM)) theta /= np.sum(theta, axis=1)[:, np.newaxis] phi = np.random.uniform(low=0, high=1, size=(TOPIC_NUM, VOCAB_SIZE)) phi /= np.sum(phi, axis=1)[:, np.newaxis] W = np.zeros((DOC_NUM, DOC_NUM)) for k in C: for x in C[k]: for y in C[k]: if y != x: W[x, y] = 1 W[y, x] = 1 dic = [] bar = progressbar.ProgressBar() for x in bar(range(DOC_NUM)): dic.append(np.nonzero(X[x])[1]) theta, phi = dtm_update(X, W, k, theta, phi, iter_num, dic) return theta if __name__ == "__main__": synth = pickle.load(open('synthetic_data')) data = synth['data'] clusters = synth['clusters'] C = dict() CC = dict() labels = np.asarray([int(clusters[x]) if np.random.uniform() < 0.2 else -1 for x in range(data.shape[0])]) categories = set(clusters) for c in categories: if c is not None: C[c] = np.where(clusters==c)[0] CC[c] = np.where(labels==c)[0] color = {0: 'g', 1: 'b', 2: 'r', 3: 'y', 4: 'm', 5: 'k', 6:'c', 7:'peru', 8:'coral', 9:'gold'} colors = [color[x] for x in clusters] solution = admm(data, CC, 20, labels, 2, 20) #solution = LDA(n_components=20, learning_method='batch', max_iter=50, n_jobs=2).fit_transform(data) low_dim = PCA(n_components=2).fit_transform(solution) plt.scatter(low_dim[:, 0], low_dim[:, 1], c=colors) plt.show()
EricNeedham/assignment-1
refs/heads/master
venv/lib/python2.7/site-packages/pip/_vendor/distlib/scripts.py
190
# -*- coding: utf-8 -*- # # Copyright (C) 2013 Vinay Sajip. # Licensed to the Python Software Foundation under a contributor agreement. # See LICENSE.txt and CONTRIBUTORS.txt. # from io import BytesIO import logging import os import re import struct import sys from .compat import sysconfig, fsencode, detect_encoding, ZipFile from .resources import finder from .util import (FileOperator, get_export_entry, convert_path, get_executable, in_venv) logger = logging.getLogger(__name__) _DEFAULT_MANIFEST = ''' <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="%s" type="win32"/> <!-- Identify the application security requirements. --> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly>'''.strip() # check if Python is called on the first line with this expression FIRST_LINE_RE = re.compile(b'^#!.*pythonw?[0-9.]*([ \t].*)?$') SCRIPT_TEMPLATE = '''# -*- coding: utf-8 -*- if __name__ == '__main__': import sys, re def _resolve(module, func): __import__(module) mod = sys.modules[module] parts = func.split('.') result = getattr(mod, parts.pop(0)) for p in parts: result = getattr(result, p) return result try: sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) func = _resolve('%(module)s', '%(func)s') rc = func() # None interpreted as 0 except Exception as e: # only supporting Python >= 2.6 sys.stderr.write('%%s\\n' %% e) rc = 1 sys.exit(rc) ''' class ScriptMaker(object): """ A class to copy or create scripts from source scripts or callable specifications. """ script_template = SCRIPT_TEMPLATE executable = None # for shebangs def __init__(self, source_dir, target_dir, add_launchers=True, dry_run=False, fileop=None): self.source_dir = source_dir self.target_dir = target_dir self.add_launchers = add_launchers self.force = False self.clobber = False # It only makes sense to set mode bits on POSIX. self.set_mode = (os.name == 'posix') self.variants = set(('', 'X.Y')) self._fileop = fileop or FileOperator(dry_run) def _get_alternate_executable(self, executable, options): if options.get('gui', False) and os.name == 'nt': dn, fn = os.path.split(executable) fn = fn.replace('python', 'pythonw') executable = os.path.join(dn, fn) return executable def _get_shebang(self, encoding, post_interp=b'', options=None): enquote = True if self.executable: executable = self.executable enquote = False # assume this will be taken care of elif not sysconfig.is_python_build(): executable = get_executable() elif in_venv(): executable = os.path.join(sysconfig.get_path('scripts'), 'python%s' % sysconfig.get_config_var('EXE')) else: executable = os.path.join( sysconfig.get_config_var('BINDIR'), 'python%s%s' % (sysconfig.get_config_var('VERSION'), sysconfig.get_config_var('EXE'))) if options: executable = self._get_alternate_executable(executable, options) # If the user didn't specify an executable, it may be necessary to # cater for executable paths with spaces (not uncommon on Windows) if enquote and ' ' in executable: executable = '"%s"' % executable executable = fsencode(executable) shebang = b'#!' + executable + post_interp + b'\n' # Python parser starts to read a script using UTF-8 until # it gets a #coding:xxx cookie. The shebang has to be the # first line of a file, the #coding:xxx cookie cannot be # written before. So the shebang has to be decodable from # UTF-8. try: shebang.decode('utf-8') except UnicodeDecodeError: raise ValueError( 'The shebang (%r) is not decodable from utf-8' % shebang) # If the script is encoded to a custom encoding (use a # #coding:xxx cookie), the shebang has to be decodable from # the script encoding too. if encoding != 'utf-8': try: shebang.decode(encoding) except UnicodeDecodeError: raise ValueError( 'The shebang (%r) is not decodable ' 'from the script encoding (%r)' % (shebang, encoding)) return shebang def _get_script_text(self, entry): return self.script_template % dict(module=entry.prefix, func=entry.suffix) manifest = _DEFAULT_MANIFEST def get_manifest(self, exename): base = os.path.basename(exename) return self.manifest % base def _write_script(self, names, shebang, script_bytes, filenames, ext): use_launcher = self.add_launchers and os.name == 'nt' linesep = os.linesep.encode('utf-8') if not use_launcher: script_bytes = shebang + linesep + script_bytes else: if ext == 'py': launcher = self._get_launcher('t') else: launcher = self._get_launcher('w') stream = BytesIO() with ZipFile(stream, 'w') as zf: zf.writestr('__main__.py', script_bytes) zip_data = stream.getvalue() script_bytes = launcher + shebang + linesep + zip_data for name in names: outname = os.path.join(self.target_dir, name) if use_launcher: n, e = os.path.splitext(outname) if e.startswith('.py'): outname = n outname = '%s.exe' % outname try: self._fileop.write_binary_file(outname, script_bytes) except Exception: # Failed writing an executable - it might be in use. logger.warning('Failed to write executable - trying to ' 'use .deleteme logic') dfname = '%s.deleteme' % outname if os.path.exists(dfname): os.remove(dfname) # Not allowed to fail here os.rename(outname, dfname) # nor here self._fileop.write_binary_file(outname, script_bytes) logger.debug('Able to replace executable using ' '.deleteme logic') try: os.remove(dfname) except Exception: pass # still in use - ignore error else: if os.name == 'nt' and not outname.endswith('.' + ext): outname = '%s.%s' % (outname, ext) if os.path.exists(outname) and not self.clobber: logger.warning('Skipping existing file %s', outname) continue self._fileop.write_binary_file(outname, script_bytes) if self.set_mode: self._fileop.set_executable_mode([outname]) filenames.append(outname) def _make_script(self, entry, filenames, options=None): shebang = self._get_shebang('utf-8', options=options) script = self._get_script_text(entry).encode('utf-8') name = entry.name scriptnames = set() if '' in self.variants: scriptnames.add(name) if 'X' in self.variants: scriptnames.add('%s%s' % (name, sys.version[0])) if 'X.Y' in self.variants: scriptnames.add('%s-%s' % (name, sys.version[:3])) if options and options.get('gui', False): ext = 'pyw' else: ext = 'py' self._write_script(scriptnames, shebang, script, filenames, ext) def _copy_script(self, script, filenames): adjust = False script = os.path.join(self.source_dir, convert_path(script)) outname = os.path.join(self.target_dir, os.path.basename(script)) if not self.force and not self._fileop.newer(script, outname): logger.debug('not copying %s (up-to-date)', script) return # Always open the file, but ignore failures in dry-run mode -- # that way, we'll get accurate feedback if we can read the # script. try: f = open(script, 'rb') except IOError: if not self.dry_run: raise f = None else: encoding, lines = detect_encoding(f.readline) f.seek(0) first_line = f.readline() if not first_line: logger.warning('%s: %s is an empty file (skipping)', self.get_command_name(), script) return match = FIRST_LINE_RE.match(first_line.replace(b'\r\n', b'\n')) if match: adjust = True post_interp = match.group(1) or b'' if not adjust: if f: f.close() self._fileop.copy_file(script, outname) if self.set_mode: self._fileop.set_executable_mode([outname]) filenames.append(outname) else: logger.info('copying and adjusting %s -> %s', script, self.target_dir) if not self._fileop.dry_run: shebang = self._get_shebang(encoding, post_interp) if b'pythonw' in first_line: ext = 'pyw' else: ext = 'py' n = os.path.basename(outname) self._write_script([n], shebang, f.read(), filenames, ext) if f: f.close() @property def dry_run(self): return self._fileop.dry_run @dry_run.setter def dry_run(self, value): self._fileop.dry_run = value if os.name == 'nt': # Executable launcher support. # Launchers are from https://bitbucket.org/vinay.sajip/simple_launcher/ def _get_launcher(self, kind): if struct.calcsize('P') == 8: # 64-bit bits = '64' else: bits = '32' name = '%s%s.exe' % (kind, bits) # Issue 31: don't hardcode an absolute package name, but # determine it relative to the current package distlib_package = __name__.rsplit('.', 1)[0] result = finder(distlib_package).find(name).bytes return result # Public API follows def make(self, specification, options=None): """ Make a script. :param specification: The specification, which is either a valid export entry specification (to make a script from a callable) or a filename (to make a script by copying from a source location). :param options: A dictionary of options controlling script generation. :return: A list of all absolute pathnames written to. """ filenames = [] entry = get_export_entry(specification) if entry is None: self._copy_script(specification, filenames) else: self._make_script(entry, filenames, options=options) return filenames def make_multiple(self, specifications, options=None): """ Take a list of specifications and make scripts from them, :param specifications: A list of specifications. :return: A list of all absolute pathnames written to, """ filenames = [] for specification in specifications: filenames.extend(self.make(specification, options)) return filenames
csmengwan/autorest
refs/heads/master
AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/models/error.py
104
# 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 msrest.serialization import Model from msrest.exceptions import HttpOperationError class Error(Model): """Error :param status: :type status: int :param message: :type message: str """ _attribute_map = { 'status': {'key': 'status', 'type': 'int'}, 'message': {'key': 'message', 'type': 'str'}, } def __init__(self, status=None, message=None): self.status = status self.message = message class ErrorException(HttpOperationError): """Server responsed with exception of type: 'Error'. :param deserialize: A deserializer :param response: Server response to be deserialized. """ def __init__(self, deserialize, response, *args): super(ErrorException, self).__init__(deserialize, response, 'Error', *args)
ProfessionalIT/maxigenios-website
refs/heads/master
sdk/google_appengine/lib/django-1.3/django/conf/global_settings.py
52
# Default Django settings. Override these with settings in the module # pointed-to by the DJANGO_SETTINGS_MODULE environment variable. # This is defined here as a do-nothing function because we can't import # django.utils.translation -- that module depends on the settings. gettext_noop = lambda s: s #################### # CORE # #################### DEBUG = False TEMPLATE_DEBUG = False # Whether the framework should propagate raw exceptions rather than catching # them. This is useful under some testing siutations and should never be used # on a live site. DEBUG_PROPAGATE_EXCEPTIONS = False # Whether to use the "Etag" header. This saves bandwidth but slows down performance. USE_ETAGS = False # People who get code error notifications. # In the format (('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com')) ADMINS = () # Tuple of IP addresses, as strings, that: # * See debug comments, when DEBUG is true # * Receive x-headers INTERNAL_IPS = () # Local time zone for this installation. All choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name (although not all # systems may support all possibilities). TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' # Languages we provide translations for, out of the box. The language name # should be the utf-8 encoded local name for the language. LANGUAGES = ( ('ar', gettext_noop('Arabic')), ('az', gettext_noop('Azerbaijani')), ('bg', gettext_noop('Bulgarian')), ('bn', gettext_noop('Bengali')), ('bs', gettext_noop('Bosnian')), ('ca', gettext_noop('Catalan')), ('cs', gettext_noop('Czech')), ('cy', gettext_noop('Welsh')), ('da', gettext_noop('Danish')), ('de', gettext_noop('German')), ('el', gettext_noop('Greek')), ('en', gettext_noop('English')), ('en-gb', gettext_noop('British English')), ('es', gettext_noop('Spanish')), ('es-ar', gettext_noop('Argentinian Spanish')), ('es-mx', gettext_noop('Mexican Spanish')), ('es-ni', gettext_noop('Nicaraguan Spanish')), ('et', gettext_noop('Estonian')), ('eu', gettext_noop('Basque')), ('fa', gettext_noop('Persian')), ('fi', gettext_noop('Finnish')), ('fr', gettext_noop('French')), ('fy-nl', gettext_noop('Frisian')), ('ga', gettext_noop('Irish')), ('gl', gettext_noop('Galician')), ('he', gettext_noop('Hebrew')), ('hi', gettext_noop('Hindi')), ('hr', gettext_noop('Croatian')), ('hu', gettext_noop('Hungarian')), ('id', gettext_noop('Indonesian')), ('is', gettext_noop('Icelandic')), ('it', gettext_noop('Italian')), ('ja', gettext_noop('Japanese')), ('ka', gettext_noop('Georgian')), ('km', gettext_noop('Khmer')), ('kn', gettext_noop('Kannada')), ('ko', gettext_noop('Korean')), ('lt', gettext_noop('Lithuanian')), ('lv', gettext_noop('Latvian')), ('mk', gettext_noop('Macedonian')), ('ml', gettext_noop('Malayalam')), ('mn', gettext_noop('Mongolian')), ('nl', gettext_noop('Dutch')), ('no', gettext_noop('Norwegian')), ('nb', gettext_noop('Norwegian Bokmal')), ('nn', gettext_noop('Norwegian Nynorsk')), ('pa', gettext_noop('Punjabi')), ('pl', gettext_noop('Polish')), ('pt', gettext_noop('Portuguese')), ('pt-br', gettext_noop('Brazilian Portuguese')), ('ro', gettext_noop('Romanian')), ('ru', gettext_noop('Russian')), ('sk', gettext_noop('Slovak')), ('sl', gettext_noop('Slovenian')), ('sq', gettext_noop('Albanian')), ('sr', gettext_noop('Serbian')), ('sr-latn', gettext_noop('Serbian Latin')), ('sv', gettext_noop('Swedish')), ('ta', gettext_noop('Tamil')), ('te', gettext_noop('Telugu')), ('th', gettext_noop('Thai')), ('tr', gettext_noop('Turkish')), ('uk', gettext_noop('Ukrainian')), ('ur', gettext_noop('Urdu')), ('vi', gettext_noop('Vietnamese')), ('zh-cn', gettext_noop('Simplified Chinese')), ('zh-tw', gettext_noop('Traditional Chinese')), ) # Languages using BiDi (right-to-left) layout LANGUAGES_BIDI = ("he", "ar", "fa") # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True LOCALE_PATHS = () LANGUAGE_COOKIE_NAME = 'django_language' # If you set this to True, Django will format dates, numbers and calendars # according to user current locale USE_L10N = False # Not-necessarily-technical managers of the site. They get broken link # notifications and other various e-mails. MANAGERS = ADMINS # Default content type and charset to use for all HttpResponse objects, if a # MIME type isn't manually specified. These are used to construct the # Content-Type header. DEFAULT_CONTENT_TYPE = 'text/html' DEFAULT_CHARSET = 'utf-8' # Encoding of files read from disk (template and initial SQL files). FILE_CHARSET = 'utf-8' # E-mail address that error messages come from. SERVER_EMAIL = 'root@localhost' # Whether to send broken-link e-mails. SEND_BROKEN_LINK_EMAILS = False # Database connection info. # Legacy format DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = '' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. DATABASE_OPTIONS = {} # Set to empty dictionary for default. # New format DATABASES = { } # Classes used to implement db routing behaviour DATABASE_ROUTERS = [] # The email backend to use. For possible shortcuts see django.core.mail. # The default is to use the SMTP backend. # Third-party backends can be specified by providing a Python path # to a module that defines an EmailBackend class. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending e-mail. EMAIL_HOST = 'localhost' # Port for sending e-mail. EMAIL_PORT = 25 # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False # List of strings representing installed apps. INSTALLED_APPS = () # List of locations of the template source files, in search order. TEMPLATE_DIRS = () # List of callables that know how to import templates from various sources. # See the comments in django/core/template/loader.py for interface # documentation. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) # List of processors used by RequestContext to populate the context. # Each one should be a callable that takes the request object as its # only parameter and returns a dictionary to add to the context. TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', # 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages', ) # Output to use in template system for invalid (e.g. misspelled) variables. TEMPLATE_STRING_IF_INVALID = '' # Default e-mail address to use for various automated correspondence from # the site managers. DEFAULT_FROM_EMAIL = 'webmaster@localhost' # Subject-line prefix for email messages send with django.core.mail.mail_admins # or ...mail_managers. Make sure to include the trailing space. EMAIL_SUBJECT_PREFIX = '[Django] ' # Whether to append trailing slashes to URLs. APPEND_SLASH = True # Whether to prepend the "www." subdomain to URLs that don't have it. PREPEND_WWW = False # Override the server-derived value of SCRIPT_NAME FORCE_SCRIPT_NAME = None # List of compiled regular expression objects representing User-Agent strings # that are not allowed to visit any page, systemwide. Use this for bad # robots/crawlers. Here are a few examples: # import re # DISALLOWED_USER_AGENTS = ( # re.compile(r'^NaverBot.*'), # re.compile(r'^EmailSiphon.*'), # re.compile(r'^SiteSucker.*'), # re.compile(r'^sohu-search') # ) DISALLOWED_USER_AGENTS = () ABSOLUTE_URL_OVERRIDES = {} # Tuple of strings representing allowed prefixes for the {% ssi %} tag. # Example: ('/home/html', '/var/www') ALLOWED_INCLUDE_ROOTS = () # If this is a admin settings module, this should be a list of # settings modules (in the format 'foo.bar.baz') for which this admin # is an admin. ADMIN_FOR = () # 404s that may be ignored. IGNORABLE_404_STARTS = ('/cgi-bin/', '/_vti_bin', '/_vti_inf') IGNORABLE_404_ENDS = ('mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi', 'favicon.ico', '.php') # A secret key for this particular Django installation. Used in secret-key # hashing algorithms. Set this in your settings, or Django will complain # loudly. SECRET_KEY = '' # Default file storage mechanism that holds media. DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. # Example: "http://media.lawrence.com/media/" MEDIA_URL = '' # Absolute path to the directory that holds static files. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL that handles the static files served from STATIC_ROOT. # Example: "http://media.lawrence.com/static/" STATIC_URL = None # List of upload handler classes to be applied in order. FILE_UPLOAD_HANDLERS = ( 'django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ) # Maximum size, in bytes, of a request before it will be streamed to the # file system instead of into memory. FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB # Directory in which upload streamed files will be temporarily saved. A value of # `None` will make Django use the operating system's default temporary directory # (i.e. "/tmp" on *nix systems). FILE_UPLOAD_TEMP_DIR = None # The numeric mode to set newly-uploaded files to. The value should be a mode # you'd pass directly to os.chmod; see http://docs.python.org/lib/os-file-dir.html. FILE_UPLOAD_PERMISSIONS = None # Python module path where user will place custom format definition. # The directory where this setting is pointing should contain subdirectories # named as the locales, containing a formats.py file # (i.e. "myproject.locale" for myproject/locale/en/formats.py etc. use) FORMAT_MODULE_PATH = None # Default formatting for date objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'N j, Y' # Default formatting for datetime objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATETIME_FORMAT = 'N j, Y, P' # Default formatting for time objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date TIME_FORMAT = 'P' # Default formatting for date objects when only the year and month are relevant. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date YEAR_MONTH_FORMAT = 'F Y' # Default formatting for date objects when only the month and day are relevant. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date MONTH_DAY_FORMAT = 'F j' # Default short formatting for date objects. See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATE_FORMAT = 'm/d/Y' # Default short formatting for datetime objects. # See all available format strings here: # http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date SHORT_DATETIME_FORMAT = 'm/d/Y P' # Default formats to be used when parsing dates from input boxes, in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATE_INPUT_FORMATS = ( '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ) # Default formats to be used when parsing times from input boxes, in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' '%H:%M', # '14:30' ) # Default formats to be used when parsing dates and times from input boxes, # in order # See all available format string here: # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATETIME_INPUT_FORMATS = ( '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y %H:%M:%S', # '10/25/2006 14:30:59' '%m/%d/%Y %H:%M', # '10/25/2006 14:30' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y %H:%M:%S', # '10/25/06 14:30:59' '%m/%d/%y %H:%M', # '10/25/06 14:30' '%m/%d/%y', # '10/25/06' ) # First day of week, to be used on calendars # 0 means Sunday, 1 means Monday... FIRST_DAY_OF_WEEK = 0 # Decimal separator symbol DECIMAL_SEPARATOR = '.' # Boolean that sets whether to add thousand separator when formatting numbers USE_THOUSAND_SEPARATOR = False # Number of digits that will be together, when spliting them by # THOUSAND_SEPARATOR. 0 means no grouping, 3 means splitting by thousands... NUMBER_GROUPING = 0 # Thousand separator symbol THOUSAND_SEPARATOR = ',' # Do you want to manage transactions manually? # Hint: you really don't! TRANSACTIONS_MANAGED = False # The User-Agent string to use when checking for URL validity through the # isExistingURL validator. from django import get_version URL_VALIDATOR_USER_AGENT = "Django/%s (http://www.djangoproject.com)" % get_version() # The tablespaces to use for each model when not specified otherwise. DEFAULT_TABLESPACE = '' DEFAULT_INDEX_TABLESPACE = '' USE_X_FORWARDED_HOST = False ############## # MIDDLEWARE # ############## # List of middleware classes to use. Order is important; in the request phase, # this middleware classes will be applied in the order given, and in the # response phase the middleware will be applied in reverse order. MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # 'django.middleware.http.ConditionalGetMiddleware', # 'django.middleware.gzip.GZipMiddleware', ) ############ # SESSIONS # ############ SESSION_COOKIE_NAME = 'sessionid' # Cookie name. This can be whatever you want. SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # Age of cookie, in seconds (default: 2 weeks). SESSION_COOKIE_DOMAIN = None # A string like ".lawrence.com", or None for standard domain cookie. SESSION_COOKIE_SECURE = False # Whether the session cookie should be secure (https:// only). SESSION_COOKIE_PATH = '/' # The path of the session cookie. SESSION_COOKIE_HTTPONLY = False # Whether to use the non-RFC standard httpOnly flag (IE, FF3+, others) SESSION_SAVE_EVERY_REQUEST = False # Whether to save the session data on every request. SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether a user's session cookie expires when the Web browser is closed. SESSION_ENGINE = 'django.contrib.sessions.backends.db' # The module to store session data SESSION_FILE_PATH = None # Directory to store session files if using the file session module. If None, the backend will use a sensible default. ######### # CACHE # ######### # New format CACHES = { } # The cache backend to use. See the docstring in django.core.cache for the # possible values. CACHE_MIDDLEWARE_KEY_PREFIX = '' CACHE_MIDDLEWARE_SECONDS = 600 CACHE_MIDDLEWARE_ALIAS = 'default' #################### # COMMENTS # #################### COMMENTS_ALLOW_PROFANITIES = False # The profanities that will trigger a validation error in the # 'hasNoProfanities' validator. All of these should be in lowercase. PROFANITIES_LIST = () # The group ID that designates which users are banned. # Set to None if you're not using it. COMMENTS_BANNED_USERS_GROUP = None # The group ID that designates which users can moderate comments. # Set to None if you're not using it. COMMENTS_MODERATORS_GROUP = None # The group ID that designates the users whose comments should be e-mailed to MANAGERS. # Set to None if you're not using it. COMMENTS_SKETCHY_USERS_GROUP = None # The system will e-mail MANAGERS the first COMMENTS_FIRST_FEW comments by each # user. Set this to 0 if you want to disable it. COMMENTS_FIRST_FEW = 0 # A tuple of IP addresses that have been banned from participating in various # Django-powered features. BANNED_IPS = () ################## # AUTHENTICATION # ################## AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) LOGIN_URL = '/accounts/login/' LOGOUT_URL = '/accounts/logout/' LOGIN_REDIRECT_URL = '/accounts/profile/' # The number of days a password reset link is valid for PASSWORD_RESET_TIMEOUT_DAYS = 3 ######## # CSRF # ######## # Dotted path to callable to be used as view when a request is # rejected by the CSRF middleware. CSRF_FAILURE_VIEW = 'django.views.csrf.csrf_failure' # Name and domain for CSRF cookie. CSRF_COOKIE_NAME = 'csrftoken' CSRF_COOKIE_DOMAIN = None ############ # MESSAGES # ############ # Class to use as messges backend MESSAGE_STORAGE = 'django.contrib.messages.storage.user_messages.LegacyFallbackStorage' # Default values of MESSAGE_LEVEL and MESSAGE_TAGS are defined within # django.contrib.messages to avoid imports in this settings file. ########### # LOGGING # ########### # The callable to use to configure logging LOGGING_CONFIG = 'django.utils.log.dictConfig' # The default logging configuration. This sends an email to # the site admins on every HTTP 500 error. All other log # records are sent to the bit bucket. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } ########### # TESTING # ########### # The name of the class to use to run the test suite TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner' # The name of the database to use for testing purposes. # If None, a name of 'test_' + DATABASE_NAME will be assumed TEST_DATABASE_NAME = None # Strings used to set the character set and collation order for the test # database. These values are passed literally to the server, so they are # backend-dependent. If None, no special settings are sent (system defaults are # used). TEST_DATABASE_CHARSET = None TEST_DATABASE_COLLATION = None ############ # FIXTURES # ############ # The list of directories to search for fixtures FIXTURE_DIRS = () ############### # STATICFILES # ############### # A list of locations of additional static files STATICFILES_DIRS = () # The default file storage backend used during the build process STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # URL prefix for admin media -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/static/admin/'
acshan/odoo
refs/heads/8.0
addons/hr_applicant_document/__init__.py
389
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010-today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # ############################################################################## import models
zolegus/neon
refs/heads/master
tests/test_gradient_pool.py
10
# ---------------------------------------------------------------------------- # Copyright 2015 Nervana Systems Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------- """ Generalized gradient testing applied to pooling layer """ import itertools as itt import numpy as np from neon import NervanaObject from neon.layers.layer import Pooling from tests.grad_funcs import general_gradient_comp # add a reset methods to the layer classes # this is used to reset the layer so that # running fprop and bprop mulitple times # produces repeatable results # some layers just need the function defined class PoolingWithReset(Pooling): def reset(self): self.nglayer = None def pytest_generate_tests(metafunc): # main test generator # generates the parameter combos for # the tests based on whether the # "--all" option is given to py.test # that option is added in conftest.py # global parameter if metafunc.config.option.all: bsz_rng = [16, 32] else: bsz_rng = [16] if 'poolargs' in metafunc.fixturenames: fargs = [] if metafunc.config.option.all: nin_rng = [5, 8] nifm_rng = [1, 2, 4] fs_rng = [2, 3, 4] else: nin_rng = [10] nifm_rng = [1, 5] fs_rng = [2, 3] op_rng = ["max", "avg"] fargs = itt.product(nin_rng, nifm_rng, fs_rng, bsz_rng, op_rng) metafunc.parametrize("poolargs", fargs) # -- pooling tests -- def test_pooling(cpu64_only, poolargs): nin, nifm, fshape, batch_size, op = poolargs NervanaObject.be.bsz = NervanaObject.be.batch_size = batch_size inp = np.random.randn(nin * nin * nifm, batch_size) lshape = (nifm, nin, nin) layer = PoolingWithReset(fshape) layer.op = op epsilon = 1.0e-5 pert_frac = 0.1 # test 10% of the inputs # select pert_frac fraction of inps to perturb pert_cnt = int(np.ceil(inp.size*pert_frac)) pert_inds = np.random.permutation(inp.size)[0:pert_cnt] (max_abs, max_rel) = general_gradient_comp(layer, inp, epsilon=epsilon, lshape=lshape, pert_inds=pert_inds) assert max_abs < 1.0e-7
UOMx/edx-platform
refs/heads/master
lms/djangoapps/instructor/views/instructor_task_helpers.py
35
""" A collection of helper utility functions for working with instructor tasks. """ import json import logging from util.date_utils import get_default_time_display from bulk_email.models import CourseEmail from django.utils.translation import ugettext as _ from django.utils.translation import ungettext from instructor_task.views import get_task_completion_info log = logging.getLogger(__name__) def email_error_information(): """ Returns email information marked as None, used in event email cannot be loaded """ expected_info = [ 'created', 'sent_to', 'email', 'number_sent', 'requester', ] return {info: None for info in expected_info} def extract_email_features(email_task): """ From the given task, extract email content information Expects that the given task has the following attributes: * task_input (dict containing email_id and to_option) * task_output (optional, dict containing total emails sent) * requester, the user who executed the task With this information, gets the corresponding email object from the bulk emails table, and loads up a dict containing the following: * created, the time the email was sent displayed in default time display * sent_to, the group the email was delivered to * email, dict containing the subject, id, and html_message of an email * number_sent, int number of emails sent * requester, the user who sent the emails If task_input cannot be loaded, then the email cannot be loaded and None is returned for these fields. """ # Load the task input info to get email id try: task_input_information = json.loads(email_task.task_input) except ValueError: log.error("Could not parse task input as valid json; task input: %s", email_task.task_input) return email_error_information() email = CourseEmail.objects.get(id=task_input_information['email_id']) email_feature_dict = { 'created': get_default_time_display(email.created), 'sent_to': task_input_information['to_option'], 'requester': str(email_task.requester), } features = ['subject', 'html_message', 'id'] email_info = {feature: unicode(getattr(email, feature)) for feature in features} # Pass along email as an object with the information we desire email_feature_dict['email'] = email_info # Translators: number sent refers to the number of emails sent number_sent = _('0 sent') if hasattr(email_task, 'task_output') and email_task.task_output is not None: try: task_output = json.loads(email_task.task_output) except ValueError: log.error("Could not parse task output as valid json; task output: %s", email_task.task_output) else: if 'succeeded' in task_output and task_output['succeeded'] > 0: num_emails = task_output['succeeded'] number_sent = ungettext( "{num_emails} sent", "{num_emails} sent", num_emails ).format(num_emails=num_emails) if 'failed' in task_output and task_output['failed'] > 0: num_emails = task_output['failed'] number_sent += ", " number_sent += ungettext( "{num_emails} failed", "{num_emails} failed", num_emails ).format(num_emails=num_emails) email_feature_dict['number_sent'] = number_sent return email_feature_dict def extract_task_features(task): """ Convert task to dict for json rendering. Expects tasks have the following features: * task_type (str, type of task) * task_input (dict, input(s) to the task) * task_id (str, celery id of the task) * requester (str, username who submitted the task) * task_state (str, state of task eg PROGRESS, COMPLETED) * created (datetime, when the task was completed) * task_output (optional) """ # Pull out information from the task features = ['task_type', 'task_input', 'task_id', 'requester', 'task_state'] task_feature_dict = {feature: str(getattr(task, feature)) for feature in features} # Some information (created, duration, status, task message) require additional formatting task_feature_dict['created'] = task.created.isoformat() # Get duration info, if known duration_sec = 'unknown' if hasattr(task, 'task_output') and task.task_output is not None: try: task_output = json.loads(task.task_output) except ValueError: log.error("Could not parse task output as valid json; task output: %s", task.task_output) else: if 'duration_ms' in task_output: duration_sec = int(task_output['duration_ms'] / 1000.0) task_feature_dict['duration_sec'] = duration_sec # Get progress status message & success information success, task_message = get_task_completion_info(task) status = _("Complete") if success else _("Incomplete") task_feature_dict['status'] = status task_feature_dict['task_message'] = task_message return task_feature_dict
nathanielvarona/airflow
refs/heads/master
tests/providers/mongo/sensors/__init__.py
5130
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License.
xbzbing/mitmproxy
refs/heads/master
examples/modify_querystring.py
36
def request(context, flow): q = flow.request.get_query() if q: q["mitmproxy"] = ["rocks"] flow.request.set_query(q)
sq5bpf/osmo-tetra-sq5bpf
refs/heads/master
src/demod/python-3.7/fcdp-tetra_demod.py
1
#!/usr/bin/env python import sys import math from gnuradio import blocks, filter, gr, audio from gnuradio.eng_option import eng_option from optparse import OptionParser try: import cqpsk except: from tetra_demod import cqpsk # applies frequency translation, resampling (interpolation/decimation) and cqpsk demodulation class my_top_block(gr.top_block): def __init__(self, options): gr.top_block.__init__(self) sample_rate = int(options.sample_rate) self.asrc = audio.source(sample_rate, options.audio_device, True) self.f2c = blocks.float_to_complex(1) self.connect((self.asrc, 1), (self.f2c, 1)) self.connect((self.asrc, 0), (self.f2c, 0)) symbol_rate = 18000 sps = 2 # output rate will be 36,000 ntaps = 11 * sps new_sample_rate = symbol_rate * sps channel_taps = filter.firdes.low_pass(1.0, sample_rate, options.low_pass, options.low_pass * 0.1, filter.firdes.WIN_HANN) FILTER = filter.freq_xlating_fir_filter_ccf(1, channel_taps, options.calibration, sample_rate) sys.stderr.write("sample rate: %d\n" %(sample_rate)) DEMOD = cqpsk.cqpsk_demod( samples_per_symbol = sps, excess_bw=0.35, costas_alpha=0.03, gain_mu=0.05, mu=0.05, omega_relative_limit=0.05, log=options.log, verbose=options.verbose) OUT = blocks.file_sink(gr.sizeof_float, options.output_file) r = float(sample_rate) / float(new_sample_rate) INTERPOLATOR = filter.fractional_resampler_cc(0, r) self.connect(self.f2c, FILTER, INTERPOLATOR, DEMOD, OUT) def get_options(): parser = OptionParser(option_class=eng_option) parser.add_option("-r", "--sample-rate", type="eng_float", default=96000, help="set sample rate to RATE (96000)") parser.add_option("-D", "--audio-device", type="string", default="", help="pcm input device name. E.g., hw:0,0 or /dev/dsp") # demodulator related settings parser.add_option("-c", "--calibration", type="int", default=0, help="freq offset") parser.add_option("-l", "--log", action="store_true", default=False, help="dump debug .dat files") parser.add_option("-L", "--low-pass", type="eng_float", default=25e3, help="low pass cut-off", metavar="Hz") parser.add_option("-o", "--output-file", type="string", default="out.float", help="specify the bit output file") parser.add_option("-v", "--verbose", action="store_true", default=False, help="dump demodulation data") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() raise SystemExit, 1 return (options) if __name__ == "__main__": (options) = get_options() tb = my_top_block(options) try: tb.run() except KeyboardInterrupt: tb.stop()
jamielennox/deluge
refs/heads/master
deluge/_libtorrent.py
6
# # _libtorrent.py # # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> # # Deluge is free software. # # You may 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. # # deluge 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 deluge. If not, write to: # The Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor # Boston, MA 02110-1301, USA. # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the OpenSSL # library. # You must obey the GNU General Public License in all respects for all of # the code used other than OpenSSL. If you modify file(s) with this # exception, you may extend this exception to your version of the file(s), # but you are not obligated to do so. If you do not wish to do so, delete # this exception statement from your version. If you delete this exception # statement from all source files in the program, then also delete it here. # # """ This module is used to handle the importing of libtorrent. We use this module to control what versions of libtorrent this version of Deluge supports. ** Usage ** >>> from deluge._libtorrent import lt """ REQUIRED_VERSION = "0.14.9.0" def check_version(LT): from deluge.common import VersionSplit if VersionSplit(lt.version) < VersionSplit(REQUIRED_VERSION): raise ImportError("This version of Deluge requires libtorrent >=%s!" % REQUIRED_VERSION) try: import deluge.libtorrent as lt check_version(lt) except ImportError: import libtorrent as lt check_version(lt)
odoomrp/odoomrp-wip
refs/heads/8.0
account_treasury_forecast_banking/models/__init__.py
124
# -*- encoding: utf-8 -*- ############################################################################## # # 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 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 . import account_treasury_forecast_template from . import account_treasury_forecast
mitocw/edx-platform
refs/heads/master
openedx/core/djangoapps/content/block_structure/tests/test_factory.py
4
""" Tests for block_structure_factory.py """ from django.test import TestCase from xmodule.modulestore.exceptions import ItemNotFoundError from ..exceptions import BlockStructureNotFound from ..factory import BlockStructureFactory from ..store import BlockStructureStore from .helpers import ChildrenMapTestMixin, MockCache, MockModulestoreFactory class TestBlockStructureFactory(TestCase, ChildrenMapTestMixin): """ Tests for BlockStructureFactory """ def setUp(self): super(TestBlockStructureFactory, self).setUp() self.children_map = self.SIMPLE_CHILDREN_MAP self.modulestore = MockModulestoreFactory.create(self.children_map, self.block_key_factory) def test_from_modulestore(self): block_structure = BlockStructureFactory.create_from_modulestore( root_block_usage_key=0, modulestore=self.modulestore ) self.assert_block_structure(block_structure, self.children_map) def test_from_modulestore_fail(self): with self.assertRaises(ItemNotFoundError): BlockStructureFactory.create_from_modulestore( root_block_usage_key=len(self.children_map) + 1, modulestore=self.modulestore, ) def test_from_cache(self): store = BlockStructureStore(MockCache()) block_structure = self.create_block_structure(self.children_map) store.add(block_structure) from_cache_block_structure = BlockStructureFactory.create_from_store( block_structure.root_block_usage_key, store, ) self.assert_block_structure(from_cache_block_structure, self.children_map) def test_from_cache_none(self): store = BlockStructureStore(MockCache()) with self.assertRaises(BlockStructureNotFound): BlockStructureFactory.create_from_store( root_block_usage_key=0, block_structure_store=store, ) def test_new(self): block_structure = BlockStructureFactory.create_from_modulestore( root_block_usage_key=0, modulestore=self.modulestore ) new_structure = BlockStructureFactory.create_new( block_structure.root_block_usage_key, block_structure._block_relations, # pylint: disable=protected-access block_structure.transformer_data, block_structure._block_data_map, # pylint: disable=protected-access ) self.assert_block_structure(new_structure, self.children_map)
resin-io/edison-linux
refs/heads/master
tools/perf/scripts/python/sctop.py
1996
# system call top # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # Periodically displays system-wide system call totals, broken down by # syscall. If a [comm] arg is specified, only syscalls called by # [comm] are displayed. If an [interval] arg is specified, the display # will be refreshed every [interval] seconds. The default interval is # 3 seconds. import os, sys, thread, time sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * usage = "perf script -s sctop.py [comm] [interval]\n"; for_comm = None default_interval = 3 interval = default_interval if len(sys.argv) > 3: sys.exit(usage) if len(sys.argv) > 2: for_comm = sys.argv[1] interval = int(sys.argv[2]) elif len(sys.argv) > 1: try: interval = int(sys.argv[1]) except ValueError: for_comm = sys.argv[1] interval = default_interval syscalls = autodict() def trace_begin(): thread.start_new_thread(print_syscall_totals, (interval,)) pass def raw_syscalls__sys_enter(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, common_callchain, id, args): if for_comm is not None: if common_comm != for_comm: return try: syscalls[id] += 1 except TypeError: syscalls[id] = 1 def syscalls__sys_enter(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, id, args): raw_syscalls__sys_enter(**locals()) def print_syscall_totals(interval): while 1: clear_term() if for_comm is not None: print "\nsyscall events for %s:\n\n" % (for_comm), else: print "\nsyscall events:\n\n", print "%-40s %10s\n" % ("event", "count"), print "%-40s %10s\n" % ("----------------------------------------", \ "----------"), for id, val in sorted(syscalls.iteritems(), key = lambda(k, v): (v, k), \ reverse = True): try: print "%-40s %10d\n" % (syscall_name(id), val), except TypeError: pass syscalls.clear() time.sleep(interval)
yoer/hue
refs/heads/master
desktop/core/ext-py/lxml/setupinfo.py
28
import sys, os, os.path from distutils.core import Extension from distutils.errors import DistutilsOptionError from versioninfo import get_base_dir, split_version try: from Cython.Distutils import build_ext as build_pyx import Cython.Compiler.Version CYTHON_INSTALLED = True except ImportError: CYTHON_INSTALLED = False EXT_MODULES = ["lxml.etree", "lxml.objectify"] PACKAGE_PATH = "src/lxml/" if sys.version_info[0] >= 3: _system_encoding = sys.getdefaultencoding() if _system_encoding is None: _system_encoding = "iso-8859-1" # :-) def decode_input(data): if isinstance(data, str): return data return data.decode(_system_encoding) else: def decode_input(data): return data def env_var(name): value = os.getenv(name) if value: value = decode_input(value) if sys.platform == 'win32' and ';' in value: return value.split(';') else: return value.split() else: return [] def ext_modules(static_include_dirs, static_library_dirs, static_cflags, static_binaries): global XML2_CONFIG, XSLT_CONFIG if OPTION_BUILD_LIBXML2XSLT: from buildlibxml import build_libxml2xslt XML2_CONFIG, XSLT_CONFIG = build_libxml2xslt( 'libs', 'build/tmp', static_include_dirs, static_library_dirs, static_cflags, static_binaries, libxml2_version=OPTION_LIBXML2_VERSION, libxslt_version=OPTION_LIBXSLT_VERSION) if CYTHON_INSTALLED: source_extension = ".pyx" print("Building with Cython %s." % Cython.Compiler.Version.version) else: print ("NOTE: Trying to build without Cython, pre-generated " "'%slxml.etree.c' needs to be available." % PACKAGE_PATH) source_extension = ".c" if OPTION_WITHOUT_OBJECTIFY: modules = [ entry for entry in EXT_MODULES if 'objectify' not in entry ] else: modules = EXT_MODULES lib_versions = get_library_versions() if lib_versions[0]: print("Using build configuration of libxml2 %s and libxslt %s" % lib_versions) else: print("Using build configuration of libxslt %s" % lib_versions[1]) _include_dirs = include_dirs(static_include_dirs) _library_dirs = library_dirs(static_library_dirs) _cflags = cflags(static_cflags) _define_macros = define_macros() _libraries = libraries() if _library_dirs: message = "Building against libxml2/libxslt in " if len(_library_dirs) > 1: print(message + "one of the following directories:") for dir in _library_dirs: print(" " + dir) else: print(message + "the following directory: " + _library_dirs[0]) if OPTION_AUTO_RPATH: runtime_library_dirs = _library_dirs else: runtime_library_dirs = [] if not OPTION_SHOW_WARNINGS: _cflags = ['-w'] + _cflags result = [] for module in modules: main_module_source = PACKAGE_PATH + module + source_extension dependencies = find_dependencies(module) result.append( Extension( module, sources = [main_module_source] + dependencies, extra_compile_args = _cflags, extra_objects = static_binaries, define_macros = _define_macros, include_dirs = _include_dirs, library_dirs = _library_dirs, runtime_library_dirs = runtime_library_dirs, libraries = _libraries, )) return result def find_dependencies(module): if not CYTHON_INSTALLED: return [] from Cython.Compiler.Version import version if split_version(version) < (0,9,6,13): return [] package_dir = os.path.join(get_base_dir(), PACKAGE_PATH) files = os.listdir(package_dir) pxd_files = [ os.path.join(PACKAGE_PATH, filename) for filename in files if filename.endswith('.pxd') ] if 'etree' in module: pxi_files = [ os.path.join(PACKAGE_PATH, filename) for filename in files if filename.endswith('.pxi') and 'objectpath' not in filename ] pxd_files = [ filename for filename in pxd_files if 'etreepublic' not in filename ] elif 'objectify' in module: pxi_files = [ os.path.join(PACKAGE_PATH, 'objectpath.pxi') ] else: pxi_files = [] return pxd_files + pxi_files def extra_setup_args(): result = {} if CYTHON_INSTALLED: result['cmdclass'] = {'build_ext': build_pyx} return result def libraries(): if sys.platform in ('win32',): libs = ['libxslt', 'libexslt', 'libxml2', 'iconv'] if OPTION_STATIC: libs = ['%s_a' % lib for lib in libs] libs.extend(['zlib', 'WS2_32']) elif OPTION_STATIC: libs = ['z', 'm'] else: libs = ['xslt', 'exslt', 'xml2', 'z', 'm'] return libs def library_dirs(static_library_dirs): if OPTION_STATIC: if not static_library_dirs: static_library_dirs = env_var('LIBRARY') assert static_library_dirs, "Static build not configured, see doc/build.txt" return static_library_dirs # filter them from xslt-config --libs result = [] possible_library_dirs = flags('libs') for possible_library_dir in possible_library_dirs: if possible_library_dir.startswith('-L'): result.append(possible_library_dir[2:]) return result def include_dirs(static_include_dirs): if OPTION_STATIC: if not static_include_dirs: static_include_dirs = env_var('INCLUDE') return static_include_dirs # filter them from xslt-config --cflags result = [] possible_include_dirs = flags('cflags') for possible_include_dir in possible_include_dirs: if possible_include_dir.startswith('-I'): result.append(possible_include_dir[2:]) return result def cflags(static_cflags): result = [] if OPTION_DEBUG_GCC: result.append('-g2') if OPTION_STATIC: if not static_cflags: static_cflags = env_var('CFLAGS') result.extend(static_cflags) else: # anything from xslt-config --cflags that doesn't start with -I possible_cflags = flags('cflags') for possible_cflag in possible_cflags: if not possible_cflag.startswith('-I'): result.append(possible_cflag) if sys.platform in ('darwin',): for opt in result: if 'flat_namespace' in opt: break else: result.append('-flat_namespace') return result def define_macros(): macros = [] if OPTION_WITHOUT_ASSERT: macros.append(('PYREX_WITHOUT_ASSERTIONS', None)) if OPTION_WITHOUT_THREADING: macros.append(('WITHOUT_THREADING', None)) if OPTION_WITH_REFNANNY: macros.append(('CYTHON_REFNANNY', None)) return macros _ERROR_PRINTED = False def run_command(cmd, *args): if not cmd: return '' if args: cmd = ' '.join((cmd,) + args) try: import subprocess except ImportError: # Python 2.3 _, rf, ef = os.popen3(cmd) else: # Python 2.4+ p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) rf, ef = p.stdout, p.stderr errors = ef.read() global _ERROR_PRINTED if errors and not _ERROR_PRINTED: _ERROR_PRINTED = True print("ERROR: %s" % errors) print("** make sure the development packages of libxml2 and libxslt are installed **\n") return decode_input(rf.read()).strip() def get_library_versions(): xml2_version = run_command(find_xml2_config(), "--version") xslt_version = run_command(find_xslt_config(), "--version") return xml2_version, xslt_version def flags(option): xml2_flags = run_command(find_xml2_config(), "--%s" % option) xslt_flags = run_command(find_xslt_config(), "--%s" % option) flag_list = xml2_flags.split() for flag in xslt_flags.split(): if flag not in flag_list: flag_list.append(flag) return flag_list XSLT_CONFIG = None XML2_CONFIG = None def find_xml2_config(): global XML2_CONFIG if XML2_CONFIG: return XML2_CONFIG option = '--with-xml2-config=' for arg in sys.argv: if arg.startswith(option): sys.argv.remove(arg) XML2_CONFIG = arg[len(option):] return XML2_CONFIG else: # default: do nothing, rely only on xslt-config XML2_CONFIG = os.getenv('XML2_CONFIG', '') return XML2_CONFIG def find_xslt_config(): global XSLT_CONFIG if XSLT_CONFIG: return XSLT_CONFIG option = '--with-xslt-config=' for arg in sys.argv: if arg.startswith(option): sys.argv.remove(arg) XSLT_CONFIG = arg[len(option):] return XSLT_CONFIG else: XSLT_CONFIG = os.getenv('XSLT_CONFIG', 'xslt-config') return XSLT_CONFIG ## Option handling: def has_option(name): try: sys.argv.remove('--%s' % name) return True except ValueError: pass # allow passing all cmd line options also as environment variables env_val = os.getenv(name.upper().replace('-', '_'), 'false').lower() if env_val == "true": return True return False def option_value(name): for index, option in enumerate(sys.argv): if option == '--' + name: if index+1 >= len(sys.argv): raise DistutilsOptionError( 'The option %s requires a value' % option) value = sys.argv[index+1] sys.argv[index:index+2] = [] return value if option.startswith('--' + name + '='): value = option[len(name)+3:] sys.argv[index:index+1] = [] return value env_val = os.getenv(name.upper().replace('-', '_')) return env_val # pick up any commandline options OPTION_WITHOUT_OBJECTIFY = has_option('without-objectify') OPTION_WITHOUT_ASSERT = has_option('without-assert') OPTION_WITHOUT_THREADING = has_option('without-threading') OPTION_WITHOUT_CYTHON = has_option('without-cython') OPTION_WITH_REFNANNY = has_option('with-refnanny') if OPTION_WITHOUT_CYTHON: CYTHON_INSTALLED = False OPTION_STATIC = has_option('static') OPTION_DEBUG_GCC = has_option('debug-gcc') OPTION_SHOW_WARNINGS = has_option('warnings') OPTION_AUTO_RPATH = has_option('auto-rpath') OPTION_BUILD_LIBXML2XSLT = has_option('static-deps') if OPTION_BUILD_LIBXML2XSLT: OPTION_STATIC = True OPTION_LIBXML2_VERSION = option_value('libxml2-version') OPTION_LIBXSLT_VERSION = option_value('libxslt-version')
1yvT0s/scrapy
refs/heads/master
scrapy/core/__init__.py
216
""" Scrapy core library classes and functions. """
nmayorov/scikit-learn
refs/heads/master
examples/linear_model/plot_logistic.py
312
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= Logit function ========================================================= Show in the plot is how the logistic regression would, in this synthetic dataset, classify values as either 0 or 1, i.e. class one or two, using the logit-curve. """ print(__doc__) # Code source: Gael Varoquaux # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model # this is our test set, it's just a straight line with some # Gaussian noise xmin, xmax = -5, 5 n_samples = 100 np.random.seed(0) X = np.random.normal(size=n_samples) y = (X > 0).astype(np.float) X[X > 0] *= 4 X += .3 * np.random.normal(size=n_samples) X = X[:, np.newaxis] # run the classifier clf = linear_model.LogisticRegression(C=1e5) clf.fit(X, y) # and plot the result plt.figure(1, figsize=(4, 3)) plt.clf() plt.scatter(X.ravel(), y, color='black', zorder=20) X_test = np.linspace(-5, 10, 300) def model(x): return 1 / (1 + np.exp(-x)) loss = model(X_test * clf.coef_ + clf.intercept_).ravel() plt.plot(X_test, loss, color='blue', linewidth=3) ols = linear_model.LinearRegression() ols.fit(X, y) plt.plot(X_test, ols.coef_ * X_test + ols.intercept_, linewidth=1) plt.axhline(.5, color='.5') plt.ylabel('y') plt.xlabel('X') plt.xticks(()) plt.yticks(()) plt.ylim(-.25, 1.25) plt.xlim(-4, 10) plt.show()
shannpersand/cooper-type
refs/heads/master
workshops/Python Workshop/Just/2016-06-25 CooperWest workshop day 1/19 draw nicer bounding box.py
1
for g in CurrentFont(): if not g.box: continue xMin, yMin, xMax, yMax = g.box g.prepareUndo("draw bounding box") pen = g.getPen() additionalSpace = 30 pen.moveTo((xMin - additionalSpace, yMin)) pen.lineTo((xMin - additionalSpace, yMax)) pen.lineTo((xMin, yMax + additionalSpace)) pen.lineTo((xMax, yMax + additionalSpace)) pen.lineTo((xMax + additionalSpace, yMax)) pen.lineTo((xMax + additionalSpace, yMin)) pen.lineTo((xMax, yMin - additionalSpace)) pen.lineTo((xMin, yMin - additionalSpace)) pen.closePath() g.performUndo()
MarnuLombard/namebench
refs/heads/master
nb_third_party/jinja2/environment.py
199
# -*- coding: utf-8 -*- """ jinja2.environment ~~~~~~~~~~~~~~~~~~ Provides a class that holds runtime and parsing time options. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ import os import sys from jinja2 import nodes from jinja2.defaults import * from jinja2.lexer import get_lexer, TokenStream from jinja2.parser import Parser from jinja2.optimizer import optimize from jinja2.compiler import generate from jinja2.runtime import Undefined, new_context from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \ TemplatesNotFound from jinja2.utils import import_string, LRUCache, Markup, missing, \ concat, consume, internalcode, _encode_filename # for direct template usage we have up to ten living environments _spontaneous_environments = LRUCache(10) # the function to create jinja traceback objects. This is dynamically # imported on the first exception in the exception handler. _make_traceback = None def get_spontaneous_environment(*args): """Return a new spontaneous environment. A spontaneous environment is an unnamed and unaccessible (in theory) environment that is used for templates generated from a string and not from the file system. """ try: env = _spontaneous_environments.get(args) except TypeError: return Environment(*args) if env is not None: return env _spontaneous_environments[args] = env = Environment(*args) env.shared = True return env def create_cache(size): """Return the cache class for the given size.""" if size == 0: return None if size < 0: return {} return LRUCache(size) def copy_cache(cache): """Create an empty copy of the given cache.""" if cache is None: return None elif type(cache) is dict: return {} return LRUCache(cache.capacity) def load_extensions(environment, extensions): """Load the extensions from the list and bind it to the environment. Returns a dict of instanciated environments. """ result = {} for extension in extensions: if isinstance(extension, basestring): extension = import_string(extension) result[extension.identifier] = extension(environment) return result def _environment_sanity_check(environment): """Perform a sanity check on the environment.""" assert issubclass(environment.undefined, Undefined), 'undefined must ' \ 'be a subclass of undefined because filters depend on it.' assert environment.block_start_string != \ environment.variable_start_string != \ environment.comment_start_string, 'block, variable and comment ' \ 'start strings must be different' assert environment.newline_sequence in ('\r', '\r\n', '\n'), \ 'newline_sequence set to unknown line ending string.' return environment class Environment(object): r"""The core component of Jinja is the `Environment`. It contains important shared variables like configuration, filters, tests, globals and others. Instances of this class may be modified if they are not shared and if no template was loaded so far. Modifications on environments after the first template was loaded will lead to surprising effects and undefined behavior. Here the possible initialization parameters: `block_start_string` The string marking the begin of a block. Defaults to ``'{%'``. `block_end_string` The string marking the end of a block. Defaults to ``'%}'``. `variable_start_string` The string marking the begin of a print statement. Defaults to ``'{{'``. `variable_end_string` The string marking the end of a print statement. Defaults to ``'}}'``. `comment_start_string` The string marking the begin of a comment. Defaults to ``'{#'``. `comment_end_string` The string marking the end of a comment. Defaults to ``'#}'``. `line_statement_prefix` If given and a string, this will be used as prefix for line based statements. See also :ref:`line-statements`. `line_comment_prefix` If given and a string, this will be used as prefix for line based based comments. See also :ref:`line-statements`. .. versionadded:: 2.2 `trim_blocks` If this is set to ``True`` the first newline after a block is removed (block, not variable tag!). Defaults to `False`. `newline_sequence` The sequence that starts a newline. Must be one of ``'\r'``, ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a useful default for Linux and OS X systems as well as web applications. `extensions` List of Jinja extensions to use. This can either be import paths as strings or extension classes. For more information have a look at :ref:`the extensions documentation <jinja-extensions>`. `optimized` should the optimizer be enabled? Default is `True`. `undefined` :class:`Undefined` or a subclass of it that is used to represent undefined values in the template. `finalize` A callable that can be used to process the result of a variable expression before it is output. For example one can convert `None` implicitly into an empty string here. `autoescape` If set to true the XML/HTML autoescaping feature is enabled by default. For more details about auto escaping see :class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also be a callable that is passed the template name and has to return `True` or `False` depending on autoescape should be enabled by default. .. versionchanged:: 2.4 `autoescape` can now be a function `loader` The template loader for this environment. `cache_size` The size of the cache. Per default this is ``50`` which means that if more than 50 templates are loaded the loader will clean out the least recently used template. If the cache size is set to ``0`` templates are recompiled all the time, if the cache size is ``-1`` the cache will not be cleaned. `auto_reload` Some loaders load templates from locations where the template sources may change (ie: file system or database). If `auto_reload` is set to `True` (default) every time a template is requested the loader checks if the source changed and if yes, it will reload the template. For higher performance it's possible to disable that. `bytecode_cache` If set to a bytecode cache object, this object will provide a cache for the internal Jinja bytecode so that templates don't have to be parsed if they were not changed. See :ref:`bytecode-cache` for more information. """ #: if this environment is sandboxed. Modifying this variable won't make #: the environment sandboxed though. For a real sandboxed environment #: have a look at jinja2.sandbox sandboxed = False #: True if the environment is just an overlay overlayed = False #: the environment this environment is linked to if it is an overlay linked_to = None #: shared environments have this set to `True`. A shared environment #: must not be modified shared = False #: these are currently EXPERIMENTAL undocumented features. exception_handler = None exception_formatter = None def __init__(self, block_start_string=BLOCK_START_STRING, block_end_string=BLOCK_END_STRING, variable_start_string=VARIABLE_START_STRING, variable_end_string=VARIABLE_END_STRING, comment_start_string=COMMENT_START_STRING, comment_end_string=COMMENT_END_STRING, line_statement_prefix=LINE_STATEMENT_PREFIX, line_comment_prefix=LINE_COMMENT_PREFIX, trim_blocks=TRIM_BLOCKS, newline_sequence=NEWLINE_SEQUENCE, extensions=(), optimized=True, undefined=Undefined, finalize=None, autoescape=False, loader=None, cache_size=50, auto_reload=True, bytecode_cache=None): # !!Important notice!! # The constructor accepts quite a few arguments that should be # passed by keyword rather than position. However it's important to # not change the order of arguments because it's used at least # internally in those cases: # - spontaneus environments (i18n extension and Template) # - unittests # If parameter changes are required only add parameters at the end # and don't change the arguments (or the defaults!) of the arguments # existing already. # lexer / parser information self.block_start_string = block_start_string self.block_end_string = block_end_string self.variable_start_string = variable_start_string self.variable_end_string = variable_end_string self.comment_start_string = comment_start_string self.comment_end_string = comment_end_string self.line_statement_prefix = line_statement_prefix self.line_comment_prefix = line_comment_prefix self.trim_blocks = trim_blocks self.newline_sequence = newline_sequence # runtime information self.undefined = undefined self.optimized = optimized self.finalize = finalize self.autoescape = autoescape # defaults self.filters = DEFAULT_FILTERS.copy() self.tests = DEFAULT_TESTS.copy() self.globals = DEFAULT_NAMESPACE.copy() # set the loader provided self.loader = loader self.bytecode_cache = None self.cache = create_cache(cache_size) self.bytecode_cache = bytecode_cache self.auto_reload = auto_reload # load extensions self.extensions = load_extensions(self, extensions) _environment_sanity_check(self) def extend(self, **attributes): """Add the items to the instance of the environment if they do not exist yet. This is used by :ref:`extensions <writing-extensions>` to register callbacks and configuration values without breaking inheritance. """ for key, value in attributes.iteritems(): if not hasattr(self, key): setattr(self, key, value) def overlay(self, block_start_string=missing, block_end_string=missing, variable_start_string=missing, variable_end_string=missing, comment_start_string=missing, comment_end_string=missing, line_statement_prefix=missing, line_comment_prefix=missing, trim_blocks=missing, extensions=missing, optimized=missing, undefined=missing, finalize=missing, autoescape=missing, loader=missing, cache_size=missing, auto_reload=missing, bytecode_cache=missing): """Create a new overlay environment that shares all the data with the current environment except of cache and the overridden attributes. Extensions cannot be removed for an overlayed environment. An overlayed environment automatically gets all the extensions of the environment it is linked to plus optional extra extensions. Creating overlays should happen after the initial environment was set up completely. Not all attributes are truly linked, some are just copied over so modifications on the original environment may not shine through. """ args = dict(locals()) del args['self'], args['cache_size'], args['extensions'] rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.overlayed = True rv.linked_to = self for key, value in args.iteritems(): if value is not missing: setattr(rv, key, value) if cache_size is not missing: rv.cache = create_cache(cache_size) else: rv.cache = copy_cache(self.cache) rv.extensions = {} for key, value in self.extensions.iteritems(): rv.extensions[key] = value.bind(rv) if extensions is not missing: rv.extensions.update(load_extensions(extensions)) return _environment_sanity_check(rv) lexer = property(get_lexer, doc="The lexer for this environment.") def iter_extensions(self): """Iterates over the extensions by priority.""" return iter(sorted(self.extensions.values(), key=lambda x: x.priority)) def getitem(self, obj, argument): """Get an item or attribute of an object but prefer the item.""" try: return obj[argument] except (TypeError, LookupError): if isinstance(argument, basestring): try: attr = str(argument) except: pass else: try: return getattr(obj, attr) except AttributeError: pass return self.undefined(obj=obj, name=argument) def getattr(self, obj, attribute): """Get an item or attribute of an object but prefer the attribute. Unlike :meth:`getitem` the attribute *must* be a bytestring. """ try: return getattr(obj, attribute) except AttributeError: pass try: return obj[attribute] except (TypeError, LookupError, AttributeError): return self.undefined(obj=obj, name=attribute) @internalcode def parse(self, source, name=None, filename=None): """Parse the sourcecode and return the abstract syntax tree. This tree of nodes is used by the compiler to convert the template into executable source- or bytecode. This is useful for debugging or to extract information from templates. If you are :ref:`developing Jinja2 extensions <writing-extensions>` this gives you a good overview of the node tree generated. """ try: return self._parse(source, name, filename) except TemplateSyntaxError: exc_info = sys.exc_info() self.handle_exception(exc_info, source_hint=source) def _parse(self, source, name, filename): """Internal parsing function used by `parse` and `compile`.""" return Parser(self, source, name, _encode_filename(filename)).parse() def lex(self, source, name=None, filename=None): """Lex the given sourcecode and return a generator that yields tokens as tuples in the form ``(lineno, token_type, value)``. This can be useful for :ref:`extension development <writing-extensions>` and debugging templates. This does not perform preprocessing. If you want the preprocessing of the extensions to be applied you have to filter source through the :meth:`preprocess` method. """ source = unicode(source) try: return self.lexer.tokeniter(source, name, filename) except TemplateSyntaxError: exc_info = sys.exc_info() self.handle_exception(exc_info, source_hint=source) def preprocess(self, source, name=None, filename=None): """Preprocesses the source with all extensions. This is automatically called for all parsing and compiling methods but *not* for :meth:`lex` because there you usually only want the actual source tokenized. """ return reduce(lambda s, e: e.preprocess(s, name, filename), self.iter_extensions(), unicode(source)) def _tokenize(self, source, name, filename=None, state=None): """Called by the parser to do the preprocessing and filtering for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. """ source = self.preprocess(source, name, filename) stream = self.lexer.tokenize(source, name, filename, state) for ext in self.iter_extensions(): stream = ext.filter_stream(stream) if not isinstance(stream, TokenStream): stream = TokenStream(stream, name, filename) return stream @internalcode def compile(self, source, name=None, filename=None, raw=False, defer_init=False): """Compile a node or template source code. The `name` parameter is the load name of the template after it was joined using :meth:`join_path` if necessary, not the filename on the file system. the `filename` parameter is the estimated filename of the template on the file system. If the template came from a database or memory this can be omitted. The return value of this method is a python code object. If the `raw` parameter is `True` the return value will be a string with python code equivalent to the bytecode returned otherwise. This method is mainly used internally. `defer_init` is use internally to aid the module code generator. This causes the generated code to be able to import without the global environment variable to be set. .. versionadded:: 2.4 `defer_init` parameter added. """ source_hint = None try: if isinstance(source, basestring): source_hint = source source = self._parse(source, name, filename) if self.optimized: source = optimize(source, self) source = generate(source, self, name, filename, defer_init=defer_init) if raw: return source if filename is None: filename = '<template>' else: filename = _encode_filename(filename) return compile(source, filename, 'exec') except TemplateSyntaxError: exc_info = sys.exc_info() self.handle_exception(exc_info, source_hint=source) def compile_expression(self, source, undefined_to_none=True): """A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression. This is useful if applications want to use the same rules as Jinja in template "configuration files" or similar situations. Example usage: >>> env = Environment() >>> expr = env.compile_expression('foo == 42') >>> expr(foo=23) False >>> expr(foo=42) True Per default the return value is converted to `None` if the expression returns an undefined value. This can be changed by setting `undefined_to_none` to `False`. >>> env.compile_expression('var')() is None True >>> env.compile_expression('var', undefined_to_none=False)() Undefined .. versionadded:: 2.1 """ parser = Parser(self, source, state='variable') exc_info = None try: expr = parser.parse_expression() if not parser.stream.eos: raise TemplateSyntaxError('chunk after expression', parser.stream.current.lineno, None, None) expr.set_environment(self) except TemplateSyntaxError: exc_info = sys.exc_info() if exc_info is not None: self.handle_exception(exc_info, source_hint=source) body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)] template = self.from_string(nodes.Template(body, lineno=1)) return TemplateExpression(template, undefined_to_none) def compile_templates(self, target, extensions=None, filter_func=None, zip='deflated', log_function=None, ignore_errors=True, py_compile=False): """Compiles all the templates the loader can find, compiles them and stores them in `target`. If `zip` is `None`, instead of in a zipfile, the templates will be will be stored in a directory. By default a deflate zip algorithm is used, to switch to the stored algorithm, `zip` can be set to ``'stored'``. `extensions` and `filter_func` are passed to :meth:`list_templates`. Each template returned will be compiled to the target folder or zipfile. By default template compilation errors are ignored. In case a log function is provided, errors are logged. If you want template syntax errors to abort the compilation you can set `ignore_errors` to `False` and you will get an exception on syntax errors. If `py_compile` is set to `True` .pyc files will be written to the target instead of standard .py files. .. versionadded:: 2.4 """ from jinja2.loaders import ModuleLoader if log_function is None: log_function = lambda x: None if py_compile: import imp, struct, marshal py_header = imp.get_magic() + \ u'\xff\xff\xff\xff'.encode('iso-8859-15') def write_file(filename, data, mode): if zip: info = ZipInfo(filename) info.external_attr = 0755 << 16L zip_file.writestr(info, data) else: f = open(os.path.join(target, filename), mode) try: f.write(data) finally: f.close() if zip is not None: from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED zip_file = ZipFile(target, 'w', dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]) log_function('Compiling into Zip archive "%s"' % target) else: if not os.path.isdir(target): os.makedirs(target) log_function('Compiling into folder "%s"' % target) try: for name in self.list_templates(extensions, filter_func): source, filename, _ = self.loader.get_source(self, name) try: code = self.compile(source, name, filename, True, True) except TemplateSyntaxError, e: if not ignore_errors: raise log_function('Could not compile "%s": %s' % (name, e)) continue filename = ModuleLoader.get_module_filename(name) if py_compile: c = compile(code, _encode_filename(filename), 'exec') write_file(filename + 'c', py_header + marshal.dumps(c), 'wb') log_function('Byte-compiled "%s" as %s' % (name, filename + 'c')) else: write_file(filename, code, 'w') log_function('Compiled "%s" as %s' % (name, filename)) finally: if zip: zip_file.close() log_function('Finished compiling templates') def list_templates(self, extensions=None, filter_func=None): """Returns a list of templates for this environment. This requires that the loader supports the loader's :meth:`~BaseLoader.list_templates` method. If there are other files in the template folder besides the actual templates, the returned list can be filtered. There are two ways: either `extensions` is set to a list of file extensions for templates, or a `filter_func` can be provided which is a callable that is passed a template name and should return `True` if it should end up in the result list. If the loader does not support that, a :exc:`TypeError` is raised. """ x = self.loader.list_templates() if extensions is not None: if filter_func is not None: raise TypeError('either extensions or filter_func ' 'can be passed, but not both') filter_func = lambda x: '.' in x and \ x.rsplit('.', 1)[1] in extensions if filter_func is not None: x = filter(filter_func, x) return x def handle_exception(self, exc_info=None, rendered=False, source_hint=None): """Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template. """ global _make_traceback if exc_info is None: exc_info = sys.exc_info() # the debugging module is imported when it's used for the first time. # we're doing a lot of stuff there and for applications that do not # get any exceptions in template rendering there is no need to load # all of that. if _make_traceback is None: from jinja2.debug import make_traceback as _make_traceback traceback = _make_traceback(exc_info, source_hint) if rendered and self.exception_formatter is not None: return self.exception_formatter(traceback) if self.exception_handler is not None: self.exception_handler(traceback) exc_type, exc_value, tb = traceback.standard_exc_info raise exc_type, exc_value, tb def join_path(self, template, parent): """Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the `template` parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name. Subclasses may override this method and implement template path joining here. """ return template @internalcode def _load_template(self, name, globals): if self.loader is None: raise TypeError('no loader for this environment specified') if self.cache is not None: template = self.cache.get(name) if template is not None and (not self.auto_reload or \ template.is_up_to_date): return template template = self.loader.load(self, name, globals) if self.cache is not None: self.cache[name] = template return template @internalcode def get_template(self, name, parent=None, globals=None): """Load a template from the loader. If a loader is configured this method ask the loader for the template and returns a :class:`Template`. If the `parent` parameter is not `None`, :meth:`join_path` is called to get the real template name before loading. The `globals` parameter can be used to provide template wide globals. These variables are available in the context at render time. If the template does not exist a :exc:`TemplateNotFound` exception is raised. .. versionchanged:: 2.4 If `name` is a :class:`Template` object it is returned from the function unchanged. """ if isinstance(name, Template): return name if parent is not None: name = self.join_path(name, parent) return self._load_template(name, self.make_globals(globals)) @internalcode def select_template(self, names, parent=None, globals=None): """Works like :meth:`get_template` but tries a number of templates before it fails. If it cannot find any of the templates, it will raise a :exc:`TemplatesNotFound` exception. .. versionadded:: 2.3 .. versionchanged:: 2.4 If `names` contains a :class:`Template` object it is returned from the function unchanged. """ if not names: raise TemplatesNotFound(message=u'Tried to select from an empty list ' u'of templates.') globals = self.make_globals(globals) for name in names: if isinstance(name, Template): return name if parent is not None: name = self.join_path(name, parent) try: return self._load_template(name, globals) except TemplateNotFound: pass raise TemplatesNotFound(names) @internalcode def get_or_select_template(self, template_name_or_list, parent=None, globals=None): """Does a typecheck and dispatches to :meth:`select_template` if an iterable of template names is given, otherwise to :meth:`get_template`. .. versionadded:: 2.3 """ if isinstance(template_name_or_list, basestring): return self.get_template(template_name_or_list, parent, globals) elif isinstance(template_name_or_list, Template): return template_name_or_list return self.select_template(template_name_or_list, parent, globals) def from_string(self, source, globals=None, template_class=None): """Load a template from a string. This parses the source given and returns a :class:`Template` object. """ globals = self.make_globals(globals) cls = template_class or self.template_class return cls.from_code(self, self.compile(source), globals, None) def make_globals(self, d): """Return a dict for the globals.""" if not d: return self.globals return dict(self.globals, **d) class Template(object): """The central template object. This class represents a compiled template and is used to evaluate it. Normally the template object is generated from an :class:`Environment` but it also has a constructor that makes it possible to create a template instance directly using the constructor. It takes the same arguments as the environment constructor but it's not possible to specify a loader. Every template object has a few methods and members that are guaranteed to exist. However it's important that a template object should be considered immutable. Modifications on the object are not supported. Template objects created from the constructor rather than an environment do have an `environment` attribute that points to a temporary environment that is probably shared with other templates created with the constructor and compatible settings. >>> template = Template('Hello {{ name }}!') >>> template.render(name='John Doe') u'Hello John Doe!' >>> stream = template.stream(name='John Doe') >>> stream.next() u'Hello John Doe!' >>> stream.next() Traceback (most recent call last): ... StopIteration """ def __new__(cls, source, block_start_string=BLOCK_START_STRING, block_end_string=BLOCK_END_STRING, variable_start_string=VARIABLE_START_STRING, variable_end_string=VARIABLE_END_STRING, comment_start_string=COMMENT_START_STRING, comment_end_string=COMMENT_END_STRING, line_statement_prefix=LINE_STATEMENT_PREFIX, line_comment_prefix=LINE_COMMENT_PREFIX, trim_blocks=TRIM_BLOCKS, newline_sequence=NEWLINE_SEQUENCE, extensions=(), optimized=True, undefined=Undefined, finalize=None, autoescape=False): env = get_spontaneous_environment( block_start_string, block_end_string, variable_start_string, variable_end_string, comment_start_string, comment_end_string, line_statement_prefix, line_comment_prefix, trim_blocks, newline_sequence, frozenset(extensions), optimized, undefined, finalize, autoescape, None, 0, False, None) return env.from_string(source, template_class=cls) @classmethod def from_code(cls, environment, code, globals, uptodate=None): """Creates a template object from compiled code and the globals. This is used by the loaders and environment to create a template object. """ namespace = { 'environment': environment, '__file__': code.co_filename } exec code in namespace rv = cls._from_namespace(environment, namespace, globals) rv._uptodate = uptodate return rv @classmethod def from_module_dict(cls, environment, module_dict, globals): """Creates a template object from a module. This is used by the module loader to create a template object. .. versionadded:: 2.4 """ return cls._from_namespace(environment, module_dict, globals) @classmethod def _from_namespace(cls, environment, namespace, globals): t = object.__new__(cls) t.environment = environment t.globals = globals t.name = namespace['name'] t.filename = namespace['__file__'] t.blocks = namespace['blocks'] # render function and module t.root_render_func = namespace['root'] t._module = None # debug and loader helpers t._debug_info = namespace['debug_info'] t._uptodate = None # store the reference namespace['environment'] = environment namespace['__jinja_template__'] = t return t def render(self, *args, **kwargs): """This method accepts the same arguments as the `dict` constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty. These two calls do the same:: template.render(knights='that say nih') template.render({'knights': 'that say nih'}) This will return the rendered template as unicode string. """ vars = dict(*args, **kwargs) try: return concat(self.root_render_func(self.new_context(vars))) except: exc_info = sys.exc_info() return self.environment.handle_exception(exc_info, True) def stream(self, *args, **kwargs): """Works exactly like :meth:`generate` but returns a :class:`TemplateStream`. """ return TemplateStream(self.generate(*args, **kwargs)) def generate(self, *args, **kwargs): """For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as unicode strings. It accepts the same arguments as :meth:`render`. """ vars = dict(*args, **kwargs) try: for event in self.root_render_func(self.new_context(vars)): yield event except: exc_info = sys.exc_info() else: return yield self.environment.handle_exception(exc_info, True) def new_context(self, vars=None, shared=False, locals=None): """Create a new :class:`Context` for this template. The vars provided will be passed to the template. Per default the globals are added to the context. If shared is set to `True` the data is passed as it to the context without adding the globals. `locals` can be a dict of local variables for internal usage. """ return new_context(self.environment, self.name, self.blocks, vars, shared, self.globals, locals) def make_module(self, vars=None, shared=False, locals=None): """This method works like the :attr:`module` attribute when called without arguments but it will evaluate the template on every call rather than caching it. It's also possible to provide a dict which is then used as context. The arguments are the same as for the :meth:`new_context` method. """ return TemplateModule(self, self.new_context(vars, shared, locals)) @property def module(self): """The template as module. This is used for imports in the template runtime but is also useful if one wants to access exported template variables from the Python layer: >>> t = Template('{% macro foo() %}42{% endmacro %}23') >>> unicode(t.module) u'23' >>> t.module.foo() u'42' """ if self._module is not None: return self._module self._module = rv = self.make_module() return rv def get_corresponding_lineno(self, lineno): """Return the source line number of a line number in the generated bytecode as they are not in sync. """ for template_line, code_line in reversed(self.debug_info): if code_line <= lineno: return template_line return 1 @property def is_up_to_date(self): """If this variable is `False` there is a newer version available.""" if self._uptodate is None: return True return self._uptodate() @property def debug_info(self): """The debug info mapping.""" return [tuple(map(int, x.split('='))) for x in self._debug_info.split('&')] def __repr__(self): if self.name is None: name = 'memory:%x' % id(self) else: name = repr(self.name) return '<%s %s>' % (self.__class__.__name__, name) class TemplateModule(object): """Represents an imported template. All the exported names of the template are available as attributes on this object. Additionally converting it into an unicode- or bytestrings renders the contents. """ def __init__(self, template, context): self._body_stream = list(template.root_render_func(context)) self.__dict__.update(context.get_exported()) self.__name__ = template.name def __html__(self): return Markup(concat(self._body_stream)) def __str__(self): return unicode(self).encode('utf-8') # unicode goes after __str__ because we configured 2to3 to rename # __unicode__ to __str__. because the 2to3 tree is not designed to # remove nodes from it, we leave the above __str__ around and let # it override at runtime. def __unicode__(self): return concat(self._body_stream) def __repr__(self): if self.__name__ is None: name = 'memory:%x' % id(self) else: name = repr(self.__name__) return '<%s %s>' % (self.__class__.__name__, name) class TemplateExpression(object): """The :meth:`jinja2.Environment.compile_expression` method returns an instance of this object. It encapsulates the expression-like access to the template with an expression it wraps. """ def __init__(self, template, undefined_to_none): self._template = template self._undefined_to_none = undefined_to_none def __call__(self, *args, **kwargs): context = self._template.new_context(dict(*args, **kwargs)) consume(self._template.root_render_func(context)) rv = context.vars['result'] if self._undefined_to_none and isinstance(rv, Undefined): rv = None return rv class TemplateStream(object): """A template stream works pretty much like an ordinary python generator but it can buffer multiple items to reduce the number of total iterations. Per default the output is unbuffered which means that for every unbuffered instruction in the template one unicode string is yielded. If buffering is enabled with a buffer size of 5, five items are combined into a new unicode string. This is mainly useful if you are streaming big templates to a client via WSGI which flushes after each iteration. """ def __init__(self, gen): self._gen = gen self.disable_buffering() def dump(self, fp, encoding=None, errors='strict'): """Dump the complete stream into a file or file-like object. Per default unicode strings are written, if you want to encode before writing specifiy an `encoding`. Example usage:: Template('Hello {{ name }}!').stream(name='foo').dump('hello.html') """ close = False if isinstance(fp, basestring): fp = file(fp, 'w') close = True try: if encoding is not None: iterable = (x.encode(encoding, errors) for x in self) else: iterable = self if hasattr(fp, 'writelines'): fp.writelines(iterable) else: for item in iterable: fp.write(item) finally: if close: fp.close() def disable_buffering(self): """Disable the output buffering.""" self._next = self._gen.next self.buffered = False def enable_buffering(self, size=5): """Enable buffering. Buffer `size` items before yielding them.""" if size <= 1: raise ValueError('buffer size too small') def generator(next): buf = [] c_size = 0 push = buf.append while 1: try: while c_size < size: c = next() push(c) if c: c_size += 1 except StopIteration: if not c_size: return yield concat(buf) del buf[:] c_size = 0 self.buffered = True self._next = generator(self._gen.next).next def __iter__(self): return self def next(self): return self._next() # hook in default template class. if anyone reads this comment: ignore that # it's possible to use custom templates ;-) Environment.template_class = Template
chand3040/cloud_that
refs/heads/named-release/cypress.rc
common/lib/xmodule/xmodule/seq_module.py
19
import json import logging import warnings from lxml import etree from xblock.fields import Integer, Scope, Boolean from xblock.fragment import Fragment from pkg_resources import resource_string from .exceptions import NotFoundError from .fields import Date from .mako_module import MakoModuleDescriptor from .progress import Progress from .x_module import XModule, STUDENT_VIEW from .xml_module import XmlDescriptor log = logging.getLogger(__name__) # HACK: This shouldn't be hard-coded to two types # OBSOLETE: This obsoletes 'type' class_priority = ['video', 'problem'] # Make '_' a no-op so we can scrape strings _ = lambda text: text class SequenceFields(object): has_children = True # NOTE: Position is 1-indexed. This is silly, but there are now student # positions saved on prod, so it's not easy to fix. position = Integer(help="Last tab viewed in this sequence", scope=Scope.user_state) due = Date( display_name=_("Due Date"), help=_("Enter the date by which problems are due."), scope=Scope.settings, ) # Entrance Exam flag -- see cms/contentstore/views/entrance_exam.py for usage is_entrance_exam = Boolean( display_name=_("Is Entrance Exam"), help=_( "Tag this course module as an Entrance Exam. " "Note, you must enable Entrance Exams for this course setting to take effect." ), default=False, scope=Scope.content, ) class SequenceModule(SequenceFields, XModule): ''' Layout module which lays out content in a temporal sequence ''' js = { 'coffee': [resource_string(__name__, 'js/src/sequence/display.coffee')], 'js': [resource_string(__name__, 'js/src/sequence/display/jquery.sequence.js')], } css = { 'scss': [resource_string(__name__, 'css/sequence/display.scss')], } js_module_name = "Sequence" def __init__(self, *args, **kwargs): super(SequenceModule, self).__init__(*args, **kwargs) # If position is specified in system, then use that instead. position = getattr(self.system, 'position', None) if position is not None: try: self.position = int(self.system.position) except (ValueError, TypeError): # Check for https://openedx.atlassian.net/browse/LMS-6496 warnings.warn( "Sequential position cannot be converted to an integer: {pos!r}".format( pos=self.system.position, ), RuntimeWarning, ) def get_progress(self): ''' Return the total progress, adding total done and total available. (assumes that each submodule uses the same "units" for progress.) ''' # TODO: Cache progress or children array? children = self.get_children() progresses = [child.get_progress() for child in children] progress = reduce(Progress.add_counts, progresses, None) return progress def handle_ajax(self, dispatch, data): # TODO: bounds checking ''' get = request.POST instance ''' if dispatch == 'goto_position': # set position to default value if either 'position' argument not # found in request or it is a non-positive integer position = data.get('position', u'1') if position.isdigit() and int(position) > 0: self.position = int(position) else: self.position = 1 return json.dumps({'success': True}) raise NotFoundError('Unexpected dispatch type') def student_view(self, context): # If we're rendering this sequence, but no position is set yet, # default the position to the first element if self.position is None: self.position = 1 ## Returns a set of all types of all sub-children contents = [] fragment = Fragment() for child in self.get_display_items(): progress = child.get_progress() rendered_child = child.render(STUDENT_VIEW, context) fragment.add_frag_resources(rendered_child) titles = child.get_content_titles() childinfo = { 'content': rendered_child.content, 'title': "\n".join(titles), 'page_title': titles[0] if titles else '', 'progress_status': Progress.to_js_status_str(progress), 'progress_detail': Progress.to_js_detail_str(progress), 'type': child.get_icon_class(), 'id': child.scope_ids.usage_id.to_deprecated_string(), } if childinfo['title'] == '': childinfo['title'] = child.display_name_with_default contents.append(childinfo) params = {'items': contents, 'element_id': self.location.html_id(), 'item_id': self.location.to_deprecated_string(), 'position': self.position, 'tag': self.location.category, 'ajax_url': self.system.ajax_url, } fragment.add_content(self.system.render_template('seq_module.html', params)) return fragment def get_icon_class(self): child_classes = set(child.get_icon_class() for child in self.get_children()) new_class = 'other' for c in class_priority: if c in child_classes: new_class = c return new_class class SequenceDescriptor(SequenceFields, MakoModuleDescriptor, XmlDescriptor): mako_template = 'widgets/sequence-edit.html' module_class = SequenceModule js = { 'coffee': [resource_string(__name__, 'js/src/sequence/edit.coffee')], } js_module_name = "SequenceDescriptor" @classmethod def definition_from_xml(cls, xml_object, system): children = [] for child in xml_object: try: child_block = system.process_xml(etree.tostring(child, encoding='unicode')) children.append(child_block.scope_ids.usage_id) except Exception as e: log.exception("Unable to load child when parsing Sequence. Continuing...") if system.error_tracker is not None: system.error_tracker(u"ERROR: {0}".format(e)) continue return {}, children def definition_to_xml(self, resource_fs): xml_object = etree.Element('sequential') for child in self.get_children(): self.runtime.add_block_as_child_node(child, xml_object) return xml_object @property def non_editable_metadata_fields(self): """ `is_entrance_exam` should not be editable in the Studio settings editor. """ non_editable_fields = super(SequenceDescriptor, self).non_editable_metadata_fields non_editable_fields.append(self.fields['is_entrance_exam']) return non_editable_fields def index_dictionary(self): """ Return dictionary prepared with module content and type for indexing. """ # return key/value fields in a Python dict object # values may be numeric / string or dict # default implementation is an empty dict xblock_body = super(SequenceDescriptor, self).index_dictionary() html_body = { "display_name": self.display_name, } if "content" in xblock_body: xblock_body["content"].update(html_body) else: xblock_body["content"] = html_body xblock_body["content_type"] = "Sequence" return xblock_body
le9i0nx/ansible
refs/heads/devel
test/units/template/test_template_utilities.py
119
# (c) 2015 Toshio Kuratomi <tkuratomi@ansible.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/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import jinja2 from ansible.compat.tests import unittest from ansible.template import _escape_backslashes, _count_newlines_from_end # These are internal utility functions only needed for templating. They're # algorithmic so good candidates for unittesting by themselves class TestBackslashEscape(unittest.TestCase): test_data = ( # Test backslashes in a filter arg are double escaped dict( template=u"{{ 'test2 %s' | format('\\1') }}", intermediate=u"{{ 'test2 %s' | format('\\\\1') }}", expectation=u"test2 \\1", args=dict() ), # Test backslashes inside the jinja2 var itself are double # escaped dict( template=u"Test 2\\3: {{ '\\1 %s' | format('\\2') }}", intermediate=u"Test 2\\3: {{ '\\\\1 %s' | format('\\\\2') }}", expectation=u"Test 2\\3: \\1 \\2", args=dict() ), # Test backslashes outside of the jinja2 var are not double # escaped dict( template=u"Test 2\\3: {{ 'test2 %s' | format('\\1') }}; \\done", intermediate=u"Test 2\\3: {{ 'test2 %s' | format('\\\\1') }}; \\done", expectation=u"Test 2\\3: test2 \\1; \\done", args=dict() ), # Test backslashes in a variable sent to a filter are handled dict( template=u"{{ 'test2 %s' | format(var1) }}", intermediate=u"{{ 'test2 %s' | format(var1) }}", expectation=u"test2 \\1", args=dict(var1=u'\\1') ), # Test backslashes in a variable expanded by jinja2 are double # escaped dict( template=u"Test 2\\3: {{ var1 | format('\\2') }}", intermediate=u"Test 2\\3: {{ var1 | format('\\\\2') }}", expectation=u"Test 2\\3: \\1 \\2", args=dict(var1=u'\\1 %s') ), ) def setUp(self): self.env = jinja2.Environment() def tearDown(self): pass def test_backslash_escaping(self): for test in self.test_data: intermediate = _escape_backslashes(test['template'], self.env) self.assertEquals(intermediate, test['intermediate']) template = jinja2.Template(intermediate) args = test['args'] self.assertEquals(template.render(**args), test['expectation']) class TestCountNewlines(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_zero_length_string(self): self.assertEquals(_count_newlines_from_end(u''), 0) def test_short_string(self): self.assertEquals(_count_newlines_from_end(u'The quick\n'), 1) def test_one_newline(self): self.assertEquals(_count_newlines_from_end(u'The quick brown fox jumped over the lazy dog' * 1000 + u'\n'), 1) def test_multiple_newlines(self): self.assertEquals(_count_newlines_from_end(u'The quick brown fox jumped over the lazy dog' * 1000 + u'\n\n\n'), 3) def test_zero_newlines(self): self.assertEquals(_count_newlines_from_end(u'The quick brown fox jumped over the lazy dog' * 1000), 0) def test_all_newlines(self): self.assertEquals(_count_newlines_from_end(u'\n' * 10), 10) def test_mostly_newlines(self): self.assertEquals(_count_newlines_from_end(u'The quick brown fox jumped over the lazy dog' + u'\n' * 1000), 1000)
cheenwe/cheenwe.github.io
refs/heads/master
_posts/study/python/8_get_web_page.py
2
import socket s = socket.socket() host = socket.gethostname() port = 1234 s.bind((host, port)) s.listen(5) while True: c, addr = s.accept() print "Get coonect from", addr c.send('Thanks your coonecting') c.close()
ricpol/quickreport
refs/heads/master
quickreport/chinook_demo/param_types.py
1
# -*- coding: utf8 -*- """Quickreport - param_types.py Questo modulo raccoglie i tipi di parametro definiti nel progetto, da usare in aggiunta a quelli messi a disposizione in quickreport.param_types. Per un'idea di come definire i tipi, vedi anche quickreport.param_types. Per ogni tipo occorre definire una classe wx che definisce il widget da usare nella gui, e una funzione factory. La classe deve supportare queste API: 1) GetValue, che restituisce il valore del widget (usato al momento di raccogliere il valore del parametro per elaborare l'output) 2) SetValue, che assegna un valore al widget (usato per impostare il default del widget) 3) SetBounds, che assegna i bounds al widget (p. es. liste di possibili scelte, minimi e massimi, etc.) (usato per impostare i bounds del widget) 4) Inoltre devono notificare il cambiamento di valore chiamando la funzione post_evt_param_changed (gia' predisposta e importata) I punti 2-4 non sono obbligatori, se non si intendono usare default, bounds, o recalc per il parametro (vedi params.py per i dettagli). In questo caso, bastera' fornire un'interfaccia vuota (con "pass"). La funzione factory deve avere il nome esatto del tipo di parametro, prende un solo argomento (il parent del widget), e restituisce una istanza del widget definito dalla classe. Schema di esempio che definisce il tipo "myparam": class MyParamWidget(wx.<SomeCtrl>): def __init__(self, *a, **k): wx.<SomeCtrl>.__init__(self, *a, **k) self.Bind(wx.<SOME_APPROPRIATE_EVENT>, post_evt_param_changed) # oppure anche: # self.Bind(wx.<SOME_APPROPRIATE_EVENT>, self.a_callback) def a_callback(self, evt): # processo l'evento internamente, e concludo: post_evt_param_changed(evt) def GetValue: # ... def SetValue: pass def SetBounds: pass def myparam(parent): return MyParamWidget(parent) """ import wx from ..gui_utils import post_evt_param_changed
barryrobison/anim-studio-tools
refs/heads/master
napalm/core/test/test.py
5
import sys import napalm.core as n import pimath as p # globals fileTypes = [ "nap", "xml" ] delayLoadableFileTypes = [ "nap" ] # helper function which returns a table containing all types that napalm uses def createUberTable(): t = n.ObjectTable() t[1] = 1 # this is interpreted as an int t[2] = 2.2 # this is interpreted as a float t[3] = n.Double(3.333) t[4] = "hello" t[5] = n.Char(-10) # in napalm, a char is interpreted as a number t[6] = n.UChar(200) # as is an unsigned char t[7] = n.Short(-30000) t[8] = n.UShort(60000) t[9] = n.UInt(2000000000) # todo add the new imath types inc half t[10] = p.V3f() t[11] = p.V3d() t[12] = p.M33f() t[13] = p.M33d() t[14] = p.M44f() t[15] = p.M44d() sz = 100 t[16] = n.CharBuffer(sz) t[17] = n.FloatBuffer(sz) t[18] = n.DoubleBuffer(sz) t[19] = n.IntBuffer(sz) t[20] = n.V3fBuffer(sz) t[21] = n.V3dBuffer(sz) t[22] = n.M33fBuffer(sz) t[23] = n.M33dBuffer(sz) t[24] = n.M44fBuffer(sz) t[25] = n.M44dBuffer(sz) t[16].attribs["a1"] = "aaa1" t["hey"] = "ho" return t # check types def testTypes(): t = createUberTable() assert(type(t[1]) == int) assert(type(t[2]) == float) assert(type(t[3]) == float) # python has just the one real-number type assert(type(t[4]) == str) assert(type(t[5]) == int) # basic file tests def testFile(): # test1 fail = False try: b = n.load("some_nonexistant_file.foo") except n.NapalmFileError: fail = True assert(fail) # test2 f = open("/tmp/notnapalm.txt", "w") f.write("this is not a napalm file.") f.close() fail = False try: b = n.load("/tmp/notnapalm.txt") except n.NapalmSerializeError: fail = True assert(fail) # basic buffer tests def testBuf(): # test1 b = n.IntBuffer() assert(len(b) == 0) # test2 b = n.IntBuffer(10, 7) assert(b[3] == 7) # test3 b = n.IntBuffer(3,2) assert(b.contents == [2,2,2]) # test4 b = n.IntBuffer(4,6) b2 = b.clone() assert(b2.contents == [6,6,6,6]) b2[0] = 7 assert(b2.contents == [7,6,6,6]) # test5 b = n.IntBuffer(10) assert(len(b) == 10) b[9] = 100 assert(b[9] == 100) fail = False; try: b[10] except IndexError: fail = True assert(fail) # basic table tests def testTable(): t = n.ObjectTable() assert(len(t) == 0) fail = False; try: t["foo"] except KeyError: fail = True assert(fail) t[1] = 1.111 t["two"] = 68 t[3] = p.V3f(5,6,7) t["four"] = 'Q' assert(len(t) == 4) assert("two" in t) assert("blah" not in t) assert(t["two"] == 68) assert(t["four"] == 'Q') vdiff = t[3] - p.V3f(5,6,7) assert(vdiff.length() < 0.0001) t["buf"] = n.IntBuffer(100) t["buf"][50] = 50 assert(t["buf"][50] == 50) del t["four"] del t[3] assert(len(t) == 3) assert(3 not in t) keys = t.keys() keys2 = [] for k in t: keys2.append(k) assert(keys == keys2) # save an intBuf, load and make sure it's the same def testIntBufSerialize(ext): # create test data on disk filepath = "/tmp/intbuf." + ext sz = 50 b = n.IntBuffer(sz) b[5] = 5 n.save(b, filepath) b2 = n.load(filepath) if ext in delayLoadableFileTypes: assert(b2.clientSize() == 0) else: assert(b2.clientSize() == sz) assert(type(b) == type(b2)) assert(len(b) == len(b2)) assert(b2[5] == b[5]) if ext in delayLoadableFileTypes: assert(b2.clientSize() == sz) # save a V3fBuf, load and make sure it's the same def testV3fBufSerialize(ext): # create test data on disk filepath = "/tmp/v3fbuf." + ext b = n.V3fBuffer(100) b[50] = p.V3f(3.3, 4.4, 5.5) n.save(b, filepath) b2 = n.load(filepath) assert(type(b) == type(b2)) assert(len(b) == len(b2)) vdiff = b[50] - b2[50] assert(vdiff.length() < 0.001) # save a table, load and make sure it's the same def testTableSerialize(ext): # create test data on disk filepath = "/tmp/tbl1." + ext t = createUberTable() n.save(t, filepath) for delayload in [True,False]: t2 = n.load(filepath, delayload) assert(n.areEqual(t,t2)) # brute-force serialisation testing. Data is serialised via every different combination # of file type and save/load option, and then checked for equivalence. def testSerializeBruteForce(): fileprefix = "/tmp/tblbrute." t = createUberTable() # save files = [] for ext in fileTypes: for compression in [0,1,2]: filepath = fileprefix + str(compression) + '.' + ext n.save(t, filepath, compression) files.append(filepath) # load for delayload in [True,False]: for f in files: t2 = n.load(f, delayload) assert(n.areEqual(t,t2)) # basic buffer cloning tests def testBufCloning(): sz = 10 b = n.IntBuffer(sz) b[4] = 40 b2 = b.clone() assert(b.hasSharedStore(b2)) assert(not b.uniqueStore()) assert(not b2.uniqueStore()) assert(b.storeUseCount() == 2) assert(b2.storeUseCount() == 2) b3 = b2.clone() assert(b3.hasSharedStore(b)) assert(not b.uniqueStore()) assert(not b2.uniqueStore()) assert(not b3.uniqueStore()) assert(b.storeUseCount() == 3) assert(b2.storeUseCount() == 3) assert(b3.storeUseCount() == 3) b[6] = 66 # will cause copy-on-write assert(b.uniqueStore()) assert(b2.hasSharedStore(b3)) assert(not b2.uniqueStore()) assert(not b3.uniqueStore()) assert(b.storeUseCount() == 1) assert(b2.storeUseCount() == 2) assert(b3.storeUseCount() == 2) b3[2] = 22 # will cause copy-on-write assert(b2.uniqueStore()) assert(b3.uniqueStore()) assert(not b2.hasSharedStore(b3)) # basic table cloning tests def testTableCloning(): t = n.ObjectTable() t[1] = 1 t["two"] = "222" t[3] = n.IntBuffer(100) t[4] = t[3] t[5] = t[3].clone() assert(t[3].storeUseCount() == 2) t2 = t.clone() assert(t.keys() == t2.keys()) assert(t2[1] == 1) assert(t2["two"] == "222") assert(t2[3] != t[3]) assert(t2[3].hasSharedStore(t[3])) assert(t2[4] == t2[3]) assert(t[3].storeUseCount() == 4) # test delay-loading def testDelayLoad(ext): # create test data on disk filepath = "/tmp/dl1." + ext sz = 100 t_ = n.ObjectTable() for i in range(10): t_[i] = n.IntBuffer(sz) n.save(t_, filepath) # test1: make sure a buffer's data isn't made resident until it's accessed t = n.load(filepath) expected_count = sz for i in t.iteritems(): i[1][0] # force resident via zeroeth element read count = 0 for j in t.iteritems(): count += j[1].clientSize() assert(count == expected_count) expected_count += sz # test delay-load + cloning cases (where cloning happens pre-load) def testDelayLoadAndPreCloning(ext): # create test data on disk filepath = "/tmp/clpre." + ext sz = 13 t_ = n.ObjectTable() b_ = n.IntBuffer(sz) b2_ = b_.clone() t_[1] = b_ t_[2] = b2_ n.save(t_, filepath) # test1: Make sure that when buffers are loaded, their cloned relationships are kept intact t = n.load(filepath) assert(t.keys() == t_.keys()) assert(t[1].hasSharedStore(t[2])) t[2][0] # force resident via zeroeth element read assert(t[1].clientSize() == sz) assert(t[1].hasSharedStore(t[2])) # test delay-load + cloning cases (where cloning happens post-load) def testDelayLoadAndPostCloning(ext): # create test data on disk filepath = "/tmp/clpost." + ext sz = 1000 b_ = n.IntBuffer(sz) b_[60] = 600 assert(b_.clientSize() == sz) n.save(b_, filepath) # test1: Make sure that cloning a buffer doesn't force any data resident. Also make # sure that if either buffer forces data resident via a read, both buffers get the # same resident data. b = n.load(filepath) assert(b.clientSize() == 0) b2 = b.clone() assert(b.clientSize() == 0) assert(b2.clientSize() == 0) assert(b[60] == 600) # will cause buffer to load into mem assert(b.clientSize() == sz) assert(b2.clientSize() == sz) assert(b.hasSharedStore(b2)) # test2: Make sure that if a buffer's data is non-resident, and then it is cloned, # then the clone is accessed for writing, that the original buffer's data is NOT # made resident. c = n.load(filepath) assert(c.uniqueStore()) assert(c.clientSize() == 0) c2 = c.clone() assert(c2.clientSize() == 0) c2[6] = 66 # will cause data to load for c2, but still not for c...! assert(c.clientSize() == 0) assert(c2.clientSize() == sz) def testToString(): t = n.ObjectTable() assert( str(t) == "{}" ) t[0] = '1' t['1'] = 0.0 t[2] = p.V3f(0,1,2) assert( str(t) == '{"1": 0.f, 0: "1", 2: V3f(0, 1, 2)}' ) def testToPyString(): t = n.ObjectTable() assert( t.pyStr()== "{}" ) t[0] = '1' t['1'] = 0.0 t[2] = p.V3f(0,1,2) assert( t.pyStr() == '{"1": 0., 0: "1", 2: V3f(0, 1, 2)}' ) def testToTupleString(): t = n.ObjectTable() assert( t.tupStr() == "{}" ) t[0] = '1' t['1'] = 0.0 t[2] = p.V3f(0,1,2) assert( t.tupStr() == '{"1": 0., 0: "1", 2: (0, 1, 2)}' ) exec("m="+t.tupStr()) assert( m == {"1":0.,0:"1",2:(0,1,2)}) ########### main print("testing napalm v" + n.getAPIVersion() + " (core)...") assert(n.getTotalClientBytes() == 0) testTypes() testFile() testBuf() testTable() testBufCloning() testTableCloning() testSerializeBruteForce() for ft in fileTypes: testIntBufSerialize(ft) testV3fBufSerialize(ft) testTableSerialize(ft) for ft in delayLoadableFileTypes: testDelayLoad(ft) testDelayLoadAndPreCloning(ft) testDelayLoadAndPostCloning(ft) assert(n.getTotalClientBytes() == 0) testToString() testToPyString() testToTupleString() print "success" # Copyright 2008-2012 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios) # # This file is part of anim-studio-tools. # # anim-studio-tools is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # anim-studio-tools 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 Lesser General Public License # along with anim-studio-tools. If not, see <http://www.gnu.org/licenses/>.
JackDandy/SickGear
refs/heads/master
lib/hachoir_py3/subfile/data_rate.py
2
from time import time DATARATE_UPDATE = 1.0 # Time slice (in second) for datarate computation class DataRate: """ Compute average speed in bits per second of a function. Store self.size data rates to compute good average speed. Don't compute average before self.min_size values are computed. """ def __init__(self, offset, size=20, min_size=3): self.last_offset = offset self.last_time = time() self.datarates = [] # Average bit rate self.average = None # Number of stored value used to compute average data rate self.size = size self.min_size = min_size def update(self, offset): # Compute time delta difftime = time() - self.last_time if difftime < DATARATE_UPDATE: # Only update each second return self.last_time = time() # Compute data rate rate = float(offset - self.last_offset) / difftime self.last_offset = offset # Update statistics self.datarates.append(rate) self.datarates = self.datarates[-self.size:] if self.min_size <= len(self.datarates): self.average = sum(self.datarates) / len(self.datarates)
janusnic/21v-pyqt
refs/heads/master
unit_03/clock/timer6.py
1
#!/usr/bin/env python # -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui class WigglyWidget(QtGui.QWidget): def __init__(self, parent=None): super(WigglyWidget, self).__init__(parent) self.setBackgroundRole(QtGui.QPalette.Midlight) self.setAutoFillBackground(True) newFont = self.font() newFont.setPointSize(newFont.pointSize() + 20) self.setFont(newFont) self.timer = QtCore.QBasicTimer() self.text = '' self.step = 0; self.timer.start(60, self) def paintEvent(self, event): sineTable = (0, 38, 71, 92, 100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71, -38) metrics = QtGui.QFontMetrics(self.font()) x = (self.width() - metrics.width(self.text)) / 2 y = (self.height() + metrics.ascent() - metrics.descent()) / 2 color = QtGui.QColor() painter = QtGui.QPainter(self) for i, ch in enumerate(self.text): index = (self.step + i) % 16 color.setHsv((15 - index) * 16, 255, 191) painter.setPen(color) painter.drawText(x, y - ((sineTable[index] * metrics.height()) / 400), ch) x += metrics.width(ch) def setText(self, newText): self.text = newText def timerEvent(self, event): if event.timerId() == self.timer.timerId(): self.step += 1 self.update() else: super(WigglyWidget, self).timerEvent(event) class Dialog(QtGui.QDialog): def __init__(self, parent=None): super(Dialog, self).__init__(parent) wigglyWidget = WigglyWidget() lineEdit = QtGui.QLineEdit() layout = QtGui.QVBoxLayout() layout.addWidget(wigglyWidget) layout.addWidget(lineEdit) self.setLayout(layout) lineEdit.textChanged.connect(wigglyWidget.setText) lineEdit.setText("Hello world!") self.setWindowTitle("Wiggly") self.resize(360, 145) if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) dialog = Dialog() dialog.show(); sys.exit(app.exec_())
getKiwiCoin/KiwiCoin
refs/heads/master
share/qt/clean_mac_info_plist.py
1
#!/usr/bin/env python # Jonas Schnelli, 2013 # make sure the Kiwicoin-Qt.app contains the right plist (including the right version) # fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267) from string import Template from datetime import date bitcoinDir = "./"; inFile = bitcoinDir+"/share/qt/Info.plist" outFile = "Kiwicoin-Qt.app/Contents/Info.plist" version = "unknown"; fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro" for line in open(fileForGrabbingVersion): lineArr = line.replace(" ", "").split("="); if lineArr[0].startswith("VERSION"): version = lineArr[1].replace("\n", ""); fIn = open(inFile, "r") fileContent = fIn.read() s = Template(fileContent) newFileContent = s.substitute(VERSION=version,YEAR=date.today().year) fOut = open(outFile, "w"); fOut.write(newFileContent); print "Info.plist fresh created"
shonenada/flask-captcha
refs/heads/master
flask_captcha/view.py
1
import random try: from cStringIO import StringIO except ImportError: from io import BytesIO as StringIO from flask import Blueprint, make_response, current_app, session from wheezy.captcha.image import captcha from wheezy.captcha.image import background from wheezy.captcha.image import curve from wheezy.captcha.image import noise from wheezy.captcha.image import smooth from wheezy.captcha.image import text from wheezy.captcha.image import offset from wheezy.captcha.image import rotate from wheezy.captcha.image import warp captcha_bp = Blueprint('captcha', __name__) def sample_chars(): characters = current_app.config['CAPTCHA_CHARACTERS'] char_length = current_app.config['CAPTCHA_CHARS_LENGTH'] captcha_code = random.sample(characters, char_length) return captcha_code @captcha_bp.route('/captcha', endpoint="captcha") def captcha_view(): out = StringIO() captcha_image = captcha(drawings=[ background(), text(fonts=current_app.config['CAPTCHA_FONTS'], drawings=[warp(), rotate(), offset()]), curve(), noise(), smooth(), ]) captcha_code = ''.join(sample_chars()) imgfile = captcha_image(captcha_code) session['captcha'] = captcha_code imgfile.save(out, 'PNG') out.seek(0) response = make_response(out.read()) response.content_type = 'image/png' return response
romain-dartigues/ansible
refs/heads/devel
lib/ansible/modules/cloud/ovirt/ovirt_auth.py
5
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ovirt_auth short_description: "Module to manage authentication to oVirt/RHV" author: "Ondra Machacek (@machacekondra)" version_added: "2.2" description: - "This module authenticates to oVirt/RHV engine and creates SSO token, which should be later used in all other oVirt/RHV modules, so all modules don't need to perform login and logout. This module returns an Ansible fact called I(ovirt_auth). Every module can use this fact as C(auth) parameter, to perform authentication." options: state: default: present choices: ['present', 'absent'] description: - "Specifies if a token should be created or revoked." username: required: False description: - "The name of the user. For example: I(admin@internal) Default value is set by I(OVIRT_USERNAME) environment variable." password: required: False description: - "The password of the user. Default value is set by I(OVIRT_PASSWORD) environment variable." token: required: False description: - "SSO token to be used instead of login with username/password. Default value is set by I(OVIRT_TOKEN) environment variable." version_added: 2.5 url: required: False description: - "A string containing the API URL of the server. For example: I(https://server.example.com/ovirt-engine/api). Default value is set by I(OVIRT_URL) environment variable." - "Either C(url) or C(hostname) is required." hostname: required: False description: - "A string containing the hostname of the server. For example: I(server.example.com). Default value is set by I(OVIRT_HOSTNAME) environment variable." - "Either C(url) or C(hostname) is required." version_added: "2.6" insecure: required: False description: - "A boolean flag that indicates if the server TLS certificate and host name should be checked." type: bool ca_file: required: False description: - "A PEM file containing the trusted CA certificates. The certificate presented by the server will be verified using these CA certificates. If C(ca_file) parameter is not set, system wide CA certificate store is used. Default value is set by I(OVIRT_CAFILE) environment variable." timeout: required: False description: - "The maximum total time to wait for the response, in seconds. A value of zero (the default) means wait forever. If the timeout expires before the response is received an exception will be raised." compress: required: False description: - "A boolean flag indicating if the SDK should ask the server to send compressed responses. The default is I(True). Note that this is a hint for the server, and that it may return uncompressed data even when this parameter is set to I(True)." type: bool kerberos: required: False description: - "A boolean flag indicating if Kerberos authentication should be used instead of the default basic authentication." type: bool headers: required: False description: - "A dictionary of HTTP headers to be added to each API call." version_added: "2.4" requirements: - python >= 2.7 - ovirt-engine-sdk-python >= 4.2.4 notes: - "Everytime you use ovirt_auth module to obtain ticket, you need to also revoke the ticket, when you no longer need it, otherwise the ticket would be revoked by engine when it expires. For an example of how to achieve that, please take a look at I(examples) section." - "In order to use this module you have to install oVirt/RHV Python SDK. To ensure it's installed with correct version you can create the following task: I(pip: name=ovirt-engine-sdk-python version=4.2.4)" - "Note that in oVirt/RHV 4.1 if you want to use a user which is not administrator you must enable the I(ENGINE_API_FILTER_BY_DEFAULT) variable in engine. In oVirt/RHV 4.2 and later it's enabled by default." ''' EXAMPLES = ''' - block: # Create a vault with `ovirt_password` variable which store your # oVirt/RHV user's password, and include that yaml file with variable: - include_vars: ovirt_password.yml - name: Obtain SSO token with using username/password credentials ovirt_auth: url: https://ovirt.example.com/ovirt-engine/api username: admin@internal ca_file: ca.pem password: "{{ ovirt_password }}" # Previous task generated I(ovirt_auth) fact, which you can later use # in different modules as follows: - ovirt_vms: auth: "{{ ovirt_auth }}" state: absent name: myvm always: - name: Always revoke the SSO token ovirt_auth: state: absent ovirt_auth: "{{ ovirt_auth }}" # When user will set following environment variables: # OVIRT_URL = https://fqdn/ovirt-engine/api # OVIRT_USERNAME = admin@internal # OVIRT_PASSWORD = the_password # User can login the oVirt using environment variable instead of variables # in yaml file. # This is mainly useful when using Ansible Tower or AWX, as it will work # for Red Hat Virtualization creadentials type. - name: Obtain SSO token ovirt_auth: state: present ''' RETURN = ''' ovirt_auth: description: Authentication facts, needed to perform authentication to oVirt/RHV. returned: success type: complex contains: token: description: SSO token which is used for connection to oVirt/RHV engine. returned: success type: string sample: "kdfVWp9ZgeewBXV-iq3Js1-xQJZPSEQ334FLb3eksoEPRaab07DhZ8ED8ghz9lJd-MQ2GqtRIeqhvhCkrUWQPw" url: description: URL of the oVirt/RHV engine API endpoint. returned: success type: string sample: "https://ovirt.example.com/ovirt-engine/api" ca_file: description: CA file, which is used to verify SSL/TLS connection. returned: success type: path sample: "ca.pem" insecure: description: Flag indicating if insecure connection is used. returned: success type: bool sample: False timeout: description: Number of seconds to wait for response. returned: success type: int sample: 0 compress: description: Flag indicating if compression is used for connection. returned: success type: bool sample: True kerberos: description: Flag indicating if kerberos is used for authentication. returned: success type: bool sample: False headers: description: Dictionary of HTTP headers to be added to each API call. returned: success type: dict ''' import os import traceback try: import ovirtsdk4 as sdk except ImportError: pass from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ovirt import check_sdk def main(): module = AnsibleModule( argument_spec=dict( url=dict(default=None), hostname=dict(default=None), username=dict(default=None), password=dict(default=None, no_log=True), ca_file=dict(default=None, type='path'), insecure=dict(required=False, type='bool', default=None), timeout=dict(required=False, type='int', default=0), compress=dict(required=False, type='bool', default=True), kerberos=dict(required=False, type='bool', default=False), headers=dict(required=False, type='dict'), state=dict(default='present', choices=['present', 'absent']), token=dict(default=None), ovirt_auth=dict(required=None, type='dict'), ), required_if=[ ('state', 'absent', ['ovirt_auth']), ], supports_check_mode=True, ) check_sdk(module) state = module.params.get('state') if state == 'present': params = module.params elif state == 'absent': params = module.params['ovirt_auth'] def get_required_parameter(param, env_var, required=False): var = params.get(param) or os.environ.get(env_var) if not var and required and state == 'present': module.fail_json(msg="'%s' is a required parameter." % param) return var url = get_required_parameter('url', 'OVIRT_URL', required=False) hostname = get_required_parameter('hostname', 'OVIRT_HOSTNAME', required=False) if url is None and hostname is None: module.fail_json(msg="You must specify either 'url' or 'hostname'.") if url is None and hostname is not None: url = 'https://{0}/ovirt-engine/api'.format(hostname) username = get_required_parameter('username', 'OVIRT_USERNAME') password = get_required_parameter('password', 'OVIRT_PASSWORD') token = get_required_parameter('token', 'OVIRT_TOKEN') ca_file = get_required_parameter('ca_file', 'OVIRT_CAFILE') insecure = params.get('insecure') if params.get('insecure') is not None else not bool(ca_file) connection = sdk.Connection( url=url, username=username, password=password, ca_file=ca_file, insecure=insecure, timeout=params.get('timeout'), compress=params.get('compress'), kerberos=params.get('kerberos'), headers=params.get('headers'), token=token, ) try: token = connection.authenticate() module.exit_json( changed=False, ansible_facts=dict( ovirt_auth=dict( token=token, url=url, ca_file=ca_file, insecure=insecure, timeout=params.get('timeout'), compress=params.get('compress'), kerberos=params.get('kerberos'), headers=params.get('headers'), ) if state == 'present' else dict() ) ) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: # Close the connection, but don't revoke token connection.close(logout=state == 'absent') if __name__ == "__main__": main()
beckastar/django
refs/heads/master
django/contrib/gis/geos/prototypes/geom.py
114
from ctypes import c_char_p, c_int, c_size_t, c_ubyte, POINTER from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR from django.contrib.gis.geos.prototypes.errcheck import ( check_geom, check_minus_one, check_sized_string, check_string, check_zero) from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc # This is the return type used by binary output (WKB, HEX) routines. c_uchar_p = POINTER(c_ubyte) # We create a simple subclass of c_char_p here because when the response # type is set to c_char_p, you get a _Python_ string and there's no way # to access the string's address inside the error checking function. # In other words, you can't free the memory allocated inside GEOS. Previously, # the return type would just be omitted and the integer address would be # used -- but this allows us to be specific in the function definition and # keeps the reference so it may be free'd. class geos_char_p(c_char_p): pass ### ctypes generation functions ### def bin_constructor(func): "Generates a prototype for binary construction (HEX, WKB) GEOS routines." func.argtypes = [c_char_p, c_size_t] func.restype = GEOM_PTR func.errcheck = check_geom return func # HEX & WKB output def bin_output(func): "Generates a prototype for the routines that return a sized string." func.argtypes = [GEOM_PTR, POINTER(c_size_t)] func.errcheck = check_sized_string func.restype = c_uchar_p return func def geom_output(func, argtypes): "For GEOS routines that return a geometry." if argtypes: func.argtypes = argtypes func.restype = GEOM_PTR func.errcheck = check_geom return func def geom_index(func): "For GEOS routines that return geometries from an index." return geom_output(func, [GEOM_PTR, c_int]) def int_from_geom(func, zero=False): "Argument is a geometry, return type is an integer." func.argtypes = [GEOM_PTR] func.restype = c_int if zero: func.errcheck = check_zero else: func.errcheck = check_minus_one return func def string_from_geom(func): "Argument is a Geometry, return type is a string." func.argtypes = [GEOM_PTR] func.restype = geos_char_p func.errcheck = check_string return func ### ctypes prototypes ### # Deprecated creation routines from WKB, HEX, WKT from_hex = bin_constructor(GEOSFunc('GEOSGeomFromHEX_buf')) from_wkb = bin_constructor(GEOSFunc('GEOSGeomFromWKB_buf')) from_wkt = geom_output(GEOSFunc('GEOSGeomFromWKT'), [c_char_p]) # Deprecated output routines to_hex = bin_output(GEOSFunc('GEOSGeomToHEX_buf')) to_wkb = bin_output(GEOSFunc('GEOSGeomToWKB_buf')) to_wkt = string_from_geom(GEOSFunc('GEOSGeomToWKT')) # The GEOS geometry type, typeid, num_coordites and number of geometries geos_normalize = int_from_geom(GEOSFunc('GEOSNormalize')) geos_type = string_from_geom(GEOSFunc('GEOSGeomType')) geos_typeid = int_from_geom(GEOSFunc('GEOSGeomTypeId')) get_dims = int_from_geom(GEOSFunc('GEOSGeom_getDimensions'), zero=True) get_num_coords = int_from_geom(GEOSFunc('GEOSGetNumCoordinates')) get_num_geoms = int_from_geom(GEOSFunc('GEOSGetNumGeometries')) # Geometry creation factories create_point = geom_output(GEOSFunc('GEOSGeom_createPoint'), [CS_PTR]) create_linestring = geom_output(GEOSFunc('GEOSGeom_createLineString'), [CS_PTR]) create_linearring = geom_output(GEOSFunc('GEOSGeom_createLinearRing'), [CS_PTR]) # Polygon and collection creation routines are special and will not # have their argument types defined. create_polygon = geom_output(GEOSFunc('GEOSGeom_createPolygon'), None) create_collection = geom_output(GEOSFunc('GEOSGeom_createCollection'), None) # Ring routines get_extring = geom_output(GEOSFunc('GEOSGetExteriorRing'), [GEOM_PTR]) get_intring = geom_index(GEOSFunc('GEOSGetInteriorRingN')) get_nrings = int_from_geom(GEOSFunc('GEOSGetNumInteriorRings')) # Collection Routines get_geomn = geom_index(GEOSFunc('GEOSGetGeometryN')) # Cloning geom_clone = GEOSFunc('GEOSGeom_clone') geom_clone.argtypes = [GEOM_PTR] geom_clone.restype = GEOM_PTR # Destruction routine. destroy_geom = GEOSFunc('GEOSGeom_destroy') destroy_geom.argtypes = [GEOM_PTR] destroy_geom.restype = None # SRID routines geos_get_srid = GEOSFunc('GEOSGetSRID') geos_get_srid.argtypes = [GEOM_PTR] geos_get_srid.restype = c_int geos_set_srid = GEOSFunc('GEOSSetSRID') geos_set_srid.argtypes = [GEOM_PTR, c_int] geos_set_srid.restype = None
cwyark/micropython
refs/heads/master
tests/cpydiff/core_function_unpacking.py
21
""" categories: Core,Functions description: Unpacking function arguments in non-last position isn't detected as an error cause: Unknown workaround: The syntax below is invalid, never use it in applications. """ print(*(1, 2), 3)
newvem/pytz
refs/heads/master
pytz/zoneinfo/Pacific/Guam.py
9
'''tzinfo timezone information for Pacific/Guam.''' from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i class Guam(DstTzInfo): '''Pacific/Guam timezone definition. See datetime.tzinfo for details''' zone = 'Pacific/Guam' _utc_transition_times = [ d(1,1,1,0,0,0), d(2000,12,22,14,0,0), ] _transition_info = [ i(36000,0,'GST'), i(36000,0,'ChST'), ] Guam = Guam()
fahhem/mbed-os
refs/heads/master
tools/host_tests/echo_flow_control.py
125
""" mbed SDK Copyright (c) 2011-2013 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from host_test import Test class EchoTest(Test): def __init__(self): Test.__init__(self) self.mbed.init_serial() self.mbed.extra_serial.rtscts = True self.mbed.reset() def test(self): self.mbed.flush() self.notify("Starting the ECHO test") TEST="longer serial test" check = True for i in range(1, 100): self.mbed.extra_serial.write(TEST + "\n") l = self.mbed.extra_serial.readline().strip() if not l: continue if l != TEST: check = False self.notify('"%s" != "%s"' % (l, TEST)) else: if (i % 10) == 0: self.notify('.') return check if __name__ == '__main__': EchoTest().run()
VitalLabs/gcloud-python
refs/heads/master
_testing/grpc/_adapter/_c.py
77
# Copyright 2015 Google 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.
maniackodi2016/repositorio.familiaiptv
refs/heads/master
program.plexus/resources/plexus/plexusutils/utilities.py
33
# -*- coding: utf-8 -*- """ Plexus (c) 2015 enen92 This file contains common utilites Functions: handle_wait(time_to_wait,title,text,segunda='') -> Timer with dialog progress capabilities getDirectorySize(directory) -> returns a directory size recursively recursive_overwrite(src, dest, ignore=None) -> Copy and replace an entire directory recursively """ import xbmc,xbmcplugin,xbmcgui,xbmcaddon,re,os,shutil from pluginxbmc import * def handle_wait(time_to_wait,title,text,segunda=''): ret = mensagemprogresso.create(' '+title) secs=0 percent=0 increment = int(100 / time_to_wait) cancelled = False while secs < time_to_wait: secs = secs + 1 percent = increment*secs secs_left = str((time_to_wait - secs)) if segunda=='': remaining_display = translate(30070) + str(secs_left) + translate(30071) else: remaining_display=segunda mensagemprogresso.update(percent,text,remaining_display) xbmc.sleep(1000) if (mensagemprogresso.iscanceled()): cancelled = True break if cancelled == True: return False else: mensagemprogresso.close() return False def getDirectorySize(directory): dir_size = 0 for (path, dirs, files) in os.walk(directory): for file in files: filename = os.path.join(path, file) dir_size += os.path.getsize(filename) return dir_size def recursive_overwrite(src, dest, ignore=None): if os.path.isdir(src): if not os.path.isdir(dest): os.makedirs(dest) files = os.listdir(src) if ignore is not None: ignored = ignore(src, files) else: ignored = set() for f in files: if f not in ignored: recursive_overwrite(os.path.join(src, f), os.path.join(dest, f), ignore) else: shutil.copyfile(src, dest) return
tarunlnmiit/django-crispy-forms
refs/heads/dev
crispy_forms/__init__.py
18
# -*- coding: utf-8 -*- __version__ = '1.5.1'
johankaito/fufuka
refs/heads/master
microblog/flask/venv/lib/python2.7/site-packages/pip/_vendor/packaging/_compat.py
901
# Copyright 2014 Donald Stufft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function import sys PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 # flake8: noqa if PY3: string_types = str, else: string_types = basestring, 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', (), {})
maxrosan/NS-3-support-for-OBS
refs/heads/master
bindings/python/apidefs/gcc-LP64/ns3_module_ns3wifi.py
132
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers def register_types(module): root_module = module.get_root() ## Register a nested module for the namespace Config nested_module = module.add_cpp_namespace('Config') register_types_ns3_Config(nested_module) ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace addressUtils nested_module = module.add_cpp_namespace('addressUtils') register_types_ns3_addressUtils(nested_module) ## Register a nested module for the namespace aodv nested_module = module.add_cpp_namespace('aodv') register_types_ns3_aodv(nested_module) ## Register a nested module for the namespace dot11s nested_module = module.add_cpp_namespace('dot11s') register_types_ns3_dot11s(nested_module) ## Register a nested module for the namespace dsdv nested_module = module.add_cpp_namespace('dsdv') register_types_ns3_dsdv(nested_module) ## Register a nested module for the namespace flame nested_module = module.add_cpp_namespace('flame') register_types_ns3_flame(nested_module) ## Register a nested module for the namespace internal nested_module = module.add_cpp_namespace('internal') register_types_ns3_internal(nested_module) ## Register a nested module for the namespace olsr nested_module = module.add_cpp_namespace('olsr') register_types_ns3_olsr(nested_module) def register_types_ns3_Config(module): root_module = module.get_root() def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_addressUtils(module): root_module = module.get_root() def register_types_ns3_aodv(module): root_module = module.get_root() def register_types_ns3_dot11s(module): root_module = module.get_root() def register_types_ns3_dsdv(module): root_module = module.get_root() def register_types_ns3_flame(module): root_module = module.get_root() def register_types_ns3_internal(module): root_module = module.get_root() def register_types_ns3_olsr(module): root_module = module.get_root() def register_methods(root_module): return def register_functions(root_module): module = root_module register_functions_ns3_Config(module.get_submodule('Config'), root_module) register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_addressUtils(module.get_submodule('addressUtils'), root_module) register_functions_ns3_aodv(module.get_submodule('aodv'), root_module) register_functions_ns3_dot11s(module.get_submodule('dot11s'), root_module) register_functions_ns3_dsdv(module.get_submodule('dsdv'), root_module) register_functions_ns3_flame(module.get_submodule('flame'), root_module) register_functions_ns3_internal(module.get_submodule('internal'), root_module) register_functions_ns3_olsr(module.get_submodule('olsr'), root_module) return def register_functions_ns3_Config(module, root_module): return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_addressUtils(module, root_module): return def register_functions_ns3_aodv(module, root_module): return def register_functions_ns3_dot11s(module, root_module): return def register_functions_ns3_dsdv(module, root_module): return def register_functions_ns3_flame(module, root_module): return def register_functions_ns3_internal(module, root_module): return def register_functions_ns3_olsr(module, root_module): return
andela-earinde/bellatrix-py
refs/heads/master
app/js/lib/lib/modules/test/test_sha.py
137
# Testing sha module (NIST's Secure Hash Algorithm) # use the three examples from Federal Information Processing Standards # Publication 180-1, Secure Hash Standard, 1995 April 17 # http://www.itl.nist.gov/div897/pubs/fip180-1.htm import warnings warnings.filterwarnings("ignore", "the sha module is deprecated.*", DeprecationWarning) import sha import unittest from test import test_support class SHATestCase(unittest.TestCase): def check(self, data, digest): # Check digest matches the expected value obj = sha.new(data) computed = obj.hexdigest() self.assertTrue(computed == digest) # Verify that the value doesn't change between two consecutive # digest operations. computed_again = obj.hexdigest() self.assertTrue(computed == computed_again) # Check hexdigest() output matches digest()'s output digest = obj.digest() hexd = "" for c in digest: hexd += '%02x' % ord(c) self.assertTrue(computed == hexd) def test_case_1(self): self.check("abc", "a9993e364706816aba3e25717850c26c9cd0d89d") def test_case_2(self): self.check("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "84983e441c3bd26ebaae4aa1f95129e5e54670f1") def test_case_3(self): self.check("a" * 1000000, "34aa973cd4c4daa4f61eeb2bdbad27316534016f") def test_case_4(self): self.check(chr(0xAA) * 80, '4ca0ef38f1794b28a8f8ee110ee79d48ce13be25') def test_main(): test_support.run_unittest(SHATestCase) if __name__ == "__main__": test_main()
tapanpandita/pocket
refs/heads/master
setup.py
1
from setuptools import setup setup( name = "pocket", # pip install pocket description = "api wrapper for getpocket.com", #long_description=open('README.md', 'rt').read(), # version # third part for minor release # second when api changes # first when it becomes stable someday version = "0.3.7", author = 'Tapan Pandita', author_email = "tapan.pandita@gmail.com", url = 'http://github.com/tapanpandita/pocket/', license = 'BSD', # as a practice no need to hard code version unless you know program wont # work unless the specific versions are used install_requires = ["requests", ], py_modules = ["pocket"], zip_safe = True, ) # TODO: Do all this and delete these lines # register: Create an accnt on pypi, store your credentials in ~/.pypirc: # # [pypirc] # servers = # pypi # # [server-login] # username:<username> # password:<pass> # # $ python setup.py register # one time only, will create pypi page for pocket # $ python setup.py sdist --formats=gztar,zip upload # create a new release #
Alberto-Beralix/Beralix
refs/heads/master
i386-squashfs-root/usr/lib/python2.7/dist-packages/PIL/OleFileIO.py
2
../../../../share/pyshared/PIL/OleFileIO.py