repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
ceerik/gitinspector
refs/heads/master
tests/__init__.py
118
# coding: utf-8 # # Copyright © 2013 Ejwa Software. All rights reserved. # # This file is part of gitinspector. # # gitinspector 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. # # gitinspector 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 gitinspector. If not, see <http://www.gnu.org/licenses/>. # This file was intentionally left blank.
ArnossArnossi/django
refs/heads/master
tests/utils_tests/test_html.py
160
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os from datetime import datetime from django.test import SimpleTestCase, ignore_warnings from django.utils import html, safestring, six from django.utils._os import upath from django.utils.deprecation import RemovedInDjango110Warning from django.utils.encoding import force_text class TestUtilsHtml(SimpleTestCase): def check_output(self, function, value, output=None): """ Check that function(value) equals output. If output is None, check that function(value) equals value. """ if output is None: output = value self.assertEqual(function(value), output) def test_escape(self): f = html.escape items = ( ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), ('"', '&quot;'), ("'", '&#39;'), ) # Substitution patterns for testing the above items. patterns = ("%s", "asdf%sfdsa", "%s1", "1%sb") for value, output in items: for pattern in patterns: self.check_output(f, pattern % value, pattern % output) # Check repeated values. self.check_output(f, value * 2, output * 2) # Verify it doesn't double replace &. self.check_output(f, '<&', '&lt;&amp;') def test_format_html(self): self.assertEqual( html.format_html("{} {} {third} {fourth}", "< Dangerous >", html.mark_safe("<b>safe</b>"), third="< dangerous again", fourth=html.mark_safe("<i>safe again</i>") ), "&lt; Dangerous &gt; <b>safe</b> &lt; dangerous again <i>safe again</i>" ) def test_linebreaks(self): f = html.linebreaks items = ( ("para1\n\npara2\r\rpara3", "<p>para1</p>\n\n<p>para2</p>\n\n<p>para3</p>"), ("para1\nsub1\rsub2\n\npara2", "<p>para1<br />sub1<br />sub2</p>\n\n<p>para2</p>"), ("para1\r\n\r\npara2\rsub1\r\rpara4", "<p>para1</p>\n\n<p>para2<br />sub1</p>\n\n<p>para4</p>"), ("para1\tmore\n\npara2", "<p>para1\tmore</p>\n\n<p>para2</p>"), ) for value, output in items: self.check_output(f, value, output) def test_strip_tags(self): f = html.strip_tags items = ( ('<p>See: &#39;&eacute; is an apostrophe followed by e acute</p>', 'See: &#39;&eacute; is an apostrophe followed by e acute'), ('<adf>a', 'a'), ('</adf>a', 'a'), ('<asdf><asdf>e', 'e'), ('hi, <f x', 'hi, <f x'), ('234<235, right?', '234<235, right?'), ('a4<a5 right?', 'a4<a5 right?'), ('b7>b2!', 'b7>b2!'), ('</fe', '</fe'), ('<x>b<y>', 'b'), ('a<p onclick="alert(\'<test>\')">b</p>c', 'abc'), ('a<p a >b</p>c', 'abc'), ('d<a:b c:d>e</p>f', 'def'), ('<strong>foo</strong><a href="http://example.com">bar</a>', 'foobar'), # caused infinite loop on Pythons not patched with # http://bugs.python.org/issue20288 ('&gotcha&#;<>', '&gotcha&#;<>'), ) for value, output in items: self.check_output(f, value, output) # Some convoluted syntax for which parsing may differ between python versions output = html.strip_tags('<sc<!-- -->ript>test<<!-- -->/script>') self.assertNotIn('<script>', output) self.assertIn('test', output) output = html.strip_tags('<script>alert()</script>&h') self.assertNotIn('<script>', output) self.assertIn('alert()', output) # Test with more lengthy content (also catching performance regressions) for filename in ('strip_tags1.html', 'strip_tags2.txt'): path = os.path.join(os.path.dirname(upath(__file__)), 'files', filename) with open(path, 'r') as fp: content = force_text(fp.read()) start = datetime.now() stripped = html.strip_tags(content) elapsed = datetime.now() - start self.assertEqual(elapsed.seconds, 0) self.assertIn("Please try again.", stripped) self.assertNotIn('<', stripped) def test_strip_spaces_between_tags(self): f = html.strip_spaces_between_tags # Strings that should come out untouched. items = (' <adf>', '<adf> ', ' </adf> ', ' <f> x</f>') for value in items: self.check_output(f, value) # Strings that have spaces to strip. items = ( ('<d> </d>', '<d></d>'), ('<p>hello </p>\n<p> world</p>', '<p>hello </p><p> world</p>'), ('\n<p>\t</p>\n<p> </p>\n', '\n<p></p><p></p>\n'), ) for value, output in items: self.check_output(f, value, output) @ignore_warnings(category=RemovedInDjango110Warning) def test_strip_entities(self): f = html.strip_entities # Strings that should come out untouched. values = ("&", "&a", "&a", "a&#a") for value in values: self.check_output(f, value) # Valid entities that should be stripped from the patterns. entities = ("&#1;", "&#12;", "&a;", "&fdasdfasdfasdf;") patterns = ( ("asdf %(entity)s ", "asdf "), ("%(entity)s%(entity)s", ""), ("&%(entity)s%(entity)s", "&"), ("%(entity)s3", "3"), ) for entity in entities: for in_pattern, output in patterns: self.check_output(f, in_pattern % {'entity': entity}, output) def test_escapejs(self): f = html.escapejs items = ( ('"double quotes" and \'single quotes\'', '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027'), (r'\ : backslashes, too', '\\u005C : backslashes, too'), ('and lots of whitespace: \r\n\t\v\f\b', 'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008'), (r'<script>and this</script>', '\\u003Cscript\\u003Eand this\\u003C/script\\u003E'), ('paragraph separator:\u2029and line separator:\u2028', 'paragraph separator:\\u2029and line separator:\\u2028'), ) for value, output in items: self.check_output(f, value, output) @ignore_warnings(category=RemovedInDjango110Warning) def test_remove_tags(self): f = html.remove_tags items = ( ("<b><i>Yes</i></b>", "b i", "Yes"), ("<a>x</a> <p><b>y</b></p>", "a b", "x <p>y</p>"), ) for value, tags, output in items: self.assertEqual(f(value, tags), output) def test_smart_urlquote(self): quote = html.smart_urlquote # Ensure that IDNs are properly quoted self.assertEqual(quote('http://öäü.com/'), 'http://xn--4ca9at.com/') self.assertEqual(quote('http://öäü.com/öäü/'), 'http://xn--4ca9at.com/%C3%B6%C3%A4%C3%BC/') # Ensure that everything unsafe is quoted, !*'();:@&=+$,/?#[]~ is considered safe as per RFC self.assertEqual(quote('http://example.com/path/öäü/'), 'http://example.com/path/%C3%B6%C3%A4%C3%BC/') self.assertEqual(quote('http://example.com/%C3%B6/ä/'), 'http://example.com/%C3%B6/%C3%A4/') self.assertEqual(quote('http://example.com/?x=1&y=2+3&z='), 'http://example.com/?x=1&y=2+3&z=') self.assertEqual(quote('http://example.com/?x=<>"\''), 'http://example.com/?x=%3C%3E%22%27') self.assertEqual(quote('http://example.com/?q=http://example.com/?x=1%26q=django'), 'http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango') self.assertEqual(quote('http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango'), 'http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango') def test_conditional_escape(self): s = '<h1>interop</h1>' self.assertEqual(html.conditional_escape(s), '&lt;h1&gt;interop&lt;/h1&gt;') self.assertEqual(html.conditional_escape(safestring.mark_safe(s)), s) def test_html_safe(self): @html.html_safe class HtmlClass(object): if six.PY2: def __unicode__(self): return "<h1>I'm a html class!</h1>" else: def __str__(self): return "<h1>I'm a html class!</h1>" html_obj = HtmlClass() self.assertTrue(hasattr(HtmlClass, '__html__')) self.assertTrue(hasattr(html_obj, '__html__')) self.assertEqual(force_text(html_obj), html_obj.__html__()) def test_html_safe_subclass(self): if six.PY2: class BaseClass(object): def __html__(self): # defines __html__ on its own return 'some html content' def __unicode__(self): return 'some non html content' @html.html_safe class Subclass(BaseClass): def __unicode__(self): # overrides __unicode__ and is marked as html_safe return 'some html safe content' else: class BaseClass(object): def __html__(self): # defines __html__ on its own return 'some html content' def __str__(self): return 'some non html content' @html.html_safe class Subclass(BaseClass): def __str__(self): # overrides __str__ and is marked as html_safe return 'some html safe content' subclass_obj = Subclass() self.assertEqual(force_text(subclass_obj), subclass_obj.__html__()) def test_html_safe_defines_html_error(self): msg = "can't apply @html_safe to HtmlClass because it defines __html__()." with self.assertRaisesMessage(ValueError, msg): @html.html_safe class HtmlClass(object): def __html__(self): return "<h1>I'm a html class!</h1>" def test_html_safe_doesnt_define_str(self): method_name = '__unicode__()' if six.PY2 else '__str__()' msg = "can't apply @html_safe to HtmlClass because it doesn't define %s." % method_name with self.assertRaisesMessage(ValueError, msg): @html.html_safe class HtmlClass(object): pass
adist/drunken-sansa
refs/heads/master
openerp/pooler.py
61
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## """ Functions kept for backward compatibility. They are simple wrappers around a global RegistryManager methods. """ from openerp.modules.registry import RegistryManager def get_db_and_pool(db_name, force_demo=False, status=None, update_module=False): """Create and return a database connection and a newly initialized registry.""" registry = RegistryManager.get(db_name, force_demo, status, update_module) return registry.db, registry def restart_pool(db_name, force_demo=False, status=None, update_module=False): """Delete an existing registry and return a database connection and a newly initialized registry.""" registry = RegistryManager.new(db_name, force_demo, status, update_module) return registry.db, registry def get_db(db_name): """Return a database connection. The corresponding registry is initialized.""" return get_db_and_pool(db_name)[0] def get_pool(db_name, force_demo=False, status=None, update_module=False): """Return a model registry.""" return get_db_and_pool(db_name, force_demo, status, update_module)[1] # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
stumoodie/VisualLanguageToolkit
refs/heads/master
lib/antlr-3.4/runtime/Python/tests/t058rewriteAST.py
16
import unittest import textwrap import antlr3 import antlr3.tree import testbase import sys class TestRewriteAST(testbase.ANTLRTest): def parserClass(self, base): class TParser(base): def __init__(self, *args, **kwargs): base.__init__(self, *args, **kwargs) self._errors = [] self._output = "" def capture(self, t): self._output += t def traceIn(self, ruleName, ruleIndex): self.traces.append('>'+ruleName) def traceOut(self, ruleName, ruleIndex): self.traces.append('<'+ruleName) def emitErrorMessage(self, msg): self._errors.append(msg) return TParser def lexerClass(self, base): class TLexer(base): def __init__(self, *args, **kwargs): base.__init__(self, *args, **kwargs) self._output = "" def capture(self, t): self._output += t def traceIn(self, ruleName, ruleIndex): self.traces.append('>'+ruleName) def traceOut(self, ruleName, ruleIndex): self.traces.append('<'+ruleName) def recover(self, input, re): # no error recovery yet, just crash! raise return TLexer def execParser(self, grammar, grammarEntry, input, expectErrors=False): lexerCls, parserCls = self.compileInlineGrammar(grammar) cStream = antlr3.StringStream(input) lexer = lexerCls(cStream) tStream = antlr3.CommonTokenStream(lexer) parser = parserCls(tStream) r = getattr(parser, grammarEntry)() if not expectErrors: self.assertEquals(len(parser._errors), 0, parser._errors) result = "" if r is not None: if hasattr(r, 'result'): result += r.result if r.tree is not None: result += r.tree.toStringTree() if not expectErrors: return result else: return result, parser._errors def execTreeParser(self, grammar, grammarEntry, treeGrammar, treeEntry, input): lexerCls, parserCls = self.compileInlineGrammar(grammar) walkerCls = self.compileInlineGrammar(treeGrammar) cStream = antlr3.StringStream(input) lexer = lexerCls(cStream) tStream = antlr3.CommonTokenStream(lexer) parser = parserCls(tStream) r = getattr(parser, grammarEntry)() nodes = antlr3.tree.CommonTreeNodeStream(r.tree) nodes.setTokenStream(tStream) walker = walkerCls(nodes) r = getattr(walker, treeEntry)() if r is not None: return r.tree.toStringTree() return "" def testDelete(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID INT -> ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc 34") self.assertEquals("", found) def testSingleToken(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID -> ID; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc") self.assertEquals("abc", found) def testSingleTokenToNewNode(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID -> ID["x"]; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc") self.assertEquals("x", found) def testSingleTokenToNewNodeRoot(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID -> ^(ID["x"] INT); ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc") self.assertEquals("(x INT)", found) def testSingleTokenToNewNode2(self): # Allow creation of new nodes w/o args. grammar = textwrap.dedent( r''' grammar TT; options {language=Python;output=AST;} a : ID -> ID[ ]; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc") self.assertEquals("ID", found) def testSingleCharLiteral(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : 'c' -> 'c'; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "c") self.assertEquals("c", found) def testSingleStringLiteral(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : 'ick' -> 'ick'; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "ick") self.assertEquals("ick", found) def testSingleRule(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : b -> b; b : ID ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc") self.assertEquals("abc", found) def testReorderTokens(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID INT -> INT ID; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc 34") self.assertEquals("34 abc", found) def testReorderTokenAndRule(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : b INT -> INT b; b : ID ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc 34") self.assertEquals("34 abc", found) def testTokenTree(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID INT -> ^(INT ID); ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc 34") self.assertEquals("(34 abc)", found) def testTokenTreeAfterOtherStuff(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : 'void' ID INT -> 'void' ^(INT ID); ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "void abc 34") self.assertEquals("void (34 abc)", found) def testNestedTokenTreeWithOuterLoop(self): # verify that ID and INT both iterate over outer index variable grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {DUH;} a : ID INT ID INT -> ^( DUH ID ^( DUH INT) )+ ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a 1 b 2") self.assertEquals("(DUH a (DUH 1)) (DUH b (DUH 2))", found) def testOptionalSingleToken(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID -> ID? ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc") self.assertEquals("abc", found) def testClosureSingleToken(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID ID -> ID* ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a b") self.assertEquals("a b", found) def testPositiveClosureSingleToken(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID ID -> ID+ ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a b") self.assertEquals("a b", found) def testOptionalSingleRule(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : b -> b?; b : ID ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc") self.assertEquals("abc", found) def testClosureSingleRule(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : b b -> b*; b : ID ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a b") self.assertEquals("a b", found) def testClosureOfLabel(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : x+=b x+=b -> $x*; b : ID ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a b") self.assertEquals("a b", found) def testOptionalLabelNoListLabel(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : (x=ID)? -> $x?; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a") self.assertEquals("a", found) def testPositiveClosureSingleRule(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : b b -> b+; b : ID ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a b") self.assertEquals("a b", found) def testSinglePredicateT(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID -> {True}? ID -> ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc") self.assertEquals("abc", found) def testSinglePredicateF(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID -> {False}? ID -> ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc") self.assertEquals("", found) def testMultiplePredicate(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID INT -> {False}? ID -> {True}? INT -> ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a 2") self.assertEquals("2", found) def testMultiplePredicateTrees(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID INT -> {False}? ^(ID INT) -> {True}? ^(INT ID) -> ID ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a 2") self.assertEquals("(2 a)", found) def testSimpleTree(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : op INT -> ^(op INT); op : '+'|'-' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "-34") self.assertEquals("(- 34)", found) def testSimpleTree2(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : op INT -> ^(INT op); op : '+'|'-' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "+ 34") self.assertEquals("(34 +)", found) def testNestedTrees(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : 'var' (ID ':' type ';')+ -> ^('var' ^(':' ID type)+) ; type : 'int' | 'float' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "var a:int; b:float;") self.assertEquals("(var (: a int) (: b float))", found) def testImaginaryTokenCopy(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {VAR;} a : ID (',' ID)*-> ^(VAR ID)+ ; type : 'int' | 'float' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a,b,c") self.assertEquals("(VAR a) (VAR b) (VAR c)", found) def testTokenUnreferencedOnLeftButDefined(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {VAR;} a : b -> ID ; b : ID ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a") self.assertEquals("ID", found) def testImaginaryTokenCopySetText(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {VAR;} a : ID (',' ID)*-> ^(VAR["var"] ID)+ ; type : 'int' | 'float' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a,b,c") self.assertEquals("(var a) (var b) (var c)", found) def testImaginaryTokenNoCopyFromToken(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : lc='{' ID+ '}' -> ^(BLOCK[$lc] ID+) ; type : 'int' | 'float' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "{a b c}") self.assertEquals("({ a b c)", found) def testImaginaryTokenNoCopyFromTokenSetText(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : lc='{' ID+ '}' -> ^(BLOCK[$lc,"block"] ID+) ; type : 'int' | 'float' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "{a b c}") self.assertEquals("(block a b c)", found) def testMixedRewriteAndAutoAST(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : b b^ ; // 2nd b matches only an INT; can make it root b : ID INT -> INT ID | INT ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a 1 2") self.assertEquals("(2 1 a)", found) def testSubruleWithRewrite(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : b b ; b : (ID INT -> INT ID | INT INT -> INT+ ) ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a 1 2 3") self.assertEquals("1 a 2 3", found) def testSubruleWithRewrite2(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {TYPE;} a : b b ; b : 'int' ( ID -> ^(TYPE 'int' ID) | ID '=' INT -> ^(TYPE 'int' ID INT) ) ';' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "int a; int b=3;") self.assertEquals("(TYPE int a) (TYPE int b 3)", found) def testNestedRewriteShutsOffAutoAST(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : b b ; b : ID ( ID (last=ID -> $last)+ ) ';' // get last ID | INT // should still get auto AST construction ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a b c d; 42") self.assertEquals("d 42", found) def testRewriteActions(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : atom -> ^({self.adaptor.create(INT,"9")} atom) ; atom : INT ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "3") self.assertEquals("(9 3)", found) def testRewriteActions2(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : atom -> {self.adaptor.create(INT,"9")} atom ; atom : INT ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "3") self.assertEquals("9 3", found) def testRefToOldValue(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : (atom -> atom) (op='+' r=atom -> ^($op $a $r) )* ; atom : INT ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "3+4+5") self.assertEquals("(+ (+ 3 4) 5)", found) def testCopySemanticsForRules(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : atom -> ^(atom atom) ; // NOT CYCLE! (dup atom) atom : INT ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "3") self.assertEquals("(3 3)", found) def testCopySemanticsForRules2(self): # copy type as a root for each invocation of (...)+ in rewrite grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : type ID (',' ID)* ';' -> ^(type ID)+ ; type : 'int' ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "int a,b,c;") self.assertEquals("(int a) (int b) (int c)", found) def testCopySemanticsForRules3(self): # copy type *and* modifier even though it's optional # for each invocation of (...)+ in rewrite grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : modifier? type ID (',' ID)* ';' -> ^(type modifier? ID)+ ; type : 'int' ; modifier : 'public' ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "public int a,b,c;") self.assertEquals("(int public a) (int public b) (int public c)", found) def testCopySemanticsForRules3Double(self): # copy type *and* modifier even though it's optional # for each invocation of (...)+ in rewrite grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : modifier? type ID (',' ID)* ';' -> ^(type modifier? ID)+ ^(type modifier? ID)+ ; type : 'int' ; modifier : 'public' ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "public int a,b,c;") self.assertEquals("(int public a) (int public b) (int public c) (int public a) (int public b) (int public c)", found) def testCopySemanticsForRules4(self): # copy type *and* modifier even though it's optional # for each invocation of (...)+ in rewrite grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {MOD;} a : modifier? type ID (',' ID)* ';' -> ^(type ^(MOD modifier)? ID)+ ; type : 'int' ; modifier : 'public' ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "public int a,b,c;") self.assertEquals("(int (MOD public) a) (int (MOD public) b) (int (MOD public) c)", found) def testCopySemanticsLists(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {MOD;} a : ID (',' ID)* ';' -> ID+ ID+ ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a,b,c;") self.assertEquals("a b c a b c", found) def testCopyRuleLabel(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : x=b -> $x $x; b : ID ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a") self.assertEquals("a a", found) def testCopyRuleLabel2(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : x=b -> ^($x $x); b : ID ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a") self.assertEquals("(a a)", found) def testQueueingOfTokens(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : 'int' ID (',' ID)* ';' -> ^('int' ID+) ; op : '+'|'-' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "int a,b,c;") self.assertEquals("(int a b c)", found) def testCopyOfTokens(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : 'int' ID ';' -> 'int' ID 'int' ID ; op : '+'|'-' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "int a;") self.assertEquals("int a int a", found) def testTokenCopyInLoop(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : 'int' ID (',' ID)* ';' -> ^('int' ID)+ ; op : '+'|'-' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "int a,b,c;") self.assertEquals("(int a) (int b) (int c)", found) def testTokenCopyInLoopAgainstTwoOthers(self): # must smear 'int' copies across as root of multiple trees grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : 'int' ID ':' INT (',' ID ':' INT)* ';' -> ^('int' ID INT)+ ; op : '+'|'-' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "int a:1,b:2,c:3;") self.assertEquals("(int a 1) (int b 2) (int c 3)", found) def testListRefdOneAtATime(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID+ -> ID ID ID ; // works if 3 input IDs op : '+'|'-' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a b c") self.assertEquals("a b c", found) def testSplitListWithLabels(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {VAR;} a : first=ID others+=ID* -> $first VAR $others+ ; op : '+'|'-' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a b c") self.assertEquals("a VAR b c", found) def testComplicatedMelange(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : A A b=B B b=B c+=C C c+=C D {s=$D.text} -> A+ B+ C+ D ; type : 'int' | 'float' ; A : 'a' ; B : 'b' ; C : 'c' ; D : 'd' ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a a b b b c c c d") self.assertEquals("a a b b b c c c d", found) def testRuleLabel(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : x=b -> $x; b : ID ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a") self.assertEquals("a", found) def testAmbiguousRule(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID a -> a | INT ; ID : 'a'..'z'+ ; INT: '0'..'9'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc 34") self.assertEquals("34", found) def testRuleListLabel(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : x+=b x+=b -> $x+; b : ID ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a b") self.assertEquals("a b", found) def testRuleListLabel2(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : x+=b x+=b -> $x $x*; b : ID ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a b") self.assertEquals("a b", found) def testOptional(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : x=b (y=b)? -> $x $y?; b : ID ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a") self.assertEquals("a", found) def testOptional2(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : x=ID (y=b)? -> $x $y?; b : ID ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a b") self.assertEquals("a b", found) def testOptional3(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : x=ID (y=b)? -> ($x $y)?; b : ID ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a b") self.assertEquals("a b", found) def testOptional4(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : x+=ID (y=b)? -> ($x $y)?; b : ID ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a b") self.assertEquals("a b", found) def testOptional5(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : ID -> ID? ; // match an ID to optional ID b : ID ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a") self.assertEquals("a", found) def testArbitraryExprType(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : x+=b x+=b -> {CommonTree(None)}; b : ID ; ID : 'a'..'z'+ ; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "a b") self.assertEquals("", found) def testSet(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a: (INT|ID)+ -> INT+ ID+ ; INT: '0'..'9'+; ID : 'a'..'z'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "2 a 34 de") self.assertEquals("2 34 a de", found) def testSet2(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a: (INT|ID) -> INT? ID? ; INT: '0'..'9'+; ID : 'a'..'z'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "2") self.assertEquals("2", found) @testbase.broken("http://www.antlr.org:8888/browse/ANTLR-162", antlr3.tree.RewriteEmptyStreamException) def testSetWithLabel(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : x=(INT|ID) -> $x ; INT: '0'..'9'+; ID : 'a'..'z'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "2") self.assertEquals("2", found) def testRewriteAction(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens { FLOAT; } r : INT -> {CommonTree(CommonToken(type=FLOAT, text=$INT.text+".0"))} ; INT : '0'..'9'+; WS: (' ' | '\n' | '\t')+ {$channel = HIDDEN;}; ''') found = self.execParser(grammar, "r", "25") self.assertEquals("25.0", found) def testOptionalSubruleWithoutRealElements(self): # copy type *and* modifier even though it's optional # for each invocation of (...)+ in rewrite grammar = textwrap.dedent( r""" grammar T; options {language=Python;output=AST;} tokens {PARMS;} modulo : 'modulo' ID ('(' parms+ ')')? -> ^('modulo' ID ^(PARMS parms+)?) ; parms : '#'|ID; ID : ('a'..'z' | 'A'..'Z')+; WS : (' '|'\n') {$channel=HIDDEN;} ; """) found = self.execParser(grammar, "modulo", "modulo abc (x y #)") self.assertEquals("(modulo abc (PARMS x y #))", found) ## C A R D I N A L I T Y I S S U E S def testCardinality(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} tokens {BLOCK;} a : ID ID INT INT INT -> (ID INT)+; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') try: self.execParser(grammar, "a", "a b 3 4 5") self.fail() except antlr3.tree.RewriteCardinalityException: pass def testCardinality2(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID+ -> ID ID ID ; // only 2 input IDs op : '+'|'-' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') try: self.execParser(grammar, "a", "a b") self.fail() except antlr3.tree.RewriteCardinalityException: pass def testCardinality3(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID? INT -> ID INT ; op : '+'|'-' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') try: self.execParser(grammar, "a", "3") self.fail() except antlr3.tree.RewriteEmptyStreamException: pass def testLoopCardinality(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID? INT -> ID+ INT ; op : '+'|'-' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') try: self.execParser(grammar, "a", "3") self.fail() except antlr3.tree.RewriteEarlyExitException: pass def testWildcard(self): grammar = textwrap.dedent( r''' grammar T; options {language=Python;output=AST;} a : ID c=. -> $c; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found = self.execParser(grammar, "a", "abc 34") self.assertEquals("34", found) # E R R O R S def testExtraTokenInSimpleDecl(self): grammar = textwrap.dedent( r''' grammar foo; options {language=Python;output=AST;} tokens {EXPR;} decl : type ID '=' INT ';' -> ^(EXPR type ID INT) ; type : 'int' | 'float' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found, errors = self.execParser(grammar, "decl", "int 34 x=1;", expectErrors=True) self.assertEquals(["line 1:4 extraneous input u'34' expecting ID"], errors) self.assertEquals("(EXPR int x 1)", found) # tree gets correct x and 1 tokens #@testbase.broken("FIXME", AssertionError) def testMissingIDInSimpleDecl(self): grammar = textwrap.dedent( r''' grammar foo; options {language=Python;output=AST;} tokens {EXPR;} decl : type ID '=' INT ';' -> ^(EXPR type ID INT) ; type : 'int' | 'float' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found, errors = self.execParser(grammar, "decl", "int =1;", expectErrors=True) self.assertEquals(["line 1:4 missing ID at u'='"], errors) self.assertEquals("(EXPR int <missing ID> 1)", found) # tree gets invented ID token def testMissingSetInSimpleDecl(self): grammar = textwrap.dedent( r''' grammar foo; options {language=Python;output=AST;} tokens {EXPR;} decl : type ID '=' INT ';' -> ^(EXPR type ID INT) ; type : 'int' | 'float' ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found, errors = self.execParser(grammar, "decl", "x=1;", expectErrors=True) self.assertEquals(["line 1:0 mismatched input u'x' expecting set None"], errors); self.assertEquals("(EXPR <error: x> x 1)", found) # tree gets invented ID token def testMissingTokenGivesErrorNode(self): grammar = textwrap.dedent( r''' grammar foo; options {language=Python;output=AST;} a : ID INT -> ID INT ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found, errors = self.execParser(grammar, "a", "abc", expectErrors=True) self.assertEquals(["line 1:3 missing INT at '<EOF>'"], errors) # doesn't do in-line recovery for sets (yet?) self.assertEquals("abc <missing INT>", found) def testExtraTokenGivesErrorNode(self): grammar = textwrap.dedent( r''' grammar foo; options {language=Python;output=AST;} a : b c -> b c; b : ID -> ID ; c : INT -> INT ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found, errors = self.execParser(grammar, "a", "abc ick 34", expectErrors=True) self.assertEquals(["line 1:4 extraneous input u'ick' expecting INT"], errors) self.assertEquals("abc 34", found) #@testbase.broken("FIXME", AssertionError) def testMissingFirstTokenGivesErrorNode(self): grammar = textwrap.dedent( r''' grammar foo; options {language=Python;output=AST;} a : ID INT -> ID INT ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found, errors = self.execParser(grammar, "a", "34", expectErrors=True) self.assertEquals(["line 1:0 missing ID at u'34'"], errors) self.assertEquals("<missing ID> 34", found) #@testbase.broken("FIXME", AssertionError) def testMissingFirstTokenGivesErrorNode2(self): grammar = textwrap.dedent( r''' grammar foo; options {language=Python;output=AST;} a : b c -> b c; b : ID -> ID ; c : INT -> INT ; ID : 'a'..'z'+ ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found, errors = self.execParser(grammar, "a", "34", expectErrors=True) # finds an error at the first token, 34, and re-syncs. # re-synchronizing does not consume a token because 34 follows # ref to rule b (start of c). It then matches 34 in c. self.assertEquals(["line 1:0 missing ID at u'34'"], errors) self.assertEquals("<missing ID> 34", found) def testNoViableAltGivesErrorNode(self): grammar = textwrap.dedent( r''' grammar foo; options {language=Python;output=AST;} a : b -> b | c -> c; b : ID -> ID ; c : INT -> INT ; ID : 'a'..'z'+ ; S : '*' ; INT : '0'..'9'+; WS : (' '|'\n') {$channel=HIDDEN;} ; ''') found, errors = self.execParser(grammar, "a", "*", expectErrors=True) # finds an error at the first token, 34, and re-syncs. # re-synchronizing does not consume a token because 34 follows # ref to rule b (start of c). It then matches 34 in c. self.assertEquals(["line 1:0 no viable alternative at input u'*'"], errors); self.assertEquals("<unexpected: [@0,0:0=u'*',<6>,1:0], resync=*>", found) if __name__ == '__main__': unittest.main()
valexandersaulys/airbnb_kaggle_contest
refs/heads/master
venv/lib/python3.4/site-packages/pip/_vendor/distlib/_backport/__init__.py
1429
"""Modules copied from Python 3 standard libraries, for internal use only. Individual classes and functions are found in d2._backport.misc. Intended usage is to always import things missing from 3.1 from that module: the built-in/stdlib objects will be used if found. """
Ninjakow/TrueSkill
refs/heads/master
lib/flask/wrappers.py
121
# -*- coding: utf-8 -*- """ flask.wrappers ~~~~~~~~~~~~~~ Implements the WSGI wrappers (request and response). :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase from werkzeug.exceptions import BadRequest from . import json from .globals import _request_ctx_stack _missing = object() def _get_data(req, cache): getter = getattr(req, 'get_data', None) if getter is not None: return getter(cache=cache) return req.data class Request(RequestBase): """The request object used by default in Flask. Remembers the matched endpoint and view arguments. It is what ends up as :class:`~flask.request`. If you want to replace the request object used you can subclass this and set :attr:`~flask.Flask.request_class` to your subclass. The request object is a :class:`~werkzeug.wrappers.Request` subclass and provides all of the attributes Werkzeug defines plus a few Flask specific ones. """ #: The internal URL rule that matched the request. This can be #: useful to inspect which methods are allowed for the URL from #: a before/after handler (``request.url_rule.methods``) etc. #: #: .. versionadded:: 0.6 url_rule = None #: A dict of view arguments that matched the request. If an exception #: happened when matching, this will be ``None``. view_args = None #: If matching the URL failed, this is the exception that will be #: raised / was raised as part of the request handling. This is #: usually a :exc:`~werkzeug.exceptions.NotFound` exception or #: something similar. routing_exception = None # Switched by the request context until 1.0 to opt in deprecated # module functionality. _is_old_module = False @property def max_content_length(self): """Read-only view of the ``MAX_CONTENT_LENGTH`` config key.""" ctx = _request_ctx_stack.top if ctx is not None: return ctx.app.config['MAX_CONTENT_LENGTH'] @property def endpoint(self): """The endpoint that matched the request. This in combination with :attr:`view_args` can be used to reconstruct the same or a modified URL. If an exception happened when matching, this will be ``None``. """ if self.url_rule is not None: return self.url_rule.endpoint @property def module(self): """The name of the current module if the request was dispatched to an actual module. This is deprecated functionality, use blueprints instead. """ from warnings import warn warn(DeprecationWarning('modules were deprecated in favor of ' 'blueprints. Use request.blueprint ' 'instead.'), stacklevel=2) if self._is_old_module: return self.blueprint @property def blueprint(self): """The name of the current blueprint""" if self.url_rule and '.' in self.url_rule.endpoint: return self.url_rule.endpoint.rsplit('.', 1)[0] @property def json(self): """If the mimetype is :mimetype:`application/json` this will contain the parsed JSON data. Otherwise this will be ``None``. The :meth:`get_json` method should be used instead. """ from warnings import warn warn(DeprecationWarning('json is deprecated. ' 'Use get_json() instead.'), stacklevel=2) return self.get_json() @property def is_json(self): """Indicates if this request is JSON or not. By default a request is considered to include JSON data if the mimetype is :mimetype:`application/json` or :mimetype:`application/*+json`. .. versionadded:: 0.11 """ mt = self.mimetype if mt == 'application/json': return True if mt.startswith('application/') and mt.endswith('+json'): return True return False def get_json(self, force=False, silent=False, cache=True): """Parses the incoming JSON request data and returns it. By default this function will return ``None`` if the mimetype is not :mimetype:`application/json` but this can be overridden by the ``force`` parameter. If parsing fails the :meth:`on_json_loading_failed` method on the request object will be invoked. :param force: if set to ``True`` the mimetype is ignored. :param silent: if set to ``True`` this method will fail silently and return ``None``. :param cache: if set to ``True`` the parsed JSON data is remembered on the request. """ rv = getattr(self, '_cached_json', _missing) # We return cached JSON only when the cache is enabled. if cache and rv is not _missing: return rv if not (force or self.is_json): return None # We accept a request charset against the specification as # certain clients have been using this in the past. This # fits our general approach of being nice in what we accept # and strict in what we send out. request_charset = self.mimetype_params.get('charset') try: data = _get_data(self, cache) if request_charset is not None: rv = json.loads(data, encoding=request_charset) else: rv = json.loads(data) except ValueError as e: if silent: rv = None else: rv = self.on_json_loading_failed(e) if cache: self._cached_json = rv return rv def on_json_loading_failed(self, e): """Called if decoding of the JSON data failed. The return value of this method is used by :meth:`get_json` when an error occurred. The default implementation just raises a :class:`BadRequest` exception. .. versionchanged:: 0.10 Removed buggy previous behavior of generating a random JSON response. If you want that behavior back you can trivially add it by subclassing. .. versionadded:: 0.8 """ ctx = _request_ctx_stack.top if ctx is not None and ctx.app.config.get('DEBUG', False): raise BadRequest('Failed to decode JSON object: {0}'.format(e)) raise BadRequest() def _load_form_data(self): RequestBase._load_form_data(self) # In debug mode we're replacing the files multidict with an ad-hoc # subclass that raises a different error for key errors. ctx = _request_ctx_stack.top if ctx is not None and ctx.app.debug and \ self.mimetype != 'multipart/form-data' and not self.files: from .debughelpers import attach_enctype_error_multidict attach_enctype_error_multidict(self) class Response(ResponseBase): """The response object that is used by default in Flask. Works like the response object from Werkzeug but is set to have an HTML mimetype by default. Quite often you don't have to create this object yourself because :meth:`~flask.Flask.make_response` will take care of that for you. If you want to replace the response object used you can subclass this and set :attr:`~flask.Flask.response_class` to your subclass. """ default_mimetype = 'text/html'
mdj2/django
refs/heads/master
tests/commands_sql/tests.py
58
from __future__ import unicode_literals from django.core.management.color import no_style from django.core.management.sql import (sql_create, sql_delete, sql_indexes, sql_destroy_indexes, sql_all) from django.db import connections, DEFAULT_DB_ALIAS, models from django.test import TestCase from django.utils import six # See also initial_sql_regress for 'custom_sql_for_model' tests class SQLCommandsTestCase(TestCase): """Tests for several functions in django/core/management/sql.py""" def count_ddl(self, output, cmd): return len([o for o in output if o.startswith(cmd)]) def test_sql_create(self): app = models.get_app('commands_sql') output = sql_create(app, no_style(), connections[DEFAULT_DB_ALIAS]) create_tables = [o for o in output if o.startswith('CREATE TABLE')] self.assertEqual(len(create_tables), 3) # Lower so that Oracle's upper case tbl names wont break sql = create_tables[-1].lower() six.assertRegex(self, sql, r'^create table .commands_sql_book.*') def test_sql_delete(self): app = models.get_app('commands_sql') output = sql_delete(app, no_style(), connections[DEFAULT_DB_ALIAS]) drop_tables = [o for o in output if o.startswith('DROP TABLE')] self.assertEqual(len(drop_tables), 3) # Lower so that Oracle's upper case tbl names wont break sql = drop_tables[-1].lower() six.assertRegex(self, sql, r'^drop table .commands_sql_comment.*') def test_sql_indexes(self): app = models.get_app('commands_sql') output = sql_indexes(app, no_style(), connections[DEFAULT_DB_ALIAS]) # PostgreSQL creates one additional index for CharField self.assertIn(self.count_ddl(output, 'CREATE INDEX'), [3, 4]) def test_sql_destroy_indexes(self): app = models.get_app('commands_sql') output = sql_destroy_indexes(app, no_style(), connections[DEFAULT_DB_ALIAS]) # PostgreSQL creates one additional index for CharField self.assertIn(self.count_ddl(output, 'DROP INDEX'), [3, 4]) def test_sql_all(self): app = models.get_app('commands_sql') output = sql_all(app, no_style(), connections[DEFAULT_DB_ALIAS]) self.assertEqual(self.count_ddl(output, 'CREATE TABLE'), 3) # PostgreSQL creates one additional index for CharField self.assertIn(self.count_ddl(output, 'CREATE INDEX'), [3, 4])
HDPxbmc/plugin.video.115
refs/heads/master
bencode.py
1
# The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software distributed under the License is distributed on an AS IS basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # Written by Petru Paler class BTFailure(Exception): pass def decode_int(x, f): f += 1 newf = x.index('e', f) n = int(x[f:newf]) if x[f] == '-': if x[f + 1] == '0': raise ValueError elif x[f] == '0' and newf != f+1: raise ValueError return (n, newf+1) def decode_string(x, f): colon = x.index(':', f) n = int(x[f:colon]) if x[f] == '0' and colon != f+1: raise ValueError colon += 1 return (x[colon:colon+n], colon+n) def decode_list(x, f): r, f = [], f+1 while x[f] != 'e': v, f = decode_func[x[f]](x, f) r.append(v) return (r, f + 1) def decode_dict(x, f): r, f = {}, f+1 while x[f] != 'e': k, f = decode_string(x, f) r[k], f = decode_func[x[f]](x, f) return (r, f + 1) decode_func = {} decode_func['l'] = decode_list decode_func['d'] = decode_dict decode_func['i'] = decode_int decode_func['0'] = decode_string decode_func['1'] = decode_string decode_func['2'] = decode_string decode_func['3'] = decode_string decode_func['4'] = decode_string decode_func['5'] = decode_string decode_func['6'] = decode_string decode_func['7'] = decode_string decode_func['8'] = decode_string decode_func['9'] = decode_string def bdecode(x): try: r, l = decode_func[x[0]](x, 0) except (IndexError, KeyError, ValueError): raise BTFailure("not a valid bencoded string") if l != len(x): pass #raise BTFailure("invalid bencoded value (data after valid prefix)") return r from types import StringType, IntType, LongType, DictType, ListType, TupleType class Bencached(object): __slots__ = ['bencoded'] def __init__(self, s): self.bencoded = s def encode_bencached(x,r): r.append(x.bencoded) def encode_int(x, r): r.extend(('i', str(x), 'e')) def encode_bool(x, r): if x: encode_int(1, r) else: encode_int(0, r) def encode_string(x, r): r.extend((str(len(x)), ':', x)) def encode_list(x, r): r.append('l') for i in x: encode_func[type(i)](i, r) r.append('e') def encode_dict(x,r): r.append('d') ilist = x.items() ilist.sort() for k, v in ilist: r.extend((str(len(k)), ':', k)) encode_func[type(v)](v, r) r.append('e') encode_func = {} encode_func[Bencached] = encode_bencached encode_func[IntType] = encode_int encode_func[LongType] = encode_int encode_func[StringType] = encode_string encode_func[ListType] = encode_list encode_func[TupleType] = encode_list encode_func[DictType] = encode_dict try: from types import BooleanType encode_func[BooleanType] = encode_bool except ImportError: pass def bencode(x): r = [] encode_func[type(x)](x, r) return ''.join(r)
rkotulla/python_module_packer
refs/heads/master
pypack.py
1
#!/usr/bin/env python import os, sys import types import modulefinder import optparse if __name__ == "__main__": parser = optparse.OptionParser() parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="print additional output to stdout") parser.add_option("-x", "--verbose2", action="store_true", dest="verbose2", default=False, help="print additional output to stdout") parser.add_option("-d", "--dry", action="store_true", dest="dryrun", default=False, help="dry run, do not tar any files") (options, args) = parser.parse_args() #print options #print type(options) #print args tar_output_file = args[0] master_modules = [] master_modules_dict = {} # # Now study all scripts and assemble a list of master modules # for scriptfile in args[1:]: # Start the code you want to study print("Assembling dependencies for %s" % (scriptfile)) mf = modulefinder.ModuleFinder() mf.run_script(scriptfile) master_modules_dict.update(mf.modules) modules = [] for mod in mf.modules: modules.append(mod) mod_parts = mod.split(".") master_modules.append(mod_parts[0]) #print type(mf.modules) #print modules #print type(modules) #modules.sort() #print "\n".join(modules) master_modules = list(set(master_modules)) master_modules.sort() if (options.verbose): print "\n------------------------------------\n" print "Collecting necessary files for the following modules:" print " -- ","\n -- ".join(master_modules) # # Now create a tar-file with all files we might need # import tarfile, glob def strip_path(tarinfo): #print tarinfo # Set username to something else (most likely was 'root/root' before) tarinfo.uname = tarinfo.gname = 'everyone' # Now change the name = filename to not include the directory name _, bn = os.path.split(tarinfo.name) tarinfo.name = bn #"test/"+tarinfo.name return tarinfo master_dir = '/usr/lib' def strip_master_dir(tarinfo): if (tarinfo.islnk()): #print "Removing hard link from filelist" #print "HARDLINK:", tarinfo.type, tarinfo.linkname tarinfo.type = tarfile.REGTYPE if (tarinfo.name.startswith(master_dir)): tarinfo.name = tarinfo.name[len(master_dir):] tarinfo.uname = tarinfo.gname = 'everyone' #print master_dir, "---", tarinfo.name, len(master_dir) return tarinfo tar = tarfile.open(tar_output_file, "w:gz") add_files = True if (add_files): print "Adding files to tar file" # Now add all files we might need for each of the modules for module_name in master_modules: #import_cmd = "import %s as module" % (module_name) #exec(import_cmd) # module = mf.modules[module_name] module = master_modules_dict[module_name] try: _path = module.__path__ except: _path = None try: _file = module.__file__ except: _file = None #print module.__name__, _path, _file if (_path == None and _file != None): # We have only a file locator, so this is likely a single-file module if (options.verbose2): print "%30s: %s" % (module_name, _file) if (not options.dryrun): tar.add(_file, filter=strip_path) elif (_path != None): # We have a full path # Go through the directory recursively, and add all files realpath = os.path.realpath(_path[0]) master_dir, bn = os.path.split(realpath) if (master_dir.startswith("/")): master_dir = master_dir[1:] if (not master_dir.endswith("/")): master_dir += "/" if (options.verbose2): print "%30s: %s (%s)" % (module_name, _path, master_dir) for root, subdirs, files in os.walk(_path[0]): # for subdir in subdirs: # print('\t- subdirectory ' + subdir) #print('--\nroot = ' + root) #list_file_path = os.path.join(root, 'my-directory-list.txt') #print('list_file_path = ' + list_file_path) for filename in files: file_path = os.path.join(root, filename) real_path = os.path.realpath(file_path) #print file_path, file_path[len(master_dir):] if (not options.dryrun): tar.add(real_path, filter=strip_master_dir) #tar.add("foo", filter=reset) tar.close()
jiwanlimbu/aura
refs/heads/master
controllers.py
1
#Copyright 2013 Metacloud, Inc. # Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Workflow Logic the Assignment service.""" import functools import uuid from oslo_log import log from six.moves import urllib from keystone.assignment import schema from keystone.common import controller from keystone.common import dependency from keystone.common import utils from keystone.common import validation from keystone.common import wsgi import keystone.conf from keystone import exception from keystone.i18n import _ CONF = keystone.conf.CONF LOG = log.getLogger(__name__) @dependency.requires('assignment_api', 'identity_api', 'token_provider_api') class TenantAssignment(controller.V2Controller): """The V2 Project APIs that are processing assignments.""" @controller.v2_auth_deprecated def get_projects_for_token(self, request, **kw): """Get valid tenants for token based on token used to authenticate. Pulls the token from the context, validates it and gets the valid tenants for the user in the token. Doesn't care about token scopedness. """ token_ref = utils.get_token_ref(request.context_dict) tenant_refs = ( self.assignment_api.list_projects_for_user(token_ref.user_id)) tenant_refs = [self.v3_to_v2_project(ref) for ref in tenant_refs if ref['domain_id'] == CONF.identity.default_domain_id] params = { 'limit': request.params.get('limit'), 'marker': request.params.get('marker'), } return self.format_project_list(tenant_refs, **params) @controller.v2_deprecated def get_project_users(self, request, tenant_id, **kw): self.assert_admin(request) user_refs = [] user_ids = self.assignment_api.list_user_ids_for_project(tenant_id) for user_id in user_ids: try: user_ref = self.identity_api.get_user(user_id) except exception.UserNotFound: # Log that user is missing and continue on. message = ("User %(user_id)s in project %(project_id)s " "doesn't exist.") LOG.debug(message, {'user_id': user_id, 'project_id': tenant_id}) else: user_refs.append(self.v3_to_v2_user(user_ref)) return {'users': user_refs} @dependency.requires('assignment_api', 'role_api') class Role(controller.V2Controller): """The Role management APIs.""" @controller.v2_deprecated def get_role(self, request, role_id): self.assert_admin(request) return {'role': self.role_api.get_role(role_id)} @controller.v2_deprecated def create_role(self, request, role): validation.lazy_validate(schema.role_create_v2, role) role = self._normalize_dict(role) self.assert_admin(request) if role['name'] == CONF.member_role_name: # Use the configured member role ID when creating the configured # member role name. This avoids the potential of creating a # "member" role with an unexpected ID. role_id = CONF.member_role_id else: role_id = uuid.uuid4().hex role['id'] = role_id role_ref = self.role_api.create_role(role_id, role, initiator=request.audit_initiator) return {'role': role_ref} @controller.v2_deprecated def delete_role(self, request, role_id): self.assert_admin(request) self.role_api.delete_role(role_id, initiator=request.audit_initiator) @controller.v2_deprecated def get_roles(self, request): self.assert_admin(request) return {'roles': self.role_api.list_roles()} @dependency.requires('assignment_api', 'resource_api', 'role_api') class RoleAssignmentV2(controller.V2Controller): """The V2 Role APIs that are processing assignments.""" # COMPAT(essex-3) @controller.v2_deprecated def get_user_roles(self, request, user_id, tenant_id=None): """Get the roles for a user and tenant pair. Since we're trying to ignore the idea of user-only roles we're not implementing them in hopes that the idea will die off. """ self.assert_admin(request) # NOTE(davechen): Router without project id is defined, # but we don't plan on implementing this. if tenant_id is None: raise exception.NotImplemented( message=_('User roles not supported: tenant_id required')) roles = self.assignment_api.get_roles_for_user_and_project( user_id, tenant_id) return {'roles': [self.role_api.get_role(x) for x in roles]} @controller.v2_deprecated def add_role_to_user(self, request, user_id, role_id, tenant_id=None): """Add a role to a user and tenant pair. Since we're trying to ignore the idea of user-only roles we're not implementing them in hopes that the idea will die off. """ self.assert_admin(request) if tenant_id is None: raise exception.NotImplemented( message=_('User roles not supported: tenant_id required')) self.assignment_api.add_role_to_user_and_project( user_id, tenant_id, role_id) role_ref = self.role_api.get_role(role_id) return {'role': role_ref} @controller.v2_deprecated def remove_role_from_user(self, request, user_id, role_id, tenant_id=None): """Remove a role from a user and tenant pair. Since we're trying to ignore the idea of user-only roles we're not implementing them in hopes that the idea will die off. """ self.assert_admin(request) if tenant_id is None: raise exception.NotImplemented( message=_('User roles not supported: tenant_id required')) # This still has the weird legacy semantics that adding a role to # a user also adds them to a tenant, so we must follow up on that self.assignment_api.remove_role_from_user_and_project( user_id, tenant_id, role_id) # COMPAT(diablo): CRUD extension @controller.v2_deprecated def get_role_refs(self, request, user_id): """Ultimate hack to get around having to make role_refs first-class. This will basically iterate over the various roles the user has in all tenants the user is a member of and create fake role_refs where the id encodes the user-tenant-role information so we can look up the appropriate data when we need to delete them. """ self.assert_admin(request) tenants = self.assignment_api.list_projects_for_user(user_id) o = [] for tenant in tenants: # As a v2 call, we should limit the response to those projects in # the default domain. if tenant['domain_id'] != CONF.identity.default_domain_id: continue role_ids = self.assignment_api.get_roles_for_user_and_project( user_id, tenant['id']) for role_id in role_ids: ref = {'roleId': role_id, 'tenantId': tenant['id'], 'userId': user_id} ref['id'] = urllib.parse.urlencode(ref) o.append(ref) return {'roles': o} # COMPAT(diablo): CRUD extension @controller.v2_deprecated def create_role_ref(self, request, user_id, role): """Used for adding a user to a tenant. In the legacy data model adding a user to a tenant required setting a role. """ self.assert_admin(request) # TODO(termie): for now we're ignoring the actual role tenant_id = role.get('tenantId') role_id = role.get('roleId') self.assignment_api.add_role_to_user_and_project( user_id, tenant_id, role_id) role_ref = self.role_api.get_role(role_id) return {'role': role_ref} # COMPAT(diablo): CRUD extension @controller.v2_deprecated def delete_role_ref(self, request, user_id, role_ref_id): """Used for deleting a user from a tenant. In the legacy data model removing a user from a tenant required deleting a role. To emulate this, we encode the tenant and role in the role_ref_id, and if this happens to be the last role for the user-tenant pair, we remove the user from the tenant. """ self.assert_admin(request) # TODO(termie): for now we're ignoring the actual role role_ref_ref = urllib.parse.parse_qs(role_ref_id) tenant_id = role_ref_ref.get('tenantId')[0] role_id = role_ref_ref.get('roleId')[0] self.assignment_api.remove_role_from_user_and_project( user_id, tenant_id, role_id) @dependency.requires('assignment_api', 'resource_api') class ProjectAssignmentV3(controller.V3Controller): """The V3 Project APIs that are processing assignments.""" collection_name = 'projects' member_name = 'project' def __init__(self): super(ProjectAssignmentV3, self).__init__() self.get_member_from_driver = self.resource_api.get_project @controller.filterprotected('domain_id', 'enabled', 'name') def list_user_projects(self, request, filters, user_id): hints = ProjectAssignmentV3.build_driver_hints(request, filters) refs = self.assignment_api.list_projects_for_user(user_id, hints=hints) return ProjectAssignmentV3.wrap_collection(request.context_dict, refs, hints=hints) @dependency.requires('role_api') class RoleV3(controller.V3Controller): """The V3 Role CRUD APIs. To ease complexity (and hence risk) in writing the policy rules for the role APIs, we create separate policy actions for roles that are domain specific, as opposed to those that are global. In order to achieve this each of the role API methods has a wrapper method that checks to see if the role is global or domain specific. NOTE (henry-nash): If this separate global vs scoped policy action pattern becomes repeated for other entities, we should consider encapsulating this into a specialized router class. """ collection_name = 'roles' member_name = 'role' def __init__(self): super(RoleV3, self).__init__() self.get_member_from_driver = self.role_api.get_role def _is_domain_role(self, role): return role.get('domain_id') is not None def _is_domain_role_target(self, role_id): try: role = self.role_api.get_role(role_id) except exception.RoleNotFound: # We hide this error since we have not yet carried out a policy # check - and it maybe that the caller isn't authorized to make # this call. If so, we want that error to be raised instead. return False return self._is_domain_role(role) def create_role_wrapper(self, request, role): if self._is_domain_role(role): return self.create_domain_role(request, role=role) else: return self.create_role(request, role=role) @controller.protected() def create_role(self, request, role): validation.lazy_validate(schema.role_create, role) return self._create_role(request, role) @controller.protected() def create_domain_role(self, request, role): validation.lazy_validate(schema.role_create, role) return self._create_role(request, role) def list_roles_wrapper(self, request): if request.params.get('domain_id'): return self.list_domain_roles(request) else: return self.list_roles(request) @controller.filterprotected('name', 'domain_id') def list_roles(self, request, filters): return self._list_roles(request, filters) @controller.filterprotected('name', 'domain_id') def list_domain_roles(self, request, filters): return self._list_roles(request, filters) def get_role_wrapper(self, request, role_id): if self._is_domain_role_target(role_id): return self.get_domain_role(request, role_id=role_id) else: return self.get_role(request, role_id=role_id) @controller.protected() def get_role(self, request, role_id): return self._get_role(request, role_id) @controller.protected() def get_domain_role(self, request, role_id): return self._get_role(request, role_id) def update_role_wrapper(self, request, role_id, role): # Since we don't allow you change whether a role is global or domain # specific, we can ignore the new update attributes and just look at # the existing role. if self._is_domain_role_target(role_id): return self.update_domain_role( request, role_id=role_id, role=role) else: return self.update_role(request, role_id=role_id, role=role) @controller.protected() def update_role(self, request, role_id, role): validation.lazy_validate(schema.role_update, role) return self._update_role(request, role_id, role) @controller.protected() def update_domain_role(self, request, role_id, role): validation.lazy_validate(schema.role_update, role) return self._update_role(request, role_id, role) def delete_role_wrapper(self, request, role_id): if self._is_domain_role_target(role_id): return self.delete_domain_role(request, role_id=role_id) else: return self.delete_role(request, role_id=role_id) @controller.protected() def delete_role(self, request, role_id): return self._delete_role(request, role_id) @controller.protected() def delete_domain_role(self, request, role_id): return self._delete_role(request, role_id) def _create_role(self, request, role): if role['name'] == CONF.member_role_name: # Use the configured member role ID when creating the configured # member role name. This avoids the potential of creating a # "member" role with an unexpected ID. role['id'] = CONF.member_role_id else: role = self._assign_unique_id(role) ref = self._normalize_dict(role) ref = self.role_api.create_role(ref['id'], ref, initiator=request.audit_initiator) return RoleV3.wrap_member(request.context_dict, ref) def _list_roles(self, request, filters): hints = RoleV3.build_driver_hints(request, filters) refs = self.role_api.list_roles(hints=hints) return RoleV3.wrap_collection(request.context_dict, refs, hints=hints) def _get_role(self, request, role_id): ref = self.role_api.get_role(role_id) return RoleV3.wrap_member(request.context_dict, ref) def _update_role(self, request, role_id, role): self._require_matching_id(role_id, role) ref = self.role_api.update_role( role_id, role, initiator=request.audit_initiator ) return RoleV3.wrap_member(request.context_dict, ref) def _delete_role(self, request, role_id): self.role_api.delete_role(role_id, initiator=request.audit_initiator) @classmethod def build_driver_hints(cls, request, supported_filters): # NOTE(jamielennox): To handle the default case of no domain_id defined # the role_assignment backend does some hackery to distinguish between # global and domain scoped roles. This backend behaviour relies upon a # value of domain_id being set (not just defaulting to None). Manually # set the empty filter if its not provided. hints = super(RoleV3, cls).build_driver_hints(request, supported_filters) if not request.params.get('domain_id'): hints.add_filter('domain_id', None) return hints @dependency.requires('role_api') class ImpliedRolesV3(controller.V3Controller): """The V3 ImpliedRoles CRD APIs. There is no Update.""" def _check_implies_role(self, request, prep_info, prior_role_id, implied_role_id=None): ref = {} ref['prior_role'] = self.role_api.get_role(prior_role_id) if implied_role_id: ref['implied_role'] = self.role_api.get_role(implied_role_id) self.check_protection(request, prep_info, ref) def _prior_role_stanza(self, endpoint, prior_role_id, prior_role_name): return { "id": prior_role_id, "links": { "self": endpoint + "/v3/roles/" + prior_role_id }, "name": prior_role_name } def _implied_role_stanza(self, endpoint, implied_role): implied_id = implied_role['id'] implied_response = { "id": implied_id, "links": { "self": endpoint + "/v3/roles/" + implied_id }, "name": implied_role['name'] } return implied_response def _populate_prior_role_response(self, endpoint, prior_id): prior_role = self.role_api.get_role(prior_id) response = { "role_inference": { "prior_role": self._prior_role_stanza( endpoint, prior_id, prior_role['name']) } } return response def _populate_implied_roles_response(self, endpoint, prior_id, implied_ids): response = self._populate_prior_role_response(endpoint, prior_id) response["role_inference"]['implies'] = [] for implied_id in implied_ids: implied_role = self.role_api.get_role(implied_id) implied_response = self._implied_role_stanza( endpoint, implied_role) response["role_inference"]['implies'].append(implied_response) response["links"] = { "self": endpoint + "/v3/roles/" + prior_id + "/implies" } return response def _populate_implied_role_response(self, endpoint, prior_id, implied_id): response = self._populate_prior_role_response(endpoint, prior_id) implied_role = self.role_api.get_role(implied_id) stanza = self._implied_role_stanza(endpoint, implied_role) response["role_inference"]['implies'] = stanza return response @controller.protected(callback=_check_implies_role) def get_implied_role(self, request, prior_role_id, implied_role_id): ref = self.role_api.get_implied_role(prior_role_id, implied_role_id) prior_id = ref['prior_role_id'] implied_id = ref['implied_role_id'] endpoint = super(controller.V3Controller, ImpliedRolesV3).base_url( request.context_dict, 'public') response = self._populate_implied_role_response( endpoint, prior_id, implied_id) return response @controller.protected(callback=_check_implies_role) def check_implied_role(self, request, prior_role_id, implied_role_id): self.role_api.get_implied_role(prior_role_id, implied_role_id) @controller.protected(callback=_check_implies_role) def create_implied_role(self, request, prior_role_id, implied_role_id): self.role_api.create_implied_role(prior_role_id, implied_role_id) return wsgi.render_response( self.get_implied_role(request, prior_role_id, implied_role_id), status=(201, 'Created')) @controller.protected(callback=_check_implies_role) def delete_implied_role(self, request, prior_role_id, implied_role_id): self.role_api.delete_implied_role(prior_role_id, implied_role_id) @controller.protected(callback=_check_implies_role) def list_implied_roles(self, request, prior_role_id): ref = self.role_api.list_implied_roles(prior_role_id) implied_ids = [r['implied_role_id'] for r in ref] endpoint = super(controller.V3Controller, ImpliedRolesV3).base_url( request.context_dict, 'public') results = self._populate_implied_roles_response( endpoint, prior_role_id, implied_ids) return results @controller.protected() def list_role_inference_rules(self, request): refs = self.role_api.list_role_inference_rules() role_dict = {role_ref['id']: role_ref for role_ref in self.role_api.list_roles()} rules = dict() endpoint = super(controller.V3Controller, ImpliedRolesV3).base_url( request.context_dict, 'public') for ref in refs: implied_role_id = ref['implied_role_id'] prior_role_id = ref['prior_role_id'] implied = rules.get(prior_role_id, []) implied.append(self._implied_role_stanza( endpoint, role_dict[implied_role_id])) rules[prior_role_id] = implied inferences = [] for prior_id, implied in rules.items(): prior_response = self._prior_role_stanza( endpoint, prior_id, role_dict[prior_id]['name']) inferences.append({'prior_role': prior_response, 'implies': implied}) results = {'role_inferences': inferences} return results @dependency.requires('assignment_api', 'identity_api', 'resource_api', 'role_api') class GrantAssignmentV3(controller.V3Controller): """The V3 Grant Assignment APIs.""" collection_name = 'roles' member_name = 'role' def __init__(self): super(GrantAssignmentV3, self).__init__() self.get_member_from_driver = self.role_api.get_role def _require_domain_xor_project(self, domain_id, project_id): if domain_id and project_id: msg = _('Specify a domain or project, not both') raise exception.ValidationError(msg) if not domain_id and not project_id: msg = _('Specify one of domain or project') raise exception.ValidationError(msg) def _require_user_xor_group(self, user_id, group_id): if user_id and group_id: msg = _('Specify a user or group, not both') raise exception.ValidationError(msg) if not user_id and not group_id: msg = _('Specify one of user or group') raise exception.ValidationError(msg) def _check_if_inherited(self, context): return (context['path'].startswith('/OS-INHERIT') and context['path'].endswith('/inherited_to_projects')) def _check_grant_protection(self, request, protection, role_id=None, user_id=None, group_id=None, domain_id=None, project_id=None, allow_no_user=False): """Check protection for role grant APIs. The policy rule might want to inspect attributes of any of the entities involved in the grant. So we get these and pass them to the check_protection() handler in the controller. """ ref = {} if role_id: ref['role'] = self.role_api.get_role(role_id) if user_id: try: ref['user'] = self.identity_api.get_user(user_id) print ("REF 'USER' : ") #reg_user_name = ref['user']['name'] #print reg_user_name #ref['location'] = 'san_antonio' #ref['admin_unit'] = 'accounting' #ref['clearance'] = 'top_secret' #ref = ref except exception.UserNotFound: if not allow_no_user: raise else: ref['group'] = self.identity_api.get_group(group_id) if domain_id: ref['domain'] = self.resource_api.get_domain(domain_id) else: ref['project'] = self.resource_api.get_project(project_id) self.check_protection(request, protection, ref) @controller.protected(callback=_check_grant_protection) def create_grant(self, request, role_id, user_id=None, group_id=None, domain_id=None, project_id=None): """Grant a role to a user or group on either a domain or project.""" self._require_domain_xor_project(domain_id, project_id) self._require_user_xor_group(user_id, group_id) self.assignment_api.create_grant( role_id, user_id, group_id, domain_id, project_id, self._check_if_inherited(request.context_dict), request.context_dict) @controller.protected(callback=_check_grant_protection) def list_grants(self, request, user_id=None, group_id=None, domain_id=None, project_id=None): """List roles granted to user/group on either a domain or project.""" self._require_domain_xor_project(domain_id, project_id) self._require_user_xor_group(user_id, group_id) refs = self.assignment_api.list_grants( user_id, group_id, domain_id, project_id, self._check_if_inherited(request.context_dict)) return GrantAssignmentV3.wrap_collection(request.context_dict, refs) @controller.protected(callback=_check_grant_protection) def check_grant(self, request, role_id, user_id=None, group_id=None, domain_id=None, project_id=None): """Check if a role has been granted on either a domain or project.""" self._require_domain_xor_project(domain_id, project_id) self._require_user_xor_group(user_id, group_id) self.assignment_api.get_grant( role_id, user_id, group_id, domain_id, project_id, self._check_if_inherited(request.context_dict)) # NOTE(lbragstad): This will allow users to clean up role assignments # from the backend in the event the user was removed prior to the role # assignment being removed. @controller.protected(callback=functools.partial( _check_grant_protection, allow_no_user=True)) def revoke_grant(self, request, role_id, user_id=None, group_id=None, domain_id=None, project_id=None): """Revoke a role from user/group on either a domain or project.""" self._require_domain_xor_project(domain_id, project_id) self._require_user_xor_group(user_id, group_id) self.assignment_api.delete_grant( role_id, user_id, group_id, domain_id, project_id, self._check_if_inherited(request.context_dict), request.context_dict) @dependency.requires('assignment_api', 'identity_api', 'resource_api') class RoleAssignmentV3(controller.V3Controller): """The V3 Role Assignment APIs, really just list_role_assignment().""" # TODO(henry-nash): The current implementation does not provide a full # first class entity for role-assignment. There is no role_assignment_id # and only the list_role_assignment call is supported. Further, since it # is not a first class entity, the links for the individual entities # reference the individual role grant APIs. collection_name = 'role_assignments' member_name = 'role_assignment' @classmethod def wrap_member(cls, context, ref): # NOTE(henry-nash): Since we are not yet a true collection, we override # the wrapper as have already included the links in the entities pass def _format_entity(self, context, entity): """Format an assignment entity for API response. The driver layer returns entities as dicts containing the ids of the actor (e.g. user or group), target (e.g. domain or project) and role. If it is an inherited role, then this is also indicated. Examples: For a non-inherited expanded assignment from group membership: {'user_id': user_id, 'project_id': project_id, 'role_id': role_id, 'indirect': {'group_id': group_id}} or, for a project inherited role: {'user_id': user_id, 'project_id': project_id, 'role_id': role_id, 'indirect': {'project_id': parent_id}} or, for a role that was implied by a prior role: {'user_id': user_id, 'project_id': project_id, 'role_id': role_id, 'indirect': {'role_id': prior role_id}} It is possible to deduce if a role assignment came from group membership if it has both 'user_id' in the main body of the dict and 'group_id' in the 'indirect' subdict, as well as it is possible to deduce if it has come from inheritance if it contains both a 'project_id' in the main body of the dict and 'parent_id' in the 'indirect' subdict. This function maps this into the format to be returned via the API, e.g. for the second example above: { 'user': { {'id': user_id} }, 'scope': { 'project': { {'id': project_id} }, 'OS-INHERIT:inherited_to': 'projects' }, 'role': { {'id': role_id} }, 'links': { 'assignment': '/OS-INHERIT/projects/parent_id/users/user_id/' 'roles/role_id/inherited_to_projects' } } """ formatted_entity = {'links': {}} inherited_assignment = entity.get('inherited_to_projects') if 'project_id' in entity: if 'project_name' in entity: formatted_entity['scope'] = {'project': { 'id': entity['project_id'], 'name': entity['project_name'], 'domain': {'id': entity['project_domain_id'], 'name': entity['project_domain_name']}}} else: formatted_entity['scope'] = { 'project': {'id': entity['project_id']}} if 'domain_id' in entity.get('indirect', {}): inherited_assignment = True formatted_link = ('/domains/%s' % entity['indirect']['domain_id']) elif 'project_id' in entity.get('indirect', {}): inherited_assignment = True formatted_link = ('/projects/%s' % entity['indirect']['project_id']) else: formatted_link = '/projects/%s' % entity['project_id'] elif 'domain_id' in entity: if 'domain_name' in entity: formatted_entity['scope'] = { 'domain': {'id': entity['domain_id'], 'name': entity['domain_name']}} else: formatted_entity['scope'] = { 'domain': {'id': entity['domain_id']}} formatted_link = '/domains/%s' % entity['domain_id'] if 'user_id' in entity: if 'user_name' in entity: formatted_entity['user'] = { 'id': entity['user_id'], 'name': entity['user_name'], 'domain': {'id': entity['user_domain_id'], 'name': entity['user_domain_name']}} else: formatted_entity['user'] = {'id': entity['user_id']} if 'group_id' in entity.get('indirect', {}): membership_url = ( self.base_url(context, '/groups/%s/users/%s' % ( entity['indirect']['group_id'], entity['user_id']))) formatted_entity['links']['membership'] = membership_url formatted_link += '/groups/%s' % entity['indirect']['group_id'] else: formatted_link += '/users/%s' % entity['user_id'] elif 'group_id' in entity: if 'group_name' in entity: formatted_entity['group'] = { 'id': entity['group_id'], 'name': entity['group_name'], 'domain': {'id': entity['group_domain_id'], 'name': entity['group_domain_name']}} else: formatted_entity['group'] = {'id': entity['group_id']} formatted_link += '/groups/%s' % entity['group_id'] if 'role_name' in entity: formatted_entity['role'] = {'id': entity['role_id'], 'name': entity['role_name']} if 'role_domain_id' in entity and 'role_domain_name' in entity: formatted_entity['role'].update( {'domain': {'id': entity['role_domain_id'], 'name': entity['role_domain_name']}}) else: formatted_entity['role'] = {'id': entity['role_id']} prior_role_link = '' if 'role_id' in entity.get('indirect', {}): formatted_link += '/roles/%s' % entity['indirect']['role_id'] prior_role_link = ( '/prior_role/%(prior)s/implies/%(implied)s' % { 'prior': entity['role_id'], 'implied': entity['indirect']['role_id'] }) else: formatted_link += '/roles/%s' % entity['role_id'] if inherited_assignment: formatted_entity['scope']['OS-INHERIT:inherited_to'] = ( 'projects') formatted_link = ('/OS-INHERIT%s/inherited_to_projects' % formatted_link) formatted_entity['links']['assignment'] = self.base_url(context, formatted_link) if prior_role_link: formatted_entity['links']['prior_role'] = ( self.base_url(context, prior_role_link)) return formatted_entity def _assert_effective_filters(self, inherited, group, domain): """Assert that useless filter combinations are avoided. In effective mode, the following filter combinations are useless, since they would always return an empty list of role assignments: - group id, since no group assignment is returned in effective mode; - domain id and inherited, since no domain inherited assignment is returned in effective mode. """ if group: msg = _('Combining effective and group filter will always ' 'result in an empty list.') raise exception.ValidationError(msg) if inherited and domain: msg = _('Combining effective, domain and inherited filters will ' 'always result in an empty list.') raise exception.ValidationError(msg) def _assert_domain_nand_project(self, domain_id, project_id): if domain_id and project_id: msg = _('Specify a domain or project, not both') raise exception.ValidationError(msg) def _assert_user_nand_group(self, user_id, group_id): if user_id and group_id: msg = _('Specify a user or group, not both') raise exception.ValidationError(msg) def _list_role_assignments(self, request, filters, include_subtree=False): """List role assignments to user and groups on domains and projects. Return a list of all existing role assignments in the system, filtered by assignments attributes, if provided. If effective option is used and OS-INHERIT extension is enabled, the following functions will be applied: 1) For any group role assignment on a target, replace it by a set of role assignments containing one for each user of that group on that target; 2) For any inherited role assignment for an actor on a target, replace it by a set of role assignments for that actor on every project under that target. It means that, if effective mode is used, no group or domain inherited assignments will be present in the resultant list. Thus, combining effective with them is invalid. As a role assignment contains only one actor and one target, providing both user and group ids or domain and project ids is invalid as well. """ params = request.params effective = 'effective' in params and ( self.query_filter_is_true(params['effective'])) include_names = ('include_names' in params and self.query_filter_is_true(params['include_names'])) if 'scope.OS-INHERIT:inherited_to' in params: inherited = ( params['scope.OS-INHERIT:inherited_to'] == 'projects') else: # None means querying both inherited and direct assignments inherited = None self._assert_domain_nand_project(params.get('scope.domain.id'), params.get('scope.project.id')) self._assert_user_nand_group(params.get('user.id'), params.get('group.id')) if effective: self._assert_effective_filters(inherited=inherited, group=params.get('group.id'), domain=params.get( 'scope.domain.id')) refs = self.assignment_api.list_role_assignments( role_id=params.get('role.id'), user_id=params.get('user.id'), group_id=params.get('group.id'), domain_id=params.get('scope.domain.id'), project_id=params.get('scope.project.id'), include_subtree=include_subtree, inherited=inherited, effective=effective, include_names=include_names) formatted_refs = [self._format_entity(request.context_dict, ref) for ref in refs] return self.wrap_collection(request.context_dict, formatted_refs) @controller.filterprotected('group.id', 'role.id', 'scope.domain.id', 'scope.project.id', 'scope.OS-INHERIT:inherited_to', 'user.id') def list_role_assignments(self, request, filters): return self._list_role_assignments(request, filters) def _check_list_tree_protection(self, request, protection_info): """Check protection for list assignment for tree API. The policy rule might want to inspect the domain of any project filter so if one is defined, then load the project ref and pass it to the check protection method. """ ref = {} for filter, value in protection_info['filter_attr'].items(): if filter == 'scope.project.id' and value: ref['project'] = self.resource_api.get_project(value) self.check_protection(request, protection_info, ref) @controller.filterprotected('group.id', 'role.id', 'scope.domain.id', 'scope.project.id', 'scope.OS-INHERIT:inherited_to', 'user.id', callback=_check_list_tree_protection) def list_role_assignments_for_tree(self, request, filters): if not request.params.get('scope.project.id'): msg = _('scope.project.id must be specified if include_subtree ' 'is also specified') raise exception.ValidationError(message=msg) return self._list_role_assignments(request, filters, include_subtree=True) def list_role_assignments_wrapper(self, request): """Main entry point from router for list role assignments. Since we want different policy file rules to be applicable based on whether there the include_subtree query parameter is part of the API call, this method checks for this and then calls the appropriate protected entry point. """ params = request.params if 'include_subtree' in params and ( self.query_filter_is_true(params['include_subtree'])): return self.list_role_assignments_for_tree(request) else: return self.list_role_assignments(request)
minhphung171093/GreenERP
refs/heads/master
openerp/addons/bus/models/__init__.py
67
# -*- coding: utf-8 -*- import bus import bus_presence import res_users import res_partner
andrespires/python-buildpack
refs/heads/master
vendor/pip-pop/pip/_vendor/html5lib/treewalkers/_base.py
436
from __future__ import absolute_import, division, unicode_literals from pip._vendor.six import text_type, string_types __all__ = ["DOCUMENT", "DOCTYPE", "TEXT", "ELEMENT", "COMMENT", "ENTITY", "UNKNOWN", "TreeWalker", "NonRecursiveTreeWalker"] from xml.dom import Node DOCUMENT = Node.DOCUMENT_NODE DOCTYPE = Node.DOCUMENT_TYPE_NODE TEXT = Node.TEXT_NODE ELEMENT = Node.ELEMENT_NODE COMMENT = Node.COMMENT_NODE ENTITY = Node.ENTITY_NODE UNKNOWN = "<#UNKNOWN#>" from ..constants import voidElements, spaceCharacters spaceCharacters = "".join(spaceCharacters) def to_text(s, blank_if_none=True): """Wrapper around six.text_type to convert None to empty string""" if s is None: if blank_if_none: return "" else: return None elif isinstance(s, text_type): return s else: return text_type(s) def is_text_or_none(string): """Wrapper around isinstance(string_types) or is None""" return string is None or isinstance(string, string_types) class TreeWalker(object): def __init__(self, tree): self.tree = tree def __iter__(self): raise NotImplementedError def error(self, msg): return {"type": "SerializeError", "data": msg} def emptyTag(self, namespace, name, attrs, hasChildren=False): assert namespace is None or isinstance(namespace, string_types), type(namespace) assert isinstance(name, string_types), type(name) assert all((namespace is None or isinstance(namespace, string_types)) and isinstance(name, string_types) and isinstance(value, string_types) for (namespace, name), value in attrs.items()) yield {"type": "EmptyTag", "name": to_text(name, False), "namespace": to_text(namespace), "data": attrs} if hasChildren: yield self.error("Void element has children") def startTag(self, namespace, name, attrs): assert namespace is None or isinstance(namespace, string_types), type(namespace) assert isinstance(name, string_types), type(name) assert all((namespace is None or isinstance(namespace, string_types)) and isinstance(name, string_types) and isinstance(value, string_types) for (namespace, name), value in attrs.items()) return {"type": "StartTag", "name": text_type(name), "namespace": to_text(namespace), "data": dict(((to_text(namespace, False), to_text(name)), to_text(value, False)) for (namespace, name), value in attrs.items())} def endTag(self, namespace, name): assert namespace is None or isinstance(namespace, string_types), type(namespace) assert isinstance(name, string_types), type(namespace) return {"type": "EndTag", "name": to_text(name, False), "namespace": to_text(namespace), "data": {}} def text(self, data): assert isinstance(data, string_types), type(data) data = to_text(data) middle = data.lstrip(spaceCharacters) left = data[:len(data) - len(middle)] if left: yield {"type": "SpaceCharacters", "data": left} data = middle middle = data.rstrip(spaceCharacters) right = data[len(middle):] if middle: yield {"type": "Characters", "data": middle} if right: yield {"type": "SpaceCharacters", "data": right} def comment(self, data): assert isinstance(data, string_types), type(data) return {"type": "Comment", "data": text_type(data)} def doctype(self, name, publicId=None, systemId=None, correct=True): assert is_text_or_none(name), type(name) assert is_text_or_none(publicId), type(publicId) assert is_text_or_none(systemId), type(systemId) return {"type": "Doctype", "name": to_text(name), "publicId": to_text(publicId), "systemId": to_text(systemId), "correct": to_text(correct)} def entity(self, name): assert isinstance(name, string_types), type(name) return {"type": "Entity", "name": text_type(name)} def unknown(self, nodeType): return self.error("Unknown node type: " + nodeType) class NonRecursiveTreeWalker(TreeWalker): def getNodeDetails(self, node): raise NotImplementedError def getFirstChild(self, node): raise NotImplementedError def getNextSibling(self, node): raise NotImplementedError def getParentNode(self, node): raise NotImplementedError def __iter__(self): currentNode = self.tree while currentNode is not None: details = self.getNodeDetails(currentNode) type, details = details[0], details[1:] hasChildren = False if type == DOCTYPE: yield self.doctype(*details) elif type == TEXT: for token in self.text(*details): yield token elif type == ELEMENT: namespace, name, attributes, hasChildren = details if name in voidElements: for token in self.emptyTag(namespace, name, attributes, hasChildren): yield token hasChildren = False else: yield self.startTag(namespace, name, attributes) elif type == COMMENT: yield self.comment(details[0]) elif type == ENTITY: yield self.entity(details[0]) elif type == DOCUMENT: hasChildren = True else: yield self.unknown(details[0]) if hasChildren: firstChild = self.getFirstChild(currentNode) else: firstChild = None if firstChild is not None: currentNode = firstChild else: while currentNode is not None: details = self.getNodeDetails(currentNode) type, details = details[0], details[1:] if type == ELEMENT: namespace, name, attributes, hasChildren = details if name not in voidElements: yield self.endTag(namespace, name) if self.tree is currentNode: currentNode = None break nextSibling = self.getNextSibling(currentNode) if nextSibling is not None: currentNode = nextSibling break else: currentNode = self.getParentNode(currentNode)
bright-sparks/chromium-spacewalk
refs/heads/master
tools/cr/cr/base/linux.py
138
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """The linux specific host and platform implementation module.""" import os import cr class LinuxHost(cr.Host): """The implementation of Host for linux.""" ACTIVE = cr.Config.From( GOOGLE_CODE='/usr/local/google/code', ) def __init__(self): super(LinuxHost, self).__init__() def Matches(self): return cr.Platform.System() == 'Linux' class LinuxPlatform(cr.Platform): """The implementation of Platform for the linux target.""" ACTIVE = cr.Config.From( CR_BINARY=os.path.join('{CR_BUILD_DIR}', '{CR_BUILD_TARGET}'), CHROME_DEVEL_SANDBOX='/usr/local/sbin/chrome-devel-sandbox', ) @property def enabled(self): return cr.Platform.System() == 'Linux' @property def priority(self): return 2 @property def paths(self): return ['{GOMA_DIR}']
saintfrank/tabu-benchmark
refs/heads/master
dtu_lcf.py
2
## ## @author Francesco Cervigni ## @date 2012-10 ## ## This file contains the main logic of the application. ## The specific functions used are defined in separte files in the same folder. ## from data_structures import Mapping from load import taskLoad from analysis import DM_guarantee import sys, operator, math from copy import deepcopy # START def divide_routers (M, N): print '\n- Dividing routers in A_4, A_3, A_2' A_2 = [] A_3 = [] A_4 = [] for index in range(M*N): #A2 are the coners, so 4 if index == 0 or index == M -1 or index == M*(N-1) or index == (M*N-1) : A_2.append( ( index, None) ) else : if index % M == 0 or index % M == M-1 or math.floor( index / M ) == 0 or math.floor( index / M ) == N-1 : A_3.append( ( index, None ) ) else : A_4.append( ( index, None ) ) print '\nSet\tTiles (indexes)' print '------------------------------------------------' print 'A_4\t' , [ index for index, ob in A_4] print 'A_3\t' ,[ index for index, ob in A_3] print 'A_2\t' , [ index for index, ob in A_2] return A_2, A_3, A_4 def assign_to_tiles( tasks_ordered , M, N, A_2, A_3, A_4) : print '\n- Mapping Tasks to tiles\n' mapping = Mapping (M, N) for task, level in tasks_ordered : A_4_free = [ ( num, index ) for num, (index, t) in enumerate(A_4) if t is None ] if len( A_4_free ) > 0 : print 'Placing ', task.name, ' in on of the ', len( A_4_free ) , ' available slots in A4.' # If there is space in A_4 best_cost = 100000000 best_index = -1 best_num = -1 # Deciding which is of the positions in A_4 is best for ( num, index ) in A_4_free : mapping.set( task, index ) if mapping.cost() < best_cost : best_index = index best_cost = mapping.cost() best_num = num mapping.set( None, index ) # Definitive mapping mapping.set( task, best_index ) print 'Best A_4 tile for task ' , task.name , ' is ' , best_index, ' :','\n', mapping # Updating A4 A_4[best_num] = ( A_4[best_num][0], task ) else: print 'Available slot in A3' A_3_free = [ ( num, index ) for num, (index, t) in enumerate(A_3) if t is None ] if len( A_3_free ) > 0 : # If there is space in A_4 best_cost = 100000000 best_index = -1 best_num = -1 # Deciding which is of the positions in A_4 is best for ( num, index ) in A_3_free : mapping.set( task, index ) if mapping.cost() < best_cost : best_index = index best_cost = mapping.cost() best_num = num mapping.set( None, index ) # Definitive mapping mapping.set( task, best_index ) print 'Mapping task ' , task.name , ' to tile ' , best_index, ' :','\n', mapping # Updating A4 A_3[best_num] = ( A_3[best_num][0], task ) else: print 'Available slot in A2' A_2_free = [ ( num, index ) for num, (index, t) in enumerate(A_2) if t is None ] if len( A_2_free ) > 0 : # If there is space in A_4 best_cost = 100000000 best_index = -1 best_num = -1 # Deciding which is of the positions in A_4 is best for ( num, index ) in A_2_free : mapping.set( task, index ) if mapping.cost() < best_cost : best_index = index best_cost = mapping.cost() best_num = num mapping.set( None, index ) # Definitive mapping mapping.set( task, best_index ) print 'Mapping task ' , task.name , ' to tile ' , best_index, ' :','\n', mapping # Updating A4 A_2[best_num] = ( A_2[best_num][0], task ) return mapping def lcf_map ( tasks, M, N ): task_com = [] for task in tasks : count = 0 for out in task.out_coms : count += out.weight #todo see better this balance for in_com in task.in_coms : count += in_com.weight #todo see better this balance task_com.append((task, count)) task_com.sort(reverse = True, key=operator.itemgetter(1) ) A_2, A_3, A_4 = divide_routers ( M, N ) mapping = assign_to_tiles ( task_com , M, N, A_2, A_3, A_4 ) print 'Final Mapping is - Cost ', mapping.cost(), '\n', mapping, if __name__ == '__main__': verbose = False import argparse parser = argparse.ArgumentParser(description='Description of your program') parser.add_argument('file',help='Path of input file') parser.add_argument('-m','--lines', help='Tiles lines',type=int, required=True) parser.add_argument('-n','--columns', help='Tiles columns', type=int, required=True) parser.add_argument('-v', '--verbose', help='Verbose') args = vars(parser.parse_args()) M = args['lines'] N = args['columns'] if args['verbose'] is not None : verbose = True input_file = args['file'] myTasks, myComs = taskLoad( input_file ) if verbose : print 'Tasks Loaded : ' for t in myTasks : print t.my_print() print 'Communications loaded : ' for c in myComs: c.my_print() M = 5 N = 5 lcf_map(myTasks, M , N)
willingc/oh-mainline
refs/heads/master
vendor/packages/twisted/twisted/conch/ttymodes.py
82
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. # import tty # this module was autogenerated. VINTR = 1 VQUIT = 2 VERASE = 3 VKILL = 4 VEOF = 5 VEOL = 6 VEOL2 = 7 VSTART = 8 VSTOP = 9 VSUSP = 10 VDSUSP = 11 VREPRINT = 12 VWERASE = 13 VLNEXT = 14 VFLUSH = 15 VSWTCH = 16 VSTATUS = 17 VDISCARD = 18 IGNPAR = 30 PARMRK = 31 INPCK = 32 ISTRIP = 33 INLCR = 34 IGNCR = 35 ICRNL = 36 IUCLC = 37 IXON = 38 IXANY = 39 IXOFF = 40 IMAXBEL = 41 ISIG = 50 ICANON = 51 XCASE = 52 ECHO = 53 ECHOE = 54 ECHOK = 55 ECHONL = 56 NOFLSH = 57 TOSTOP = 58 IEXTEN = 59 ECHOCTL = 60 ECHOKE = 61 PENDIN = 62 OPOST = 70 OLCUC = 71 ONLCR = 72 OCRNL = 73 ONOCR = 74 ONLRET = 75 CS7 = 90 CS8 = 91 PARENB = 92 PARODD = 93 TTY_OP_ISPEED = 128 TTY_OP_OSPEED = 129 TTYMODES = { 1 : 'VINTR', 2 : 'VQUIT', 3 : 'VERASE', 4 : 'VKILL', 5 : 'VEOF', 6 : 'VEOL', 7 : 'VEOL2', 8 : 'VSTART', 9 : 'VSTOP', 10 : 'VSUSP', 11 : 'VDSUSP', 12 : 'VREPRINT', 13 : 'VWERASE', 14 : 'VLNEXT', 15 : 'VFLUSH', 16 : 'VSWTCH', 17 : 'VSTATUS', 18 : 'VDISCARD', 30 : (tty.IFLAG, 'IGNPAR'), 31 : (tty.IFLAG, 'PARMRK'), 32 : (tty.IFLAG, 'INPCK'), 33 : (tty.IFLAG, 'ISTRIP'), 34 : (tty.IFLAG, 'INLCR'), 35 : (tty.IFLAG, 'IGNCR'), 36 : (tty.IFLAG, 'ICRNL'), 37 : (tty.IFLAG, 'IUCLC'), 38 : (tty.IFLAG, 'IXON'), 39 : (tty.IFLAG, 'IXANY'), 40 : (tty.IFLAG, 'IXOFF'), 41 : (tty.IFLAG, 'IMAXBEL'), 50 : (tty.LFLAG, 'ISIG'), 51 : (tty.LFLAG, 'ICANON'), 52 : (tty.LFLAG, 'XCASE'), 53 : (tty.LFLAG, 'ECHO'), 54 : (tty.LFLAG, 'ECHOE'), 55 : (tty.LFLAG, 'ECHOK'), 56 : (tty.LFLAG, 'ECHONL'), 57 : (tty.LFLAG, 'NOFLSH'), 58 : (tty.LFLAG, 'TOSTOP'), 59 : (tty.LFLAG, 'IEXTEN'), 60 : (tty.LFLAG, 'ECHOCTL'), 61 : (tty.LFLAG, 'ECHOKE'), 62 : (tty.LFLAG, 'PENDIN'), 70 : (tty.OFLAG, 'OPOST'), 71 : (tty.OFLAG, 'OLCUC'), 72 : (tty.OFLAG, 'ONLCR'), 73 : (tty.OFLAG, 'OCRNL'), 74 : (tty.OFLAG, 'ONOCR'), 75 : (tty.OFLAG, 'ONLRET'), # 90 : (tty.CFLAG, 'CS7'), # 91 : (tty.CFLAG, 'CS8'), 92 : (tty.CFLAG, 'PARENB'), 93 : (tty.CFLAG, 'PARODD'), 128 : 'ISPEED', 129 : 'OSPEED' }
fujunwei/chromium-crosswalk
refs/heads/master
third_party/cython/src/Cython/Compiler/Tests/TestUtilityLoad.py
129
import unittest from Cython.Compiler import Code, UtilityCode def strip_2tup(tup): return tup[0] and tup[0].strip(), tup[1] and tup[1].strip() class TestUtilityLoader(unittest.TestCase): """ Test loading UtilityCodes """ expected = "test {{loader}} prototype", "test {{loader}} impl" required = "req {{loader}} proto", "req {{loader}} impl" context = dict(loader='Loader') name = "TestUtilityLoader" filename = "TestUtilityLoader.c" cls = Code.UtilityCode def test_load_as_string(self): got = strip_2tup(self.cls.load_as_string(self.name)) self.assertEquals(got, self.expected) got = strip_2tup(self.cls.load_as_string(self.name, self.filename)) self.assertEquals(got, self.expected) def test_load(self): utility = self.cls.load(self.name) got = strip_2tup((utility.proto, utility.impl)) self.assertEquals(got, self.expected) required, = utility.requires got = strip_2tup((required.proto, required.impl)) self.assertEquals(got, self.required) utility = self.cls.load(self.name, from_file=self.filename) got = strip_2tup((utility.proto, utility.impl)) self.assertEquals(got, self.expected) utility = self.cls.load_cached(self.name, from_file=self.filename) got = strip_2tup((utility.proto, utility.impl)) self.assertEquals(got, self.expected) class TestTempitaUtilityLoader(TestUtilityLoader): """ Test loading UtilityCodes with Tempita substitution """ expected_tempita = (TestUtilityLoader.expected[0].replace('{{loader}}', 'Loader'), TestUtilityLoader.expected[1].replace('{{loader}}', 'Loader')) required_tempita = (TestUtilityLoader.required[0].replace('{{loader}}', 'Loader'), TestUtilityLoader.required[1].replace('{{loader}}', 'Loader')) cls = Code.TempitaUtilityCode def test_load_as_string(self): got = strip_2tup(self.cls.load_as_string(self.name, context=self.context)) self.assertEquals(got, self.expected_tempita) def test_load(self): utility = self.cls.load(self.name, context=self.context) got = strip_2tup((utility.proto, utility.impl)) self.assertEquals(got, self.expected_tempita) required, = utility.requires got = strip_2tup((required.proto, required.impl)) self.assertEquals(got, self.required_tempita) utility = self.cls.load(self.name, from_file=self.filename, context=self.context) got = strip_2tup((utility.proto, utility.impl)) self.assertEquals(got, self.expected_tempita) class TestCythonUtilityLoader(TestTempitaUtilityLoader): """ Test loading CythonUtilityCodes """ # Just change the attributes and run the same tests expected = None, "test {{cy_loader}} impl" expected_tempita = None, "test CyLoader impl" required = None, "req {{cy_loader}} impl" required_tempita = None, "req CyLoader impl" context = dict(cy_loader='CyLoader') name = "TestCyUtilityLoader" filename = "TestCyUtilityLoader.pyx" cls = UtilityCode.CythonUtilityCode # Small hack to pass our tests above cls.proto = None test_load = TestUtilityLoader.test_load test_load_tempita = TestTempitaUtilityLoader.test_load
lesina/Hack70
refs/heads/master
env/lib/python3.5/site-packages/setuptools/command/bdist_wininst.py
991
import distutils.command.bdist_wininst as orig class bdist_wininst(orig.bdist_wininst): def reinitialize_command(self, command, reinit_subcommands=0): """ Supplement reinitialize_command to work around http://bugs.python.org/issue20819 """ cmd = self.distribution.reinitialize_command( command, reinit_subcommands) if command in ('install', 'install_lib'): cmd.install_lib = None return cmd def run(self): self._is_running = True try: orig.bdist_wininst.run(self) finally: self._is_running = False
leafclick/intellij-community
refs/heads/master
python/testData/refactoring/pullup/abstractMethodPy3AddMeta/SuperClass.py
80
from abc import object class Parent(object): pass
mmcbride1/python-coretemp
refs/heads/master
coretemp/sensor_reading.py
1
import re import os import sys import subprocess import sensors as r import coretemp_log as log import coretemp_config as conf from collections import OrderedDict ''' Get sensor constants ''' from coretemp_constants import SUB_MAX_TYPE, SUB_CRT_TYPE, CHIP, NORM, HIGH, CRTC class SensorReading: ''' Store sensor threshold ''' crit = [] high = [] ''' Store log message ''' MSG = "" ''' Store sensor reading ''' read = OrderedDict() ''' Configuration ''' CONF = conf.Config("threshold").get_config() ERRO = log.ExceptionLog() def __init__(self): """ Constructor: Set chip reading and log message """ try: self.__set_chip_read() self.__set_message() except Exception as ex: self.ERRO.update_errlog(ex) def get_reading(self): """ Get sensor reading :return: sensor reading """ return self.read def get_message(self): """ Get log message :return: log message string """ return self.MSG def get_failed(self): """ Get readings only deemed as high or critical from the primary reading :return: max/crt message string """ return re.sub(".*NORMAL.*\n?","",self.MSG) def __collect_recommended(self, sub): """ Gets the recommended threshold values as determined by the sensor sub-feature set :param str sub: the given sub-feature """ self.sub = sub num = sub.get_value() if sub.type == SUB_MAX_TYPE: self.high.append(num) if sub.type == SUB_CRT_TYPE: self.crit.append(num) def __avg(self, arr): """ Obtains the mean value of the collection :param list arr: any given list :return: average value """ self.arr = arr try: avg = sum(arr)/float(len(arr)) return round(avg, 2) except ZeroDivisionError as z: self.ERRO.update_errlog(z) return 0 def get_avg_read(self): """ Gets the average core value of the list of chips on the read :return: average core value """ return self.__avg(self.read.values()) def __msg_str(self, k, v, i): """ Helper function to build the log output message :param str k: core # :param str v: reading :param str i: indicator :return: formatted log message """ self.k = k self.v = v self.i = i return "%s : %s -> %s\n" % (k, v, i) def __set_defaults(self, arr): """ Sets default values for the thresholds in the case that none are provided in the config and a reading cannot be obtained from the chip :param list arr: generated threshold list :return: updated list with defaults """ self.arr = arr for k, v in arr.items(): if k is 'MAX' and v == 0: arr[k] = 86.0 if k is 'CRT' and v == 0: arr[k] = 96.0 return arr def get_threshold(self): """ The primary threshold setting mechanism. Sets first from the config then next from the recommended values if no such properties exist :return: dict containing max/crt values """ h = self.CONF['high'] c = self.CONF['crit'] if h is "" or float(h) <= 0: h = self.__avg(self.high) if c is "" or float(c) <= 0: c = self.__avg(self.crit) order = [float(h),float(c)] high = min(order) crit = max(order) return {'MAX':high,'CRT':crit} def __set_chip_read(self): """ Queries the chip applies result to the 'read' dict. Then, collects the recommended threshold values """ r.init() try: for x in r.iter_detected_chips(CHIP): for f in x: if "Core" in f.label: self.read[f.label] = f.get_value() for sub in f: self.__collect_recommended(sub) finally: r.cleanup() def __set_message(self): """ Builds the output (log) message based on the standing of the chip read and whether given thresholds were reached """ th = self.__set_defaults(self.get_threshold()) for k, v in self.get_reading().items(): if v < th['MAX']: self.MSG += self.__msg_str(k,v,NORM) elif v >= th['MAX'] and v < th['CRT']: self.MSG += self.__msg_str(k,v,HIGH) elif v >= th['CRT']: self.MSG += self.__msg_str(k,v,CRTC) else: self.MSG += self.__msg_str(k,v,"UNKNOWN")
yogo1212/RIOT
refs/heads/master
examples/micropython/boot.py
21
print("boot.py: MicroPython says hello!")
creativecommons/cc.license
refs/heads/master
cc/license/selectors/__init__.py
1
from cc.license._lib import rdf_helper from cc.license._lib.exceptions import CCLicenseError import classes SELECTORS = {} __all__ = ['choose', 'list', # functions ] for uri in rdf_helper.get_selector_uris(): sel = classes.LicenseSelector(uri) SELECTORS[sel.id] = sel del sel # cleanup reference def choose(license_class): """Return an instance of ILicenseSelector for a specific license class id. The default license class id is 'standard'""" try: return SELECTORS[license_class] except KeyError: return None def list(): """Return a list of available selector IDs.""" return SELECTORS.keys()
jseabold/statsmodels
refs/heads/master
examples/python/discrete_choice_overview.py
5
# coding: utf-8 # DO NOT EDIT # Autogenerated from the notebook discrete_choice_overview.ipynb. # Edit the notebook and then sync the output with this file. # # flake8: noqa # DO NOT EDIT # # Discrete Choice Models Overview import numpy as np import statsmodels.api as sm # ## Data # # Load data from Spector and Mazzeo (1980). Examples follow Greene's # Econometric Analysis Ch. 21 (5th Edition). spector_data = sm.datasets.spector.load() spector_data.exog = sm.add_constant(spector_data.exog, prepend=False) # Inspect the data: print(spector_data.exog[:5, :]) print(spector_data.endog[:5]) # ## Linear Probability Model (OLS) lpm_mod = sm.OLS(spector_data.endog, spector_data.exog) lpm_res = lpm_mod.fit() print('Parameters: ', lpm_res.params[:-1]) # ## Logit Model logit_mod = sm.Logit(spector_data.endog, spector_data.exog) logit_res = logit_mod.fit(disp=0) print('Parameters: ', logit_res.params) # Marginal Effects margeff = logit_res.get_margeff() print(margeff.summary()) # As in all the discrete data models presented below, we can print a nice # summary of results: print(logit_res.summary()) # ## Probit Model probit_mod = sm.Probit(spector_data.endog, spector_data.exog) probit_res = probit_mod.fit() probit_margeff = probit_res.get_margeff() print('Parameters: ', probit_res.params) print('Marginal effects: ') print(probit_margeff.summary()) # ## Multinomial Logit # Load data from the American National Election Studies: anes_data = sm.datasets.anes96.load() anes_exog = anes_data.exog anes_exog = sm.add_constant(anes_exog, prepend=False) # Inspect the data: print(anes_data.exog[:5, :]) print(anes_data.endog[:5]) # Fit MNL model: mlogit_mod = sm.MNLogit(anes_data.endog, anes_exog) mlogit_res = mlogit_mod.fit() print(mlogit_res.params) # ## Poisson # # Load the Rand data. Note that this example is similar to Cameron and # Trivedi's `Microeconometrics` Table 20.5, but it is slightly different # because of minor changes in the data. rand_data = sm.datasets.randhie.load() rand_exog = rand_data.exog.view(float).reshape(len(rand_data.exog), -1) rand_exog = sm.add_constant(rand_exog, prepend=False) # Fit Poisson model: poisson_mod = sm.Poisson(rand_data.endog, rand_exog) poisson_res = poisson_mod.fit(method="newton") print(poisson_res.summary()) # ## Negative Binomial # # The negative binomial model gives slightly different results. mod_nbin = sm.NegativeBinomial(rand_data.endog, rand_exog) res_nbin = mod_nbin.fit(disp=False) print(res_nbin.summary()) # ## Alternative solvers # # The default method for fitting discrete data MLE models is Newton- # Raphson. You can use other solvers by using the ``method`` argument: mlogit_res = mlogit_mod.fit(method='bfgs', maxiter=100) print(mlogit_res.summary())
vrenaville/ngo-addons-backport
refs/heads/master
addons/delivery/stock.py
2
# -*- 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 _ import openerp.addons.decimal_precision as dp # Overloaded stock_picking to manage carriers : class stock_picking(osv.osv): _inherit = 'stock.picking' def _cal_weight(self, cr, uid, ids, name, args, context=None): res = {} uom_obj = self.pool.get('product.uom') for picking in self.browse(cr, uid, ids, context=context): total_weight = total_weight_net = 0.00 for move in picking.move_lines: total_weight += move.weight total_weight_net += move.weight_net res[picking.id] = { 'weight': total_weight, 'weight_net': total_weight_net, } return res def _get_picking_line(self, cr, uid, ids, context=None): result = {} for line in self.pool.get('stock.move').browse(cr, uid, ids, context=context): result[line.picking_id.id] = True return result.keys() def write(self, cr, uid, ids, vals, context=None): if context is None: context = {} if vals.get('backorder_id'): vals.update(carrier_tracking_ref = '') return super(stock_picking, self).write(cr, uid, ids, vals, context=context) _columns = { 'carrier_id':fields.many2one("delivery.carrier","Carrier"), 'volume': fields.float('Volume'), 'weight': fields.function(_cal_weight, type='float', string='Weight', digits_compute= dp.get_precision('Stock Weight'), multi='_cal_weight', store={ 'stock.picking': (lambda self, cr, uid, ids, c={}: ids, ['move_lines'], 20), 'stock.move': (_get_picking_line, ['product_id','product_qty','product_uom','product_uos_qty'], 20), }), 'weight_net': fields.function(_cal_weight, type='float', string='Net Weight', digits_compute= dp.get_precision('Stock Weight'), multi='_cal_weight', store={ 'stock.picking': (lambda self, cr, uid, ids, c={}: ids, ['move_lines'], 20), 'stock.move': (_get_picking_line, ['product_id','product_qty','product_uom','product_uos_qty'], 20), }), 'carrier_tracking_ref': fields.char('Carrier Tracking Ref', size=32), 'number_of_packages': fields.integer('Number of Packages'), 'weight_uom_id': fields.many2one('product.uom', 'Unit of Measure', required=True,readonly="1",help="Unit of measurement for Weight",), } def _prepare_shipping_invoice_line(self, cr, uid, picking, invoice, context=None): """Prepare the invoice line to add to the shipping costs to the shipping's invoice. :param browse_record picking: the stock picking being invoiced :param browse_record invoice: the stock picking's invoice :return: dict containing the values to create the invoice line, or None to create nothing """ carrier_obj = self.pool.get('delivery.carrier') grid_obj = self.pool.get('delivery.grid') if not picking.carrier_id or \ any(inv_line.product_id.id == picking.carrier_id.product_id.id for inv_line in invoice.invoice_line): return None grid_id = carrier_obj.grid_get(cr, uid, [picking.carrier_id.id], picking.partner_id.id, context=context) if not grid_id: raise osv.except_osv(_('Warning!'), _('The carrier %s (id: %d) has no delivery grid!') \ % (picking.carrier_id.name, picking.carrier_id.id)) price = grid_obj.get_price_from_picking(cr, uid, grid_id, invoice.amount_untaxed, picking.weight, picking.volume, context=context) account_id = picking.carrier_id.product_id.property_account_income.id if not account_id: account_id = picking.carrier_id.product_id.categ_id\ .property_account_income_categ.id taxes = picking.carrier_id.product_id.taxes_id partner = picking.partner_id or False if partner: account_id = self.pool.get('account.fiscal.position').map_account(cr, uid, partner.property_account_position, account_id) taxes_ids = self.pool.get('account.fiscal.position').map_tax(cr, uid, partner.property_account_position, taxes) else: taxes_ids = [x.id for x in taxes] return { 'name': picking.carrier_id.name, 'invoice_id': invoice.id, 'uos_id': picking.carrier_id.product_id.uos_id.id, 'product_id': picking.carrier_id.product_id.id, 'account_id': account_id, 'price_unit': price, 'quantity': 1, 'invoice_line_tax_id': [(6, 0, taxes_ids)], } def action_invoice_create(self, cr, uid, ids, journal_id=False, group=False, type='out_invoice', context=None): invoice_obj = self.pool.get('account.invoice') picking_obj = self.pool.get('stock.picking') invoice_line_obj = self.pool.get('account.invoice.line') result = super(stock_picking, self).action_invoice_create(cr, uid, ids, journal_id=journal_id, group=group, type=type, context=context) for picking in picking_obj.browse(cr, uid, result.keys(), context=context): invoice = invoice_obj.browse(cr, uid, result[picking.id], context=context) invoice_line = self._prepare_shipping_invoice_line(cr, uid, picking, invoice, context=context) if invoice_line: invoice_line_obj.create(cr, uid, invoice_line) invoice_obj.button_compute(cr, uid, [invoice.id], context=context) return result def _get_default_uom(self,cr,uid,c): uom_categ, uom_categ_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'product', 'product_uom_categ_kgm') return self.pool.get('product.uom').search(cr, uid, [('category_id', '=', uom_categ_id),('factor','=',1)])[0] _defaults = { 'weight_uom_id': lambda self,cr,uid,c: self._get_default_uom(cr,uid,c) } def copy(self, cr, uid, id, default=None, context=None): default = dict(default or {}, number_of_packages=0, carrier_tracking_ref=False, volume=0.0) return super(stock_picking, self).copy(cr, uid, id, default=default, context=context) def do_partial(self, cr, uid, ids, partial_datas, context=None): res = super(stock_picking, self).do_partial(cr, uid, ids, partial_datas, context=context) for backorder_id, picking_vals in res.iteritems(): if backorder_id != picking_vals.get('delivered_picking'): # delivery info is set on backorder but not on new picking backorder = self.browse(cr, uid, backorder_id, context=context) self.write(cr, uid, picking_vals['delivered_picking'], { 'carrier_tracking_ref': backorder.carrier_tracking_ref, 'number_of_packages': backorder.number_of_packages, 'volume': backorder.volume, }, context=context) # delivery info are not relevant to backorder self.write(cr, uid, backorder_id, { 'carrier_tracking_ref': False, 'number_of_packages': 0, 'volume': 0, }, context=context) return res class stock_move(osv.osv): _inherit = 'stock.move' def _cal_move_weight(self, cr, uid, ids, name, args, context=None): res = {} uom_obj = self.pool.get('product.uom') for move in self.browse(cr, uid, ids, context=context): weight = weight_net = 0.00 if move.product_id.weight > 0.00: converted_qty = move.product_qty if move.product_uom.id <> move.product_id.uom_id.id: converted_qty = uom_obj._compute_qty(cr, uid, move.product_uom.id, move.product_qty, move.product_id.uom_id.id) weight = (converted_qty * move.product_id.weight) if move.product_id.weight_net > 0.00: weight_net = (converted_qty * move.product_id.weight_net) res[move.id] = { 'weight': weight, 'weight_net': weight_net, } return res def _prepare_chained_picking(self, cr, uid, picking_name, picking, picking_type, moves_todo, context=None): values = super(stock_move, self)._prepare_chained_picking(cr, uid, picking_name, picking, picking_type, moves_todo, context=context) if picking.carrier_id: values['carrier_id'] = picking.carrier_id.id values['volume'] = picking.volume values['weight'] = picking.weight values['weight_net'] = picking.weight_net values['carrier_tracking_ref'] = picking.carrier_tracking_ref values['number_of_packages'] = picking.number_of_packages return values _columns = { 'weight': fields.function(_cal_move_weight, type='float', string='Weight', digits_compute= dp.get_precision('Stock Weight'), multi='_cal_move_weight', store={ 'stock.move': (lambda self, cr, uid, ids, c=None: ids, ['product_id', 'product_qty', 'product_uom'], 20), }), 'weight_net': fields.function(_cal_move_weight, type='float', string='Net weight', digits_compute= dp.get_precision('Stock Weight'), multi='_cal_move_weight', store={ 'stock.move': (lambda self, cr, uid, ids, c=None: ids, ['product_id', 'product_qty', 'product_uom'], 20), }), 'weight_uom_id': fields.many2one('product.uom', 'Unit of Measure', required=True,readonly="1",help="Unit of Measure (Unit of Measure) is the unit of measurement for Weight",), } def _get_default_uom(self,cr,uid,c): uom_categ, uom_categ_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'product', 'product_uom_categ_kgm') return self.pool.get('product.uom').search(cr, uid, [('category_id', '=', uom_categ_id),('factor','=',1)])[0] _defaults = { 'weight_uom_id': lambda self,cr,uid,c: self._get_default_uom(cr,uid,c) } stock_move() # Redefinition of the new fields in order to update the model stock.picking.out in the orm # FIXME: this is a temporary workaround because of a framework bug (ref: lp996816). It should be removed as soon as # the bug is fixed # TODO in trunk: Remove the duplication below using a mixin class! class stock_picking_out(osv.osv): _inherit = 'stock.picking.out' def _cal_weight(self, cr, uid, ids, name, args, context=None): return self.pool.get('stock.picking')._cal_weight(cr, uid, ids, name, args, context=context) def _get_picking_line(self, cr, uid, ids, context=None): return self.pool.get('stock.picking')._get_picking_line(cr, uid, ids, context=context) _columns = { 'carrier_id':fields.many2one("delivery.carrier","Carrier"), 'volume': fields.float('Volume'), 'weight': fields.function(_cal_weight, type='float', string='Weight', digits_compute= dp.get_precision('Stock Weight'), multi='_cal_weight', store={ 'stock.picking': (lambda self, cr, uid, ids, c={}: ids, ['move_lines'], 20), 'stock.move': (_get_picking_line, ['product_id','product_qty','product_uom','product_uos_qty'], 20), }), 'weight_net': fields.function(_cal_weight, type='float', string='Net Weight', digits_compute= dp.get_precision('Stock Weight'), multi='_cal_weight', store={ 'stock.picking': (lambda self, cr, uid, ids, c={}: ids, ['move_lines'], 20), 'stock.move': (_get_picking_line, ['product_id','product_qty','product_uom','product_uos_qty'], 20), }), 'carrier_tracking_ref': fields.char('Carrier Tracking Ref', size=32), 'number_of_packages': fields.integer('Number of Packages'), 'weight_uom_id': fields.many2one('product.uom', 'Unit of Measure', required=True,readonly="1",help="Unit of measurement for Weight",), } stock_picking_out() class stock_picking_in(osv.osv): _inherit = 'stock.picking.in' def _cal_weight(self, cr, uid, ids, name, args, context=None): return self.pool.get('stock.picking')._cal_weight(cr, uid, ids, name, args, context=context) def _get_picking_line(self, cr, uid, ids, context=None): return self.pool.get('stock.picking')._get_picking_line(cr, uid, ids, context=context) _columns = { 'carrier_id':fields.many2one("delivery.carrier","Carrier"), 'volume': fields.float('Volume'), 'weight': fields.function(_cal_weight, type='float', string='Weight', digits_compute= dp.get_precision('Stock Weight'), multi='_cal_weight', store={ 'stock.picking': (lambda self, cr, uid, ids, c={}: ids, ['move_lines'], 20), 'stock.move': (_get_picking_line, ['product_id','product_qty','product_uom','product_uos_qty'], 20), }), 'weight_net': fields.function(_cal_weight, type='float', string='Net Weight', digits_compute= dp.get_precision('Stock Weight'), multi='_cal_weight', store={ 'stock.picking': (lambda self, cr, uid, ids, c={}: ids, ['move_lines'], 20), 'stock.move': (_get_picking_line, ['product_id','product_qty','product_uom','product_uos_qty'], 20), }), 'carrier_tracking_ref': fields.char('Carrier Tracking Ref', size=32), 'number_of_packages': fields.integer('Number of Packages'), 'weight_uom_id': fields.many2one('product.uom', 'Unit of Measure', required=True,readonly="1",help="Unit of measurement for Weight",), } stock_picking_in() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
mollstam/UnrealPy
refs/heads/master
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/boto-2.38.0/tests/unit/dynamodb2/test_layer1.py
126
# Copyright (c) 2013 Amazon.com, Inc. or its affiliates. # All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. """ Tests for Layer1 of DynamoDB v2 """ from tests.unit import unittest from boto.dynamodb2.layer1 import DynamoDBConnection from boto.regioninfo import RegionInfo class DynamoDBv2Layer1UnitTest(unittest.TestCase): dynamodb = True def test_init_region(self): dynamodb = DynamoDBConnection( aws_access_key_id='aws_access_key_id', aws_secret_access_key='aws_secret_access_key') self.assertEqual(dynamodb.region.name, 'us-east-1') dynamodb = DynamoDBConnection( region=RegionInfo(name='us-west-2', endpoint='dynamodb.us-west-2.amazonaws.com'), aws_access_key_id='aws_access_key_id', aws_secret_access_key='aws_secret_access_key', ) self.assertEqual(dynamodb.region.name, 'us-west-2') def test_init_host_override(self): dynamodb = DynamoDBConnection( aws_access_key_id='aws_access_key_id', aws_secret_access_key='aws_secret_access_key', host='localhost', port=8000) self.assertEqual(dynamodb.host, 'localhost') self.assertEqual(dynamodb.port, 8000)
dlazz/ansible
refs/heads/devel
lib/ansible/modules/cloud/amazon/aws_region_facts.py
34
#!/usr/bin/python # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = { 'metadata_version': '1.1', 'supported_by': 'community', 'status': ['preview'] } DOCUMENTATION = ''' module: aws_region_facts short_description: Gather facts about AWS regions. description: - Gather facts about AWS regions. version_added: '2.5' author: 'Henrique Rodrigues (@Sodki)' options: filters: description: - A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeRegions.html) for possible filters. Filter names and values are case sensitive. You can also use underscores instead of dashes (-) in the filter keys, which will take precedence in case of conflict. default: {} extends_documentation_fragment: - aws - ec2 requirements: [botocore, boto3] ''' EXAMPLES = ''' # Note: These examples do not set authentication details, see the AWS Guide for details. # Gather facts about all regions - aws_region_facts: # Gather facts about a single region - aws_region_facts: filters: region-name: eu-west-1 ''' RETURN = ''' regions: returned: on success description: > Regions that match the provided filters. Each element consists of a dict with all the information related to that region. type: list sample: "[{ 'endpoint': 'ec2.us-west-1.amazonaws.com', 'region_name': 'us-west-1' }]" ''' import traceback from ansible.module_utils._text import to_native from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import get_aws_connection_info, ec2_argument_spec, boto3_conn from ansible.module_utils.ec2 import ansible_dict_to_boto3_filter_list, camel_dict_to_snake_dict, HAS_BOTO3 try: from botocore.exceptions import ClientError, BotoCoreError except ImportError: pass # will be detected by imported HAS_BOTO3 def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( filters=dict(default={}, type='dict') ) ) module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) connection = boto3_conn( module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_params ) # Replace filter key underscores with dashes, for compatibility sanitized_filters = dict((k.replace('_', '-'), v) for k, v in module.params.get('filters').items()) try: regions = connection.describe_regions( Filters=ansible_dict_to_boto3_filter_list(sanitized_filters) ) except ClientError as e: module.fail_json(msg="Unable to describe regions: {0}".format(to_native(e)), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) except BotoCoreError as e: module.fail_json(msg="Unable to describe regions: {0}".format(to_native(e)), exception=traceback.format_exc()) module.exit_json(regions=[camel_dict_to_snake_dict(r) for r in regions['Regions']]) if __name__ == '__main__': main()
ttsirkia/a-plus
refs/heads/master
exercise/api/full_serializers.py
2
from rest_framework import serializers from rest_framework_extensions.fields import NestedHyperlinkedIdentityField from lib.api.serializers import ( AlwaysListSerializer, CompositeListSerializer, AplusSerializerMeta, AplusModelSerializerBase, ) from course.api.serializers import CourseBriefSerializer from userprofile.api.serializers import UserBriefSerializer, UserListField from ..models import Submission from .serializers import ( ExerciseBriefSerializer, SubmissionBriefSerializer, SubmittedFileBriefSerializer, ) __all__ = [ 'ExerciseSerializer', 'ExerciseGraderSerializer', 'SubmissionSerializer', 'SubmissionGraderSerializer', ] class ExerciseSerializer(ExerciseBriefSerializer): course = CourseBriefSerializer(source='course_instance') post_url = serializers.SerializerMethodField() exercise_info = serializers.JSONField() submissions = NestedHyperlinkedIdentityField( view_name='api:exercise-submissions-list', lookup_map='exercise.api.views.ExerciseViewSet', ) my_submissions = NestedHyperlinkedIdentityField( view_name='api:exercise-submissions-detail', lookup_map={ 'exercise_id': 'id', 'user_id': lambda o=None: 'me', }, ) my_stats = NestedHyperlinkedIdentityField( view_name='api:exercise-submitter_stats-detail', lookup_map={ 'exercise_id': 'id', 'user_id': lambda o=None: 'me', }, ) def get_post_url(self, obj): # FIXME: obj should implement .get_post_url() and that should be used here if obj.is_submittable: request = self.context['request'] url = obj.get_url("exercise") return request.build_absolute_uri(url) return None class Meta(ExerciseBriefSerializer.Meta): fields = ( 'name', 'course', 'is_submittable', 'post_url', 'max_points', 'max_submissions', 'exercise_info', 'templates', 'submissions', 'my_submissions', 'my_stats', ) class ExerciseGraderSerializer(AplusModelSerializerBase): url = NestedHyperlinkedIdentityField( view_name='api:exercise-grader', lookup_map='exercise.api.views.ExerciseViewSet', ) exercise = ExerciseBriefSerializer(source='*') class Meta(AplusSerializerMeta): model = Submission fields = ( 'url', 'exercise', ) class SubmitterLinks(AlwaysListSerializer, UserBriefSerializer): pass class SubmittedFileLinks(AlwaysListSerializer, SubmittedFileBriefSerializer): pass class SubmissionSerializer(SubmissionBriefSerializer): exercise = ExerciseBriefSerializer() submitters = SubmitterLinks() submission_data = serializers.JSONField() files = SubmittedFileLinks() grader = UserBriefSerializer() grading_data = serializers.JSONField() class Meta(SubmissionBriefSerializer.Meta): fields = ( 'html_url', 'exercise', 'submitters', 'submission_data', 'files', 'status', 'grade', 'late_penalty_applied', 'grading_time', 'grader', 'feedback', 'assistant_feedback', 'grading_data', ) class SubmissionInGraderSerializer(SubmissionBriefSerializer): class Meta(SubmissionBriefSerializer.Meta): fields = ( 'html_url', ) class SubmissionGraderSerializer(AplusModelSerializerBase): url = NestedHyperlinkedIdentityField( view_name='api:submission-grader', lookup_map='exercise.api.views.SubmissionViewSet', ) submission = SubmissionInGraderSerializer(source='*') exercise = ExerciseBriefSerializer() class Meta(AplusSerializerMeta): model = Submission fields = ( 'url', 'submission', 'exercise', 'grading_data', 'is_graded', )
elpaso/QGIS
refs/heads/master
python/plugins/processing/tests/GdalAlgorithmsRasterTest.py
6
# -*- coding: utf-8 -*- """ *************************************************************************** GdalAlgorithmRasterTest.py --------------------- Date : January 2016 Copyright : (C) 2016 by Matthias Kuhn Email : matthias@opengis.ch *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Matthias Kuhn' __date__ = 'January 2016' __copyright__ = '(C) 2016, Matthias Kuhn' import nose2 import os import shutil import tempfile from qgis.core import (QgsProcessingContext, QgsProcessingFeedback, QgsRectangle) from qgis.testing import (start_app, unittest) import AlgorithmsTestBase from processing.algs.gdal.AssignProjection import AssignProjection from processing.algs.gdal.ClipRasterByExtent import ClipRasterByExtent from processing.algs.gdal.ClipRasterByMask import ClipRasterByMask from processing.algs.gdal.ColorRelief import ColorRelief from processing.algs.gdal.GridAverage import GridAverage from processing.algs.gdal.GridDataMetrics import GridDataMetrics from processing.algs.gdal.GridInverseDistance import GridInverseDistance from processing.algs.gdal.GridInverseDistanceNearestNeighbor import GridInverseDistanceNearestNeighbor from processing.algs.gdal.GridLinear import GridLinear from processing.algs.gdal.GridNearestNeighbor import GridNearestNeighbor from processing.algs.gdal.gdal2tiles import gdal2tiles from processing.algs.gdal.gdalcalc import gdalcalc from processing.algs.gdal.gdaltindex import gdaltindex from processing.algs.gdal.contour import contour from processing.algs.gdal.gdalinfo import gdalinfo from processing.algs.gdal.hillshade import hillshade from processing.algs.gdal.aspect import aspect from processing.algs.gdal.buildvrt import buildvrt from processing.algs.gdal.proximity import proximity from processing.algs.gdal.rasterize import rasterize from processing.algs.gdal.retile import retile from processing.algs.gdal.translate import translate from processing.algs.gdal.warp import warp from processing.algs.gdal.fillnodata import fillnodata from processing.algs.gdal.rearrange_bands import rearrange_bands from processing.algs.gdal.gdaladdo import gdaladdo from processing.algs.gdal.sieve import sieve from processing.algs.gdal.gdal2xyz import gdal2xyz from processing.algs.gdal.polygonize import polygonize from processing.algs.gdal.pansharp import pansharp from processing.algs.gdal.merge import merge from processing.algs.gdal.nearblack import nearblack from processing.algs.gdal.slope import slope from processing.algs.gdal.rasterize_over import rasterize_over from processing.algs.gdal.rasterize_over_fixed_value import rasterize_over_fixed_value from processing.algs.gdal.viewshed import viewshed testDataPath = os.path.join(os.path.dirname(__file__), 'testdata') class TestGdalRasterAlgorithms(unittest.TestCase, AlgorithmsTestBase.AlgorithmsTest): @classmethod def setUpClass(cls): start_app() from processing.core.Processing import Processing Processing.initialize() cls.cleanup_paths = [] @classmethod def tearDownClass(cls): for path in cls.cleanup_paths: shutil.rmtree(path) def test_definition_file(self): return 'gdal_algorithm_raster_tests.yaml' def testAssignProjection(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = AssignProjection() alg.initAlgorithm() # with target srs self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'CRS': 'EPSG:3111'}, context, feedback), ['gdal_edit.py', '-a_srs EPSG:3111 ' + source]) # with target using proj string custom_crs = 'proj4: +proj=utm +zone=36 +south +a=6378249.145 +b=6356514.966398753 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs' self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'CRS': custom_crs}, context, feedback), ['gdal_edit.py', '-a_srs EPSG:20936 ' + source]) # with target using custom projection custom_crs = 'proj4: +proj=utm +zone=36 +south +a=63785 +b=6357 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs' self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'CRS': custom_crs}, context, feedback), ['gdal_edit.py', '-a_srs "+proj=utm +zone=36 +south +a=63785 +b=6357 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs" ' + source]) # with non-EPSG crs code self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'CRS': 'POSTGIS:3111'}, context, feedback), ['gdal_edit.py', '-a_srs EPSG:3111 ' + source]) def testGdalTranslate(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') translate_alg = translate() translate_alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # without NODATA value self.assertEqual( translate_alg.getConsoleCommands({'INPUT': source, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with None NODATA value self.assertEqual( translate_alg.getConsoleCommands({'INPUT': source, 'NODATA': None, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with NODATA value self.assertEqual( translate_alg.getConsoleCommands({'INPUT': source, 'NODATA': 9999, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-a_nodata 9999.0 ' + '-of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value self.assertEqual( translate_alg.getConsoleCommands({'INPUT': source, 'NODATA': 0, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-a_nodata 0.0 ' + '-of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value and custom data type self.assertEqual( translate_alg.getConsoleCommands({'INPUT': source, 'NODATA': 0, 'DATA_TYPE': 6, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-a_nodata 0.0 ' + '-ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with target srs self.assertEqual( translate_alg.getConsoleCommands({'INPUT': source, 'TARGET_CRS': 'EPSG:3111', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-a_srs EPSG:3111 ' + '-of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with target using proj string custom_crs = 'proj4: +proj=utm +zone=36 +south +a=6378249.145 +b=6356514.966398753 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs' self.assertEqual( translate_alg.getConsoleCommands({'INPUT': source, 'TARGET_CRS': custom_crs, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-a_srs EPSG:20936 ' + '-of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with target using custom projection custom_crs = 'proj4: +proj=utm +zone=36 +south +a=63785 +b=6357 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs' self.assertEqual( translate_alg.getConsoleCommands({'INPUT': source, 'TARGET_CRS': custom_crs, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-a_srs "+proj=utm +zone=36 +south +a=63785 +b=6357 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs" ' + '-of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with non-EPSG crs code self.assertEqual( translate_alg.getConsoleCommands({'INPUT': source, 'TARGET_CRS': 'POSTGIS:3111', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-a_srs EPSG:3111 ' + '-of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with copy subdatasets self.assertEqual( translate_alg.getConsoleCommands({'INPUT': source, 'COPY_SUBDATASETS': True, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdal_translate', '-sds ' + '-of GTiff ' + source + ' ' + outdir + '/check.tif']) # additional parameters self.assertEqual( translate_alg.getConsoleCommands({'INPUT': source, 'EXTRA': '-strict -unscale -epo', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-of JPEG -strict -unscale -epo ' + source + ' ' + outdir + '/check.jpg']) def testClipRasterByExtent(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = ClipRasterByExtent() alg.initAlgorithm() extent = QgsRectangle(1, 2, 3, 4) with tempfile.TemporaryDirectory() as outdir: # with no NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTENT': extent, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-projwin 0.0 0.0 0.0 0.0 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTENT': extent, 'NODATA': 9999, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-projwin 0.0 0.0 0.0 0.0 -a_nodata 9999.0 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTENT': extent, 'NODATA': 0, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-projwin 0.0 0.0 0.0 0.0 -a_nodata 0.0 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value and custom data type self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTENT': extent, 'NODATA': 0, 'DATA_TYPE': 6, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-projwin 0.0 0.0 0.0 0.0 -a_nodata 0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with creation options self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTENT': extent, 'OPTIONS': 'COMPRESS=DEFLATE|PREDICTOR=2|ZLEVEL=9', 'DATA_TYPE': 0, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-projwin 0.0 0.0 0.0 0.0 -of JPEG -co COMPRESS=DEFLATE -co PREDICTOR=2 -co ZLEVEL=9 ' + source + ' ' + outdir + '/check.jpg']) # with additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTENT': extent, 'EXTRA': '-s_srs EPSG:4326 -tps -tr 0.1 0.1', 'DATA_TYPE': 0, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_translate', '-projwin 0.0 0.0 0.0 0.0 -of JPEG -s_srs EPSG:4326 -tps -tr 0.1 0.1 ' + source + ' ' + outdir + '/check.jpg']) def testClipRasterByMask(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') mask = os.path.join(testDataPath, 'polys.gml') alg = ClipRasterByMask() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # with no NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'MASK': mask, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-of JPEG -cutline ' + mask + ' -cl polys2 -crop_to_cutline ' + source + ' ' + outdir + '/check.jpg']) # with NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'MASK': mask, 'NODATA': 9999, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-of JPEG -cutline ' + mask + ' -cl polys2 -crop_to_cutline -dstnodata 9999.0 ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'MASK': mask, 'NODATA': 0, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-of JPEG -cutline ' + mask + ' -cl polys2 -crop_to_cutline -dstnodata 0.0 ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value and custom data type self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'MASK': mask, 'NODATA': 0, 'DATA_TYPE': 6, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-ot Float32 -of JPEG -cutline ' + mask + ' -cl polys2 -crop_to_cutline -dstnodata 0.0 ' + source + ' ' + outdir + '/check.jpg']) # with creation options self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'MASK': mask, 'OPTIONS': 'COMPRESS=DEFLATE|PREDICTOR=2|ZLEVEL=9', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-of JPEG -cutline ' + mask + ' -cl polys2 -crop_to_cutline -co COMPRESS=DEFLATE -co PREDICTOR=2 -co ZLEVEL=9 ' + source + ' ' + outdir + '/check.jpg']) # with multothreading and additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'MASK': mask, 'MULTITHREADING': True, 'EXTRA': '-nosrcalpha -wm 2048 -nomd', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-of JPEG -cutline ' + mask + ' -cl polys2 -crop_to_cutline -multi -nosrcalpha -wm 2048 -nomd ' + source + ' ' + outdir + '/check.jpg']) def testContour(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = contour() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # with no NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'FIELD_NAME': 'elev', 'INTERVAL': 5, 'OUTPUT': outdir + '/check.shp'}, context, feedback), ['gdal_contour', '-b 1 -a elev -i 5.0 -f "ESRI Shapefile" ' + source + ' ' + outdir + '/check.shp']) # with NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'FIELD_NAME': 'elev', 'INTERVAL': 5, 'NODATA': 9999, 'OUTPUT': outdir + '/check.shp'}, context, feedback), ['gdal_contour', '-b 1 -a elev -i 5.0 -snodata 9999.0 -f "ESRI Shapefile" ' + source + ' ' + outdir + '/check.shp']) # with "0" NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'FIELD_NAME': 'elev', 'INTERVAL': 5, 'NODATA': 0, 'OUTPUT': outdir + '/check.gpkg'}, context, feedback), ['gdal_contour', '-b 1 -a elev -i 5.0 -snodata 0.0 -f "GPKG" ' + source + ' ' + outdir + '/check.gpkg']) # with CREATE_3D self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'CREATE_3D': True, 'OUTPUT': outdir + '/check.shp'}, context, feedback), ['gdal_contour', '-b 1 -a ELEV -i 10.0 -3d -f "ESRI Shapefile" ' + source + ' ' + outdir + '/check.shp']) # with IGNORE_NODATA and OFFSET self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'IGNORE_NODATA': True, 'OFFSET': 100, 'OUTPUT': outdir + '/check.shp'}, context, feedback), ['gdal_contour', '-b 1 -a ELEV -i 10.0 -inodata -off 100.0 -f "ESRI Shapefile" ' + source + ' ' + outdir + '/check.shp']) # with additional command line parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'EXTRA': '-e 3 -amin MIN_H', 'OUTPUT': outdir + '/check.shp'}, context, feedback), ['gdal_contour', '-b 1 -a ELEV -i 10.0 -f "ESRI Shapefile" -e 3 -amin MIN_H ' + source + ' ' + outdir + '/check.shp']) # obsolete OPTIONS param self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'OPTIONS': '-fl 100 125 150 200', 'OUTPUT': outdir + '/check.shp'}, context, feedback), ['gdal_contour', '-b 1 -a ELEV -i 10.0 -f "ESRI Shapefile" -fl 100 125 150 200 ' + source + ' ' + outdir + '/check.shp']) def testGdal2Tiles(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = gdal2tiles() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # with no NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'OUTPUT': outdir + '/'}, context, feedback), ['gdal2tiles.py', '-p mercator -w all -r average ' + source + ' ' + outdir + '/']) # with NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': -9999, 'OUTPUT': outdir + '/'}, context, feedback), ['gdal2tiles.py', '-p mercator -w all -r average -a -9999.0 ' + source + ' ' + outdir + '/']) # with "0" NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 0, 'OUTPUT': outdir + '/'}, context, feedback), ['gdal2tiles.py', '-p mercator -w all -r average -a 0.0 ' + source + ' ' + outdir + '/']) # with input srs self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'SOURCE_CRS': 'EPSG:3111', 'OUTPUT': outdir + '/'}, context, feedback), ['gdal2tiles.py', '-p mercator -w all -r average -s EPSG:3111 ' + source + ' ' + outdir + '/']) # with target using proj string custom_crs = 'proj4: +proj=utm +zone=36 +south +a=6378249.145 +b=6356514.966398753 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs' self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'SOURCE_CRS': custom_crs, 'OUTPUT': outdir + '/'}, context, feedback), ['gdal2tiles.py', '-p mercator -w all -r average -s EPSG:20936 ' + source + ' ' + outdir + '/']) # with target using custom projection custom_crs = 'proj4: +proj=utm +zone=36 +south +a=63785 +b=6357 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs' self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'SOURCE_CRS': custom_crs, 'OUTPUT': outdir + '/'}, context, feedback), ['gdal2tiles.py', '-p mercator -w all -r average -s "+proj=utm +zone=36 +south +a=63785 +b=6357 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs" ' + source + ' ' + outdir + '/']) # with non-EPSG crs code self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'SOURCE_CRS': 'POSTGIS:3111', 'OUTPUT': outdir + '/'}, context, feedback), ['gdal2tiles.py', '-p mercator -w all -r average -s EPSG:3111 ' + source + ' ' + outdir + '/']) def testGdalCalc(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = gdalcalc() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: output = outdir + '/check.jpg' # default execution formula = 'A*2' # default formula self.assertEqual( alg.getConsoleCommands({'INPUT_A': source, 'BAND_A': 1, 'FORMULA': formula, 'OUTPUT': output}, context, feedback), ['gdal_calc.py', '--calc "{}" --format JPEG --type Float32 -A {} --A_band 1 --outfile {}'.format(formula, source, output)]) # check that formula is not escaped and formula is returned as it is formula = 'A * 2' # <--- add spaces in the formula self.assertEqual( alg.getConsoleCommands({'INPUT_A': source, 'BAND_A': 1, 'FORMULA': formula, 'OUTPUT': output}, context, feedback), ['gdal_calc.py', '--calc "{}" --format JPEG --type Float32 -A {} --A_band 1 --outfile {}'.format(formula, source, output)]) # additional creation options formula = 'A*2' self.assertEqual( alg.getConsoleCommands({'INPUT_A': source, 'BAND_A': 1, 'FORMULA': formula, 'OPTIONS': 'COMPRESS=JPEG|JPEG_QUALITY=75', 'OUTPUT': output}, context, feedback), ['gdal_calc.py', '--calc "{}" --format JPEG --type Float32 -A {} --A_band 1 --co COMPRESS=JPEG --co JPEG_QUALITY=75 --outfile {}'.format(formula, source, output)]) # additional parameters formula = 'A*2' self.assertEqual( alg.getConsoleCommands({'INPUT_A': source, 'BAND_A': 1, 'FORMULA': formula, 'EXTRA': '--debug --quiet', 'OUTPUT': output}, context, feedback), ['gdal_calc.py', '--calc "{}" --format JPEG --type Float32 -A {} --A_band 1 --debug --quiet --outfile {}'.format(formula, source, output)]) def testGdalInfo(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = gdalinfo() alg.initAlgorithm() self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'MIN_MAX': False, 'NOGCP': False, 'NO_METADATA': False, 'STATS': False}, context, feedback), ['gdalinfo', source]) source = os.path.join(testDataPath, 'raster with spaces.tif') self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'MIN_MAX': False, 'NOGCP': False, 'NO_METADATA': False, 'STATS': False}, context, feedback), ['gdalinfo', '"' + source + '"']) self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'MIN_MAX': True, 'NOGCP': False, 'NO_METADATA': False, 'STATS': False}, context, feedback), ['gdalinfo', '-mm "' + source + '"']) self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'MIN_MAX': False, 'NOGCP': True, 'NO_METADATA': False, 'STATS': False}, context, feedback), ['gdalinfo', '-nogcp "' + source + '"']) self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'MIN_MAX': False, 'NOGCP': False, 'NO_METADATA': True, 'STATS': False}, context, feedback), ['gdalinfo', '-nomd "' + source + '"']) self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'MIN_MAX': False, 'NOGCP': False, 'NO_METADATA': False, 'STATS': True}, context, feedback), ['gdalinfo', '-stats "' + source + '"']) self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'MIN_MAX': False, 'NOGCP': False, 'NO_METADATA': False, 'STATS': False, 'EXTRA': '-proj4 -listmdd -checksum'}, context, feedback), ['gdalinfo', '-proj4 -listmdd -checksum "' + source + '"']) def testGdalTindex(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = gdaltindex() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: commands = alg.getConsoleCommands({'LAYERS': [source], 'OUTPUT': outdir + '/test.shp'}, context, feedback) self.assertEqual(len(commands), 2) self.assertEqual(commands[0], 'gdaltindex') self.assertIn('-tileindex location -f "ESRI Shapefile" ' + outdir + '/test.shp', commands[1]) self.assertIn('--optfile ', commands[1]) # with input srs commands = alg.getConsoleCommands({'LAYERS': [source], 'TARGET_CRS': 'EPSG:3111', 'OUTPUT': outdir + '/test.shp'}, context, feedback) self.assertEqual(len(commands), 2) self.assertEqual(commands[0], 'gdaltindex') self.assertIn('-tileindex location -t_srs EPSG:3111 -f "ESRI Shapefile" ' + outdir + '/test.shp', commands[1]) self.assertIn('--optfile ', commands[1]) # with target using proj string custom_crs = 'proj4: +proj=utm +zone=36 +south +a=6378249.145 +b=6356514.966398753 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs' commands = alg.getConsoleCommands({'LAYERS': [source], 'TARGET_CRS': custom_crs, 'OUTPUT': outdir + '/test.shp'}, context, feedback) self.assertEqual(len(commands), 2) self.assertEqual(commands[0], 'gdaltindex') self.assertIn('-tileindex location -t_srs EPSG:20936 -f "ESRI Shapefile" ' + outdir + '/test.shp', commands[1]) self.assertIn('--optfile ', commands[1]) # with target using custom projection custom_crs = 'proj4: +proj=utm +zone=36 +south +a=63785 +b=6357 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs' commands = alg.getConsoleCommands({'LAYERS': [source], 'TARGET_CRS': custom_crs, 'OUTPUT': outdir + '/test.shp'}, context, feedback) self.assertEqual(len(commands), 2) self.assertEqual(commands[0], 'gdaltindex') self.assertIn('-tileindex location -t_srs "+proj=utm +zone=36 +south +a=63785 +b=6357 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs" -f "ESRI Shapefile" ' + outdir + '/test.shp', commands[1]) self.assertIn('--optfile ', commands[1]) # with non-EPSG crs code commands = alg.getConsoleCommands({'LAYERS': [source], 'TARGET_CRS': 'POSTGIS:3111', 'OUTPUT': outdir + '/test.shp'}, context, feedback) self.assertEqual(len(commands), 2) self.assertEqual(commands[0], 'gdaltindex') self.assertIn( '-tileindex location -t_srs EPSG:3111 -f "ESRI Shapefile" ' + outdir + '/test.shp', commands[1]) self.assertIn('--optfile ', commands[1]) def testGridAverage(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'points.gml') alg = GridAverage() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # with no NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a average:radius1=0.0:radius2=0.0:angle=0.0:min_points=0:nodata=0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 9999, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a average:radius1=0.0:radius2=0.0:angle=0.0:min_points=0:nodata=9999.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 0, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a average:radius1=0.0:radius2=0.0:angle=0.0:min_points=0:nodata=0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTRA': '-z_multiply 1.5 -outsize 1754 1394', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a average:radius1=0.0:radius2=0.0:angle=0.0:min_points=0:nodata=0.0 -ot Float32 -of JPEG -z_multiply 1.5 -outsize 1754 1394 ' + source + ' ' + outdir + '/check.jpg']) def testGridDataMetrics(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'points.gml') alg = GridDataMetrics() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # without NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a minimum:radius1=0.0:radius2=0.0:angle=0.0:min_points=0:nodata=0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 9999, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a minimum:radius1=0.0:radius2=0.0:angle=0.0:min_points=0:nodata=9999.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 0, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a minimum:radius1=0.0:radius2=0.0:angle=0.0:min_points=0:nodata=0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # non-default datametrics self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'METRIC': 4, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a average_distance:radius1=0.0:radius2=0.0:angle=0.0:min_points=0:nodata=0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTRA': '-z_multiply 1.5 -outsize 1754 1394', 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdal_grid', '-l points -a minimum:radius1=0.0:radius2=0.0:angle=0.0:min_points=0:nodata=0.0 ' + '-ot Float32 -of GTiff -z_multiply 1.5 -outsize 1754 1394 ' + source + ' ' + outdir + '/check.tif']) def testGridInverseDistance(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'points.gml') alg = GridInverseDistance() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # without NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a invdist:power=2.0:smothing=0.0:radius1=0.0:radius2=0.0:angle=0.0:max_points=0:min_points=0:nodata=0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 9999, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a invdist:power=2.0:smothing=0.0:radius1=0.0:radius2=0.0:angle=0.0:max_points=0:min_points=0:nodata=9999.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 0, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a invdist:power=2.0:smothing=0.0:radius1=0.0:radius2=0.0:angle=0.0:max_points=0:min_points=0:nodata=0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTRA': '-z_multiply 1.5 -outsize 1754 1394', 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdal_grid', '-l points -a invdist:power=2.0:smothing=0.0:radius1=0.0:radius2=0.0:angle=0.0:max_points=0:min_points=0:nodata=0.0 ' + '-ot Float32 -of GTiff -z_multiply 1.5 -outsize 1754 1394 ' + source + ' ' + outdir + '/check.tif']) def testGridInverseDistanceNearestNeighbour(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'points.gml') alg = GridInverseDistanceNearestNeighbor() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # without NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a invdistnn:power=2.0:smothing=0.0:radius=1.0:max_points=12:min_points=0:nodata=0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 9999, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a invdistnn:power=2.0:smothing=0.0:radius=1.0:max_points=12:min_points=0:nodata=9999.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 0, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a invdistnn:power=2.0:smothing=0.0:radius=1.0:max_points=12:min_points=0:nodata=0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTRA': '-z_multiply 1.5 -outsize 1754 1394', 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdal_grid', '-l points -a invdistnn:power=2.0:smothing=0.0:radius=1.0:max_points=12:min_points=0:nodata=0.0 ' + '-ot Float32 -of GTiff -z_multiply 1.5 -outsize 1754 1394 ' + source + ' ' + outdir + '/check.tif']) def testGridLinear(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'points.gml') alg = GridLinear() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # without NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a linear:radius=-1.0:nodata=0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 9999, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a linear:radius=-1.0:nodata=9999.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 0, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a linear:radius=-1.0:nodata=0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTRA': '-z_multiply 1.5 -outsize 1754 1394', 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdal_grid', '-l points -a linear:radius=-1.0:nodata=0.0 -ot Float32 -of GTiff ' + '-z_multiply 1.5 -outsize 1754 1394 ' + source + ' ' + outdir + '/check.tif']) def testGridNearestNeighbour(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'points.gml') alg = GridNearestNeighbor() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # without NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a nearest:radius1=0.0:radius2=0.0:angle=0.0:nodata=0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 9999, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a nearest:radius1=0.0:radius2=0.0:angle=0.0:nodata=9999.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 0, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_grid', '-l points -a nearest:radius1=0.0:radius2=0.0:angle=0.0:nodata=0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTRA': '-z_multiply 1.5 -outsize 1754 1394', 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdal_grid', '-l points -a nearest:radius1=0.0:radius2=0.0:angle=0.0:nodata=0.0 -ot Float32 -of GTiff ' + '-z_multiply 1.5 -outsize 1754 1394 ' + source + ' ' + outdir + '/check.tif']) def testHillshade(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = hillshade() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'Z_FACTOR': 5, 'SCALE': 2, 'AZIMUTH': 90, 'ALTITUDE': 20, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'hillshade ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -z 5.0 -s 2.0 -az 90.0 -alt 20.0']) # paths with space source_with_space = os.path.join(testDataPath, 'raster with spaces.tif') self.assertEqual( alg.getConsoleCommands({'INPUT': source_with_space, 'BAND': 1, 'Z_FACTOR': 5, 'SCALE': 2, 'AZIMUTH': 90, 'ALTITUDE': 20, 'OUTPUT': outdir + '/check out.tif'}, context, feedback), ['gdaldem', 'hillshade ' + '"' + source_with_space + '" ' + '"{}/check out.tif" -of GTiff -b 1 -z 5.0 -s 2.0 -az 90.0 -alt 20.0'.format(outdir)]) # compute edges self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'Z_FACTOR': 5, 'SCALE': 2, 'AZIMUTH': 90, 'ALTITUDE': 20, 'COMPUTE_EDGES': True, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'hillshade ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -z 5.0 -s 2.0 -az 90.0 -alt 20.0 -compute_edges']) # with ZEVENBERGEN self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'Z_FACTOR': 5, 'SCALE': 2, 'AZIMUTH': 90, 'ALTITUDE': 20, 'ZEVENBERGEN': True, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'hillshade ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -z 5.0 -s 2.0 -az 90.0 -alt 20.0 -alg ZevenbergenThorne']) # with COMBINED self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'Z_FACTOR': 5, 'SCALE': 2, 'AZIMUTH': 90, 'ALTITUDE': 20, 'COMBINED': True, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'hillshade ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -z 5.0 -s 2.0 -az 90.0 -alt 20.0 -combined']) # with multidirectional - "az" argument is not allowed! self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'Z_FACTOR': 5, 'SCALE': 2, 'AZIMUTH': 90, 'ALTITUDE': 20, 'MULTIDIRECTIONAL': True, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'hillshade ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -z 5.0 -s 2.0 -alt 20.0 -multidirectional']) # defaults with additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'EXTRA': '-q', 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'hillshade ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -z 1.0 -s 1.0 -az 315.0 -alt 45.0 -q']) def testAspect(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = aspect() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'TRIG_ANGLE': False, 'ZERO_FLAT': False, 'COMPUTE_EDGES': False, 'ZEVENBERGEN': False, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'aspect ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1']) # paths with space source_with_space = os.path.join(testDataPath, 'raster with spaces.tif') self.assertEqual( alg.getConsoleCommands({'INPUT': source_with_space, 'BAND': 1, 'TRIG_ANGLE': False, 'ZERO_FLAT': False, 'COMPUTE_EDGES': False, 'ZEVENBERGEN': False, 'OUTPUT': outdir + '/check out.tif'}, context, feedback), ['gdaldem', 'aspect ' + '"' + source_with_space + '" ' + '"{}/check out.tif" -of GTiff -b 1'.format(outdir)]) # compute edges self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'TRIG_ANGLE': False, 'ZERO_FLAT': False, 'COMPUTE_EDGES': True, 'ZEVENBERGEN': False, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'aspect ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -compute_edges']) # with ZEVENBERGEN self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'TRIG_ANGLE': False, 'ZERO_FLAT': False, 'COMPUTE_EDGES': False, 'ZEVENBERGEN': True, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'aspect ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -alg ZevenbergenThorne']) # with ZERO_FLAT self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'TRIG_ANGLE': False, 'ZERO_FLAT': True, 'COMPUTE_EDGES': False, 'ZEVENBERGEN': False, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'aspect ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -zero_for_flat']) # with TRIG_ANGLE self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'TRIG_ANGLE': True, 'ZERO_FLAT': False, 'COMPUTE_EDGES': False, 'ZEVENBERGEN': False, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'aspect ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -trigonometric']) # with creation options self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'TRIG_ANGLE': False, 'ZERO_FLAT': False, 'COMPUTE_EDGES': False, 'ZEVENBERGEN': False, 'OPTIONS': 'COMPRESS=JPEG|JPEG_QUALITY=75', 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'aspect ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -co COMPRESS=JPEG -co JPEG_QUALITY=75']) # with additional parameter self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'TRIG_ANGLE': False, 'ZERO_FLAT': False, 'COMPUTE_EDGES': False, 'ZEVENBERGEN': False, 'EXTRA': '-q', 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'aspect ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -q']) def testSlope(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = slope() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'slope ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -s 1.0']) # compute edges self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'COMPUTE_EDGES': True, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'slope ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -s 1.0 -compute_edges']) # with ZEVENBERGEN self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'ZEVENBERGEN': True, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'slope ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -s 1.0 -alg ZevenbergenThorne']) # custom ratio self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'SCALE': 2.0, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'slope ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -s 2.0']) # with creation options self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'OPTIONS': 'COMPRESS=JPEG|JPEG_QUALITY=75', 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'slope ' + source + ' ' + outdir + '/check.tif -of GTiff -b 1 -s 1.0 -co COMPRESS=JPEG -co JPEG_QUALITY=75']) # with additional parameter self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'EXTRA': '-q', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdaldem', 'slope ' + source + ' ' + outdir + '/check.jpg -of JPEG -b 1 -s 1.0 -q']) def testColorRelief(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') colorTable = os.path.join(testDataPath, 'colors.txt') alg = ColorRelief() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'COLOR_TABLE': colorTable, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'color-relief ' + source + ' ' + colorTable + ' ' + outdir + '/check.tif -of GTiff -b 1']) # paths with space source_with_space = os.path.join(testDataPath, 'raster with spaces.tif') self.assertEqual( alg.getConsoleCommands({'INPUT': source_with_space, 'BAND': 1, 'COLOR_TABLE': colorTable, 'OUTPUT': outdir + '/check out.tif'}, context, feedback), ['gdaldem', 'color-relief ' + '"' + source_with_space + '" ' + colorTable + ' ' + '"{}/check out.tif" -of GTiff -b 1'.format(outdir)]) # compute edges self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'COLOR_TABLE': colorTable, 'COMPUTE_EDGES': True, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'color-relief ' + source + ' ' + colorTable + ' ' + outdir + '/check.tif -of GTiff -b 1 -compute_edges']) # with custom matching mode self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'COLOR_TABLE': colorTable, 'MATCH_MODE': 1, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'color-relief ' + source + ' ' + colorTable + ' ' + outdir + '/check.tif -of GTiff -b 1 -nearest_color_entry']) # with creation options self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'COLOR_TABLE': colorTable, 'MATCH_MODE': 1, 'OPTIONS': 'COMPRESS=JPEG|JPEG_QUALITY=75', 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'color-relief ' + source + ' ' + colorTable + ' ' + outdir + '/check.tif -of GTiff -b 1 -nearest_color_entry -co COMPRESS=JPEG -co JPEG_QUALITY=75']) # with additional parameter self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'COLOR_TABLE': colorTable, 'EXTRA': '-alpha -q', 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdaldem', 'color-relief ' + source + ' ' + colorTable + ' ' + outdir + '/check.tif -of GTiff -b 1 -alpha -q']) def testProximity(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = proximity() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # without NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_proximity.py', '-srcband 1 -distunits PIXEL -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 9999, 'BAND': 2, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_proximity.py', '-srcband 2 -distunits PIXEL -nodata 9999.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 0, 'BAND': 1, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_proximity.py', '-srcband 1 -distunits PIXEL -nodata 0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'EXTRA': '-dstband 2 -values 3,4,12', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_proximity.py', '-srcband 1 -distunits PIXEL -ot Float32 -of JPEG -dstband 2 -values 3,4,12 ' + source + ' ' + outdir + '/check.jpg']) def testRasterize(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'polys.gml') alg = rasterize() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # with no NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'FIELD': 'id', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_rasterize', '-l polys2 -a id -ts 0.0 0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 9999, 'FIELD': 'id', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_rasterize', '-l polys2 -a id -ts 0.0 0.0 -a_nodata 9999.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" INIT value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'INIT': 0, 'FIELD': 'id', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_rasterize', '-l polys2 -a id -ts 0.0 0.0 -init 0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 0, 'FIELD': 'id', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_rasterize', '-l polys2 -a id -ts 0.0 0.0 -a_nodata 0.0 -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'FIELD': 'id', 'EXTRA': '-at -add', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdal_rasterize', '-l polys2 -a id -ts 0.0 0.0 -ot Float32 -of JPEG -at -add ' + source + ' ' + outdir + '/check.jpg']) def testRasterizeOver(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() raster = os.path.join(testDataPath, 'dem.tif') vector = os.path.join(testDataPath, 'polys.gml') alg = rasterize_over() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: self.assertEqual( alg.getConsoleCommands({'INPUT': vector, 'FIELD': 'id', 'INPUT_RASTER': raster}, context, feedback), ['gdal_rasterize', '-l polys2 -a id ' + vector + ' ' + raster]) self.assertEqual( alg.getConsoleCommands({'INPUT': vector, 'FIELD': 'id', 'ADD': True, 'INPUT_RASTER': raster}, context, feedback), ['gdal_rasterize', '-l polys2 -a id -add ' + vector + ' ' + raster]) self.assertEqual( alg.getConsoleCommands({'INPUT': vector, 'FIELD': 'id', 'EXTRA': '-i', 'INPUT_RASTER': raster}, context, feedback), ['gdal_rasterize', '-l polys2 -a id -i ' + vector + ' ' + raster]) def testRasterizeOverFixed(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() raster = os.path.join(testDataPath, 'dem.tif') vector = os.path.join(testDataPath, 'polys.gml') alg = rasterize_over_fixed_value() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: self.assertEqual( alg.getConsoleCommands({'INPUT': vector, 'BURN': 100, 'INPUT_RASTER': raster}, context, feedback), ['gdal_rasterize', '-l polys2 -burn 100.0 ' + vector + ' ' + raster]) self.assertEqual( alg.getConsoleCommands({'INPUT': vector, 'BURN': 100, 'ADD': True, 'INPUT_RASTER': raster}, context, feedback), ['gdal_rasterize', '-l polys2 -burn 100.0 -add ' + vector + ' ' + raster]) self.assertEqual( alg.getConsoleCommands({'INPUT': vector, 'BURN': 100, 'EXTRA': '-i', 'INPUT_RASTER': raster}, context, feedback), ['gdal_rasterize', '-l polys2 -burn 100.0 -i ' + vector + ' ' + raster]) def testRetile(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = retile() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: self.assertEqual( alg.getConsoleCommands({'INPUT': [source], 'OUTPUT': outdir}, context, feedback), ['gdal_retile.py', '-ps 256 256 -overlap 0 -levels 1 -r near -ot Float32 -targetDir {} '.format(outdir) + source]) # with input srs self.assertEqual( alg.getConsoleCommands({'INPUT': [source], 'SOURCE_CRS': 'EPSG:3111', 'OUTPUT': outdir}, context, feedback), ['gdal_retile.py', '-ps 256 256 -overlap 0 -levels 1 -s_srs EPSG:3111 -r near -ot Float32 -targetDir {} {}'.format(outdir, source) ]) # with target using proj string custom_crs = 'proj4: +proj=utm +zone=36 +south +a=6378249.145 +b=6356514.966398753 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs' self.assertEqual( alg.getConsoleCommands({'INPUT': [source], 'SOURCE_CRS': custom_crs, 'OUTPUT': outdir}, context, feedback), ['gdal_retile.py', '-ps 256 256 -overlap 0 -levels 1 -s_srs EPSG:20936 -r near -ot Float32 -targetDir {} {}'.format(outdir, source) ]) # with target using custom projection custom_crs = 'proj4: +proj=utm +zone=36 +south +a=63785 +b=6357 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs' self.assertEqual( alg.getConsoleCommands({'INPUT': [source], 'SOURCE_CRS': custom_crs, 'OUTPUT': outdir}, context, feedback), ['gdal_retile.py', '-ps 256 256 -overlap 0 -levels 1 -s_srs "+proj=utm +zone=36 +south +a=63785 +b=6357 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs" -r near -ot Float32 -targetDir {} {}'.format(outdir, source) ]) # with non-EPSG crs code self.assertEqual( alg.getConsoleCommands({'INPUT': [source], 'SOURCE_CRS': 'POSTGIS:3111', 'OUTPUT': outdir}, context, feedback), ['gdal_retile.py', '-ps 256 256 -overlap 0 -levels 1 -s_srs EPSG:3111 -r near -ot Float32 -targetDir {} {}'.format(outdir, source) ]) # additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': [source], 'EXTRA': '-v -tileIndex tindex.shp', 'OUTPUT': outdir}, context, feedback), ['gdal_retile.py', '-ps 256 256 -overlap 0 -levels 1 -r near -ot Float32 -v -tileIndex tindex.shp -targetDir {} '.format(outdir) + source]) def testWarp(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = warp() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # with no NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'SOURCE_CRS': 'EPSG:3111', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-s_srs EPSG:3111 -r near -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with None NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': None, 'SOURCE_CRS': 'EPSG:3111', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-s_srs EPSG:3111 -r near -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 9999, 'SOURCE_CRS': 'EPSG:3111', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-s_srs EPSG:3111 -dstnodata 9999.0 -r near -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 0, 'SOURCE_CRS': 'EPSG:3111', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-s_srs EPSG:3111 -dstnodata 0.0 -r near -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with "0" NODATA value and custom data type self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NODATA': 0, 'DATA_TYPE': 6, 'SOURCE_CRS': 'EPSG:3111', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-s_srs EPSG:3111 -dstnodata 0.0 -r near -ot Float32 -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with target using EPSG self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'SOURCE_CRS': 'EPSG:3111', 'TARGET_CRS': 'EPSG:4326', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-s_srs EPSG:3111 -t_srs EPSG:4326 -r near -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with target using proj string custom_crs = 'proj4: +proj=utm +zone=36 +south +a=6378249.145 +b=6356514.966398753 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs' self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'SOURCE_CRS': custom_crs, 'TARGET_CRS': custom_crs, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-s_srs EPSG:20936 -t_srs EPSG:20936 -r near -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with target using custom projection custom_crs = 'proj4: +proj=utm +zone=36 +south +a=63785 +b=6357 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs' self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'SOURCE_CRS': custom_crs, 'TARGET_CRS': custom_crs, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-s_srs "+proj=utm +zone=36 +south +a=63785 +b=6357 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs" -t_srs "+proj=utm +zone=36 +south +a=63785 +b=6357 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs" -r near -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with target using custom projection and user-defined extent custom_crs2 = 'proj4: +proj=longlat +a=6378388 +b=6356912 +no_defs' self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'SOURCE_CRS': custom_crs2, 'TARGET_CRS': custom_crs2, 'TARGET_EXTENT': '18.67,18.70,45.78,45.81', 'TARGET_EXTENT_CRS': custom_crs2, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['gdalwarp', '-s_srs "+proj=longlat +a=6378388 +b=6356912 +no_defs" -t_srs "+proj=longlat +a=6378388 +b=6356912 +no_defs" -r near -te 18.67 45.78 18.7 45.81 -te_srs "+proj=longlat +a=6378388 +b=6356912 +no_defs" -of GTiff ' + source + ' ' + outdir + '/check.tif']) # with non-EPSG crs code self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'SOURCE_CRS': 'POSTGIS:3111', 'TARGET_CRS': 'POSTGIS:3111', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-s_srs EPSG:3111 -t_srs EPSG:3111 -r near -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with target resolution with None value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'SOURCE_CRS': 'EPSG:3111', 'TARGET_RESOLUTION': None, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-s_srs EPSG:3111 -r near -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # test target resolution with a valid value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'SOURCE_CRS': 'EPSG:3111', 'TARGET_RESOLUTION': 10.0, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-s_srs EPSG:3111 -tr 10.0 10.0 -r near -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # test target resolution with a value of zero, to be ignored self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'SOURCE_CRS': 'EPSG:3111', 'TARGET_RESOLUTION': 0.0, 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-s_srs EPSG:3111 -r near -of JPEG ' + source + ' ' + outdir + '/check.jpg']) # with additional command-line parameter self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTRA': '-dstalpha', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-r near -of JPEG -dstalpha ' + source + ' ' + outdir + '/check.jpg']) self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTRA': '-dstalpha -srcnodata -9999', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-r near -of JPEG -dstalpha -srcnodata -9999 ' + source + ' ' + outdir + '/check.jpg']) self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTRA': '-dstalpha -srcnodata "-9999 -8888"', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-r near -of JPEG -dstalpha -srcnodata "-9999 -8888" ' + source + ' ' + outdir + '/check.jpg']) self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTRA': '', 'OUTPUT': outdir + '/check.jpg'}, context, feedback), ['gdalwarp', '-r near -of JPEG ' + source + ' ' + outdir + '/check.jpg']) def testMerge(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = [os.path.join(testDataPath, 'dem1.tif'), os.path.join(testDataPath, 'dem1.tif')] alg = merge() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # this algorithm creates temporary text file with input layers # so we strip its path, leaving only filename cmd = alg.getConsoleCommands({'INPUT': source, 'OUTPUT': outdir + '/check.tif'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('--optfile') + 10] + t[t.find('mergeInputFiles.txt'):] self.assertEqual(cmd, ['gdal_merge.py', '-ot Float32 -of GTiff ' + '-o ' + outdir + '/check.tif ' + '--optfile mergeInputFiles.txt']) # separate cmd = alg.getConsoleCommands({'INPUT': source, 'SEPARATE': True, 'OUTPUT': outdir + '/check.tif'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('--optfile') + 10] + t[t.find('mergeInputFiles.txt'):] self.assertEqual(cmd, ['gdal_merge.py', '-separate -ot Float32 -of GTiff ' + '-o ' + outdir + '/check.tif ' + '--optfile mergeInputFiles.txt']) # assign nodata cmd = alg.getConsoleCommands({'INPUT': source, 'EXTRA': '-tap -ps 0.1 0.1', 'OUTPUT': outdir + '/check.tif'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('--optfile') + 10] + t[t.find('mergeInputFiles.txt'):] self.assertEqual(cmd, ['gdal_merge.py', '-ot Float32 -of GTiff -tap -ps 0.1 0.1 ' + '-o ' + outdir + '/check.tif ' + '--optfile mergeInputFiles.txt']) # additional parameters cmd = alg.getConsoleCommands({'INPUT': source, 'NODATA_OUTPUT': -9999, 'OUTPUT': outdir + '/check.tif'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('--optfile') + 10] + t[t.find('mergeInputFiles.txt'):] self.assertEqual(cmd, ['gdal_merge.py', '-a_nodata -9999 -ot Float32 -of GTiff ' + '-o ' + outdir + '/check.tif ' + '--optfile mergeInputFiles.txt']) def testNearblack(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = nearblack() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # defaults self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['nearblack', source + ' -of GTiff -o ' + outdir + '/check.tif ' + '-near 15']) # search white pixels self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'WHITE': True, 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['nearblack', source + ' -of GTiff -o ' + outdir + '/check.tif ' + '-near 15 -white']) # additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTRA': '-nb 5 -setalpha', 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['nearblack', source + ' -of GTiff -o ' + outdir + '/check.tif ' + '-near 15 -nb 5 -setalpha']) # additional parameters and creation options self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'OPTIONS': 'COMPRESS=JPEG|JPEG_QUALITY=75', 'EXTRA': '-nb 5 -setalpha', 'OUTPUT': outdir + '/check.tif'}, context, feedback), ['nearblack', source + ' -of GTiff -o ' + outdir + '/check.tif ' + '-near 15 -co COMPRESS=JPEG -co JPEG_QUALITY=75 -nb 5 -setalpha']) def testRearrangeBands(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') with tempfile.TemporaryDirectory() as outdir: outsource = outdir + '/check.tif' alg = rearrange_bands() alg.initAlgorithm() # single band self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BANDS': 1, 'OUTPUT': outsource}, context, feedback), ['gdal_translate', '-b 1 ' + '-of GTiff ' + source + ' ' + outsource]) # three bands, re-ordered self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BANDS': [3, 2, 1], 'OUTPUT': outsource}, context, feedback), ['gdal_translate', '-b 3 -b 2 -b 1 ' + '-of GTiff ' + source + ' ' + outsource]) # three bands, re-ordered with custom data type self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BANDS': [3, 2, 1], 'DATA_TYPE': 6, 'OUTPUT': outsource}, context, feedback), ['gdal_translate', '-b 3 -b 2 -b 1 ' + '-ot Float32 -of GTiff ' + source + ' ' + outsource]) def testFillnodata(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') mask = os.path.join(testDataPath, 'raster.tif') with tempfile.TemporaryDirectory() as outdir: outsource = outdir + '/check.tif' alg = fillnodata() alg.initAlgorithm() # with mask value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'DISTANCE': 10, 'ITERATIONS': 0, 'MASK_LAYER': mask, 'NO_MASK': False, 'OUTPUT': outsource}, context, feedback), ['gdal_fillnodata.py', '-md 10 -b 1 -mask ' + mask + ' -of GTiff ' + source + ' ' + outsource]) # without mask value self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'DISTANCE': 10, 'ITERATIONS': 0, 'NO_MASK': False, 'OUTPUT': outsource}, context, feedback), ['gdal_fillnodata.py', '-md 10 -b 1 ' + '-of GTiff ' + source + ' ' + outsource]) # nomask true self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'DISTANCE': 10, 'ITERATIONS': 0, 'NO_MASK': True, 'OUTPUT': outsource}, context, feedback), ['gdal_fillnodata.py', '-md 10 -b 1 -nomask ' + '-of GTiff ' + source + ' ' + outsource]) # creation options self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'OPTIONS': 'COMPRESS=JPEG|JPEG_QUALITY=75', 'OUTPUT': outsource}, context, feedback), ['gdal_fillnodata.py', '-md 10 -b 1 -of GTiff -co COMPRESS=JPEG -co JPEG_QUALITY=75 ' + source + ' ' + outsource]) # additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'EXTRA': '-q', 'OUTPUT': outsource}, context, feedback), ['gdal_fillnodata.py', '-md 10 -b 1 -of GTiff -q ' + source + ' ' + outsource]) def testGdalAddo(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') with tempfile.TemporaryDirectory() as outdir: alg = gdaladdo() alg.initAlgorithm() # defaults self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'LEVELS': '2 4 8 16', 'CLEAN': False, 'RESAMPLING': 0, 'FORMAT': 0}, context, feedback), ['gdaladdo', source + ' ' + '-r nearest 2 4 8 16']) # with "clean" option self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'LEVELS': '2 4 8 16', 'CLEAN': True, 'RESAMPLING': 0, 'FORMAT': 0}, context, feedback), ['gdaladdo', source + ' ' + '-r nearest -clean 2 4 8 16']) # ovr format self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'LEVELS': '2 4 8 16', 'CLEAN': False, 'RESAMPLING': 0, 'FORMAT': 1}, context, feedback), ['gdaladdo', source + ' ' + '-r nearest -ro 2 4 8 16']) # Erdas format self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'LEVELS': '2 4 8 16', 'CLEAN': False, 'RESAMPLING': 0, 'FORMAT': 2}, context, feedback), ['gdaladdo', source + ' ' + '-r nearest --config USE_RRD YES 2 4 8 16']) # custom resampling method format self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'LEVELS': '2 4 8 16', 'CLEAN': False, 'RESAMPLING': 4, 'FORMAT': 0}, context, feedback), ['gdaladdo', source + ' ' + '-r cubicspline 2 4 8 16']) # more levels self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'LEVELS': '2 4 8 16 32 64', 'CLEAN': False, 'RESAMPLING': 0, 'FORMAT': 0}, context, feedback), ['gdaladdo', source + ' ' + '-r nearest 2 4 8 16 32 64']) # additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'LEVELS': '2 4 8 16', 'CLEAN': False, 'EXTRA': '--config COMPRESS_OVERVIEW JPEG'}, context, feedback), ['gdaladdo', source + ' ' + '-r nearest --config COMPRESS_OVERVIEW JPEG 2 4 8 16']) # without advanced params self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'LEVELS': '2 4 8 16', 'CLEAN': False}, context, feedback), ['gdaladdo', source + ' ' + '-r nearest 2 4 8 16']) def testSieve(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') mask = os.path.join(testDataPath, 'raster.tif') with tempfile.TemporaryDirectory() as outdir: outsource = outdir + '/check.tif' alg = sieve() alg.initAlgorithm() # defaults self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'OUTPUT': outsource}, context, feedback), ['gdal_sieve.py', '-st 10 -4 -of GTiff ' + source + ' ' + outsource]) # Eight connectedness and custom threshold self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'THRESHOLD': 16, 'EIGHT_CONNECTEDNESS': True, 'OUTPUT': outsource}, context, feedback), ['gdal_sieve.py', '-st 16 -8 -of GTiff ' + source + ' ' + outsource]) # without default mask layer self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'NO_MASK': True, 'OUTPUT': outsource}, context, feedback), ['gdal_sieve.py', '-st 10 -4 -nomask -of GTiff ' + source + ' ' + outsource]) # defaults with external validity mask self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'MASK_LAYER': mask, 'OUTPUT': outsource}, context, feedback), ['gdal_sieve.py', '-st 10 -4 -mask ' + mask + ' -of GTiff ' + source + ' ' + outsource]) # additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'EXTRA': '-q', 'OUTPUT': outsource}, context, feedback), ['gdal_sieve.py', '-st 10 -4 -of GTiff -q ' + source + ' ' + outsource]) def testGdal2Xyz(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') with tempfile.TemporaryDirectory() as outdir: outsource = outdir + '/check.csv' alg = gdal2xyz() alg.initAlgorithm() # defaults self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'CSV': False, 'OUTPUT': outsource}, context, feedback), ['gdal2xyz.py', '-band 1 ' + source + ' ' + outsource]) # csv output self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'CSV': True, 'OUTPUT': outsource}, context, feedback), ['gdal2xyz.py', '-band 1 -csv ' + source + ' ' + outsource]) def testGdalPolygonize(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') with tempfile.TemporaryDirectory() as outdir: outsource = outdir + '/check.shp' alg = polygonize() alg.initAlgorithm() # defaults self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'FIELD': 'DN', 'EIGHT_CONNECTEDNESS': False, 'OUTPUT': outsource}, context, feedback), ['gdal_polygonize.py', source + ' ' + outsource + ' ' + '-b 1 -f "ESRI Shapefile" check DN' ]) self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'FIELD': 'VAL', 'EIGHT_CONNECTEDNESS': False, 'OUTPUT': outsource}, context, feedback), ['gdal_polygonize.py', source + ' ' + outsource + ' ' + '-b 1 -f "ESRI Shapefile" check VAL' ]) # 8 connectedness self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'FIELD': 'DN', 'EIGHT_CONNECTEDNESS': True, 'OUTPUT': outsource}, context, feedback), ['gdal_polygonize.py', source + ' ' + outsource + ' ' + '-8 -b 1 -f "ESRI Shapefile" check DN' ]) # custom output format outsource = outdir + '/check.gpkg' self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'FIELD': 'DN', 'EIGHT_CONNECTEDNESS': False, 'OUTPUT': outsource}, context, feedback), ['gdal_polygonize.py', source + ' ' + outsource + ' ' + '-b 1 -f "GPKG" check DN' ]) # additional parameters self.assertEqual( alg.getConsoleCommands({'INPUT': source, 'BAND': 1, 'FIELD': 'DN', 'EXTRA': '-nomask -q', 'OUTPUT': outsource}, context, feedback), ['gdal_polygonize.py', source + ' ' + outsource + ' ' + '-b 1 -f "GPKG" -nomask -q check DN' ]) def testGdalPansharpen(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() panchrom = os.path.join(testDataPath, 'dem.tif') spectral = os.path.join(testDataPath, 'raster.tif') with tempfile.TemporaryDirectory() as outdir: outsource = outdir + '/out.tif' alg = pansharp() alg.initAlgorithm() # defaults self.assertEqual( alg.getConsoleCommands({'SPECTRAL': spectral, 'PANCHROMATIC': panchrom, 'OUTPUT': outsource}, context, feedback), ['gdal_pansharpen.py', panchrom + ' ' + spectral + ' ' + outsource + ' ' + '-r cubic -of GTiff' ]) # custom resampling self.assertEqual( alg.getConsoleCommands({'SPECTRAL': spectral, 'PANCHROMATIC': panchrom, 'RESAMPLING': 4, 'OUTPUT': outsource}, context, feedback), ['gdal_pansharpen.py', panchrom + ' ' + spectral + ' ' + outsource + ' ' + '-r lanczos -of GTiff' ]) # additional parameters self.assertEqual( alg.getConsoleCommands({'SPECTRAL': spectral, 'PANCHROMATIC': panchrom, 'EXTRA': '-bitdepth 12 -threads ALL_CPUS', 'OUTPUT': outsource}, context, feedback), ['gdal_pansharpen.py', panchrom + ' ' + spectral + ' ' + outsource + ' ' + '-r cubic -of GTiff -bitdepth 12 -threads ALL_CPUS' ]) def testGdalViewshed(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() dem = os.path.join(testDataPath, 'dem.tif') with tempfile.TemporaryDirectory() as outdir: outsource = outdir + '/out.tif' alg = viewshed() alg.initAlgorithm() # defaults self.assertEqual( alg.getConsoleCommands({'INPUT': dem, 'BAND': 1, 'OBSERVER': '18.67274,45.80599', 'OUTPUT': outsource}, context, feedback), ['gdal_viewshed', '-b 1 -ox 18.67274 -oy 45.80599 -oz 1.0 -tz 1.0 -md 100.0 -f GTiff ' + dem + ' ' + outsource ]) self.assertEqual( alg.getConsoleCommands({'INPUT': dem, 'BAND': 2, 'OBSERVER': '18.67274,45.80599', 'OBSERVER_HEIGHT': 1.8, 'TARGET_HEIGHT': 20, 'MAX_DISTANCE': 1000, 'OUTPUT': outsource}, context, feedback), ['gdal_viewshed', '-b 2 -ox 18.67274 -oy 45.80599 -oz 1.8 -tz 20.0 -md 1000.0 -f GTiff ' + dem + ' ' + outsource ]) self.assertEqual( alg.getConsoleCommands({'INPUT': dem, 'BAND': 1, 'OBSERVER': '18.67274,45.80599', 'EXTRA': '-a_nodata=-9999 -cc 0.2', 'OUTPUT': outsource}, context, feedback), ['gdal_viewshed', '-b 1 -ox 18.67274 -oy 45.80599 -oz 1.0 -tz 1.0 -md 100.0 -f GTiff ' + '-a_nodata=-9999 -cc 0.2 ' + dem + ' ' + outsource ]) self.assertEqual( alg.getConsoleCommands({'INPUT': dem, 'BAND': 1, 'OBSERVER': '18.67274,45.80599', 'OPTIONS': 'COMPRESS=DEFLATE|PREDICTOR=2|ZLEVEL=9', 'OUTPUT': outsource}, context, feedback), ['gdal_viewshed', '-b 1 -ox 18.67274 -oy 45.80599 -oz 1.0 -tz 1.0 -md 100.0 -f GTiff ' + '-co COMPRESS=DEFLATE -co PREDICTOR=2 -co ZLEVEL=9 ' + dem + ' ' + outsource ]) def testBuildVrt(self): context = QgsProcessingContext() feedback = QgsProcessingFeedback() source = os.path.join(testDataPath, 'dem.tif') alg = buildvrt() alg.initAlgorithm() with tempfile.TemporaryDirectory() as outdir: # defaults cmd = alg.getConsoleCommands({'INPUT': [source], 'OUTPUT': outdir + '/check.vrt'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('-input_file_list') + 17] + t[t.find('buildvrtInputFiles.txt'):] self.assertEqual(cmd, ['gdalbuildvrt', '-resolution average -separate -r nearest ' + '-input_file_list buildvrtInputFiles.txt ' + outdir + '/check.vrt']) # custom resolution cmd = alg.getConsoleCommands({'INPUT': [source], 'RESOLUTION': 2, 'OUTPUT': outdir + '/check.vrt'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('-input_file_list') + 17] + t[t.find('buildvrtInputFiles.txt'):] self.assertEqual(cmd, ['gdalbuildvrt', '-resolution lowest -separate -r nearest ' + '-input_file_list buildvrtInputFiles.txt ' + outdir + '/check.vrt']) # single layer cmd = alg.getConsoleCommands({'INPUT': [source], 'SEPARATE': False, 'OUTPUT': outdir + '/check.vrt'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('-input_file_list') + 17] + t[t.find('buildvrtInputFiles.txt'):] self.assertEqual(cmd, ['gdalbuildvrt', '-resolution average -r nearest ' + '-input_file_list buildvrtInputFiles.txt ' + outdir + '/check.vrt']) # projection difference cmd = alg.getConsoleCommands({'INPUT': [source], 'PROJ_DIFFERENCE': True, 'OUTPUT': outdir + '/check.vrt'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('-input_file_list') + 17] + t[t.find('buildvrtInputFiles.txt'):] self.assertEqual(cmd, ['gdalbuildvrt', '-resolution average -separate -allow_projection_difference -r nearest ' + '-input_file_list buildvrtInputFiles.txt ' + outdir + '/check.vrt']) # add alpha band cmd = alg.getConsoleCommands({'INPUT': [source], 'ADD_ALPHA': True, 'OUTPUT': outdir + '/check.vrt'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('-input_file_list') + 17] + t[t.find('buildvrtInputFiles.txt'):] self.assertEqual(cmd, ['gdalbuildvrt', '-resolution average -separate -addalpha -r nearest ' + '-input_file_list buildvrtInputFiles.txt ' + outdir + '/check.vrt']) # assign CRS cmd = alg.getConsoleCommands({'INPUT': [source], 'ASSIGN_CRS': 'EPSG:3111', 'OUTPUT': outdir + '/check.vrt'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('-input_file_list') + 17] + t[t.find('buildvrtInputFiles.txt'):] self.assertEqual(cmd, ['gdalbuildvrt', '-resolution average -separate -a_srs EPSG:3111 -r nearest ' + '-input_file_list buildvrtInputFiles.txt ' + outdir + '/check.vrt']) custom_crs = 'proj4: +proj=utm +zone=36 +south +a=6378249.145 +b=6356514.966398753 +towgs84=-143,-90,-294,0,0,0,0 +units=m +no_defs' cmd = alg.getConsoleCommands({'INPUT': [source], 'ASSIGN_CRS': custom_crs, 'OUTPUT': outdir + '/check.vrt'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('-input_file_list') + 17] + t[t.find('buildvrtInputFiles.txt'):] self.assertEqual(cmd, ['gdalbuildvrt', '-resolution average -separate -a_srs EPSG:20936 -r nearest ' + '-input_file_list buildvrtInputFiles.txt ' + outdir + '/check.vrt']) # source NODATA cmd = alg.getConsoleCommands({'INPUT': [source], 'SRC_NODATA': '-9999', 'OUTPUT': outdir + '/check.vrt'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('-input_file_list') + 17] + t[t.find('buildvrtInputFiles.txt'):] self.assertEqual(cmd, ['gdalbuildvrt', '-resolution average -separate -r nearest -srcnodata "-9999" ' + '-input_file_list buildvrtInputFiles.txt ' + outdir + '/check.vrt']) cmd = alg.getConsoleCommands({'INPUT': [source], 'SRC_NODATA': '-9999 9999', 'OUTPUT': outdir + '/check.vrt'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('-input_file_list') + 17] + t[t.find('buildvrtInputFiles.txt'):] self.assertEqual(cmd, ['gdalbuildvrt', '-resolution average -separate -r nearest -srcnodata "-9999 9999" ' + '-input_file_list buildvrtInputFiles.txt ' + outdir + '/check.vrt']) cmd = alg.getConsoleCommands({'INPUT': [source], 'SRC_NODATA': '', 'OUTPUT': outdir + '/check.vrt'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('-input_file_list') + 17] + t[t.find('buildvrtInputFiles.txt'):] self.assertEqual(cmd, ['gdalbuildvrt', '-resolution average -separate -r nearest ' + '-input_file_list buildvrtInputFiles.txt ' + outdir + '/check.vrt']) # additional parameters cmd = alg.getConsoleCommands({'INPUT': [source], 'EXTRA': '-overwrite -optim RASTER -vrtnodata -9999', 'OUTPUT': outdir + '/check.vrt'}, context, feedback) t = cmd[1] cmd[1] = t[:t.find('-input_file_list') + 17] + t[t.find('buildvrtInputFiles.txt'):] self.assertEqual(cmd, ['gdalbuildvrt', '-resolution average -separate -r nearest -overwrite -optim RASTER -vrtnodata -9999 ' + '-input_file_list buildvrtInputFiles.txt ' + outdir + '/check.vrt']) if __name__ == '__main__': nose2.main()
gauribhoite/personfinder
refs/heads/master
env/google_appengine/lib/yaml/lib/yaml/representer.py
120
__all__ = ['BaseRepresenter', 'SafeRepresenter', 'Representer', 'RepresenterError'] from error import * from nodes import * import datetime try: set except NameError: from sets import Set as set import sys, copy_reg, types class RepresenterError(YAMLError): pass class BaseRepresenter(object): yaml_representers = {} yaml_multi_representers = {} def __init__(self, default_style=None, default_flow_style=None): self.default_style = default_style self.default_flow_style = default_flow_style self.represented_objects = {} self.object_keeper = [] self.alias_key = None def represent(self, data): node = self.represent_data(data) self.serialize(node) self.represented_objects = {} self.object_keeper = [] self.alias_key = None def get_classobj_bases(self, cls): bases = [cls] for base in cls.__bases__: bases.extend(self.get_classobj_bases(base)) return bases def represent_data(self, data): if self.ignore_aliases(data): self.alias_key = None else: self.alias_key = id(data) if self.alias_key is not None: if self.alias_key in self.represented_objects: node = self.represented_objects[self.alias_key] #if node is None: # raise RepresenterError("recursive objects are not allowed: %r" % data) return node #self.represented_objects[alias_key] = None self.object_keeper.append(data) data_types = type(data).__mro__ if type(data) is types.InstanceType: data_types = self.get_classobj_bases(data.__class__)+list(data_types) if data_types[0] in self.yaml_representers: node = self.yaml_representers[data_types[0]](self, data) else: for data_type in data_types: if data_type in self.yaml_multi_representers: node = self.yaml_multi_representers[data_type](self, data) break else: if None in self.yaml_multi_representers: node = self.yaml_multi_representers[None](self, data) elif None in self.yaml_representers: node = self.yaml_representers[None](self, data) else: node = ScalarNode(None, unicode(data)) #if alias_key is not None: # self.represented_objects[alias_key] = node return node def add_representer(cls, data_type, representer): if not 'yaml_representers' in cls.__dict__: cls.yaml_representers = cls.yaml_representers.copy() cls.yaml_representers[data_type] = representer add_representer = classmethod(add_representer) def add_multi_representer(cls, data_type, representer): if not 'yaml_multi_representers' in cls.__dict__: cls.yaml_multi_representers = cls.yaml_multi_representers.copy() cls.yaml_multi_representers[data_type] = representer add_multi_representer = classmethod(add_multi_representer) def represent_scalar(self, tag, value, style=None): if style is None: style = self.default_style node = ScalarNode(tag, value, style=style) if self.alias_key is not None: self.represented_objects[self.alias_key] = node return node def represent_sequence(self, tag, sequence, flow_style=None): value = [] node = SequenceNode(tag, value, flow_style=flow_style) if self.alias_key is not None: self.represented_objects[self.alias_key] = node best_style = True for item in sequence: node_item = self.represent_data(item) if not (isinstance(node_item, ScalarNode) and not node_item.style): best_style = False value.append(node_item) if flow_style is None: if self.default_flow_style is not None: node.flow_style = self.default_flow_style else: node.flow_style = best_style return node def represent_mapping(self, tag, mapping, flow_style=None): value = [] node = MappingNode(tag, value, flow_style=flow_style) if self.alias_key is not None: self.represented_objects[self.alias_key] = node best_style = True if hasattr(mapping, 'items'): mapping = mapping.items() mapping.sort() for item_key, item_value in mapping: node_key = self.represent_data(item_key) node_value = self.represent_data(item_value) if not (isinstance(node_key, ScalarNode) and not node_key.style): best_style = False if not (isinstance(node_value, ScalarNode) and not node_value.style): best_style = False value.append((node_key, node_value)) if flow_style is None: if self.default_flow_style is not None: node.flow_style = self.default_flow_style else: node.flow_style = best_style return node def ignore_aliases(self, data): return False class SafeRepresenter(BaseRepresenter): def ignore_aliases(self, data): if data in [None, ()]: return True if isinstance(data, (str, unicode, bool, int, float)): return True def represent_none(self, data): return self.represent_scalar(u'tag:yaml.org,2002:null', u'null') def represent_str(self, data): tag = None style = None try: data = unicode(data, 'ascii') tag = u'tag:yaml.org,2002:str' except UnicodeDecodeError: try: data = unicode(data, 'utf-8') tag = u'tag:yaml.org,2002:str' except UnicodeDecodeError: data = data.encode('base64') tag = u'tag:yaml.org,2002:binary' style = '|' return self.represent_scalar(tag, data, style=style) def represent_unicode(self, data): return self.represent_scalar(u'tag:yaml.org,2002:str', data) def represent_bool(self, data): if data: value = u'true' else: value = u'false' return self.represent_scalar(u'tag:yaml.org,2002:bool', value) def represent_int(self, data): return self.represent_scalar(u'tag:yaml.org,2002:int', unicode(data)) def represent_long(self, data): return self.represent_scalar(u'tag:yaml.org,2002:int', unicode(data)) inf_value = 1e300 while repr(inf_value) != repr(inf_value*inf_value): inf_value *= inf_value def represent_float(self, data): if data != data or (data == 0.0 and data == 1.0): value = u'.nan' elif data == self.inf_value: value = u'.inf' elif data == -self.inf_value: value = u'-.inf' else: value = unicode(repr(data)).lower() # Note that in some cases `repr(data)` represents a float number # without the decimal parts. For instance: # >>> repr(1e17) # '1e17' # Unfortunately, this is not a valid float representation according # to the definition of the `!!float` tag. We fix this by adding # '.0' before the 'e' symbol. if u'.' not in value and u'e' in value: value = value.replace(u'e', u'.0e', 1) return self.represent_scalar(u'tag:yaml.org,2002:float', value) def represent_list(self, data): #pairs = (len(data) > 0 and isinstance(data, list)) #if pairs: # for item in data: # if not isinstance(item, tuple) or len(item) != 2: # pairs = False # break #if not pairs: return self.represent_sequence(u'tag:yaml.org,2002:seq', data) #value = [] #for item_key, item_value in data: # value.append(self.represent_mapping(u'tag:yaml.org,2002:map', # [(item_key, item_value)])) #return SequenceNode(u'tag:yaml.org,2002:pairs', value) def represent_dict(self, data): return self.represent_mapping(u'tag:yaml.org,2002:map', data) def represent_set(self, data): value = {} for key in data: value[key] = None return self.represent_mapping(u'tag:yaml.org,2002:set', value) def represent_date(self, data): value = unicode(data.isoformat()) return self.represent_scalar(u'tag:yaml.org,2002:timestamp', value) def represent_datetime(self, data): value = unicode(data.isoformat(' ')) return self.represent_scalar(u'tag:yaml.org,2002:timestamp', value) def represent_yaml_object(self, tag, data, cls, flow_style=None): if hasattr(data, '__getstate__'): state = data.__getstate__() else: state = data.__dict__.copy() return self.represent_mapping(tag, state, flow_style=flow_style) def represent_undefined(self, data): raise RepresenterError("cannot represent an object: %s" % data) SafeRepresenter.add_representer(type(None), SafeRepresenter.represent_none) SafeRepresenter.add_representer(str, SafeRepresenter.represent_str) SafeRepresenter.add_representer(unicode, SafeRepresenter.represent_unicode) SafeRepresenter.add_representer(bool, SafeRepresenter.represent_bool) SafeRepresenter.add_representer(int, SafeRepresenter.represent_int) SafeRepresenter.add_representer(long, SafeRepresenter.represent_long) SafeRepresenter.add_representer(float, SafeRepresenter.represent_float) SafeRepresenter.add_representer(list, SafeRepresenter.represent_list) SafeRepresenter.add_representer(tuple, SafeRepresenter.represent_list) SafeRepresenter.add_representer(dict, SafeRepresenter.represent_dict) SafeRepresenter.add_representer(set, SafeRepresenter.represent_set) SafeRepresenter.add_representer(datetime.date, SafeRepresenter.represent_date) SafeRepresenter.add_representer(datetime.datetime, SafeRepresenter.represent_datetime) SafeRepresenter.add_representer(None, SafeRepresenter.represent_undefined) class Representer(SafeRepresenter): def represent_str(self, data): tag = None style = None try: data = unicode(data, 'ascii') tag = u'tag:yaml.org,2002:str' except UnicodeDecodeError: try: data = unicode(data, 'utf-8') tag = u'tag:yaml.org,2002:python/str' except UnicodeDecodeError: data = data.encode('base64') tag = u'tag:yaml.org,2002:binary' style = '|' return self.represent_scalar(tag, data, style=style) def represent_unicode(self, data): tag = None try: data.encode('ascii') tag = u'tag:yaml.org,2002:python/unicode' except UnicodeEncodeError: tag = u'tag:yaml.org,2002:str' return self.represent_scalar(tag, data) def represent_long(self, data): tag = u'tag:yaml.org,2002:int' if int(data) is not data: tag = u'tag:yaml.org,2002:python/long' return self.represent_scalar(tag, unicode(data)) def represent_complex(self, data): if data.imag == 0.0: data = u'%r' % data.real elif data.real == 0.0: data = u'%rj' % data.imag elif data.imag > 0: data = u'%r+%rj' % (data.real, data.imag) else: data = u'%r%rj' % (data.real, data.imag) return self.represent_scalar(u'tag:yaml.org,2002:python/complex', data) def represent_tuple(self, data): return self.represent_sequence(u'tag:yaml.org,2002:python/tuple', data) def represent_name(self, data): name = u'%s.%s' % (data.__module__, data.__name__) return self.represent_scalar(u'tag:yaml.org,2002:python/name:'+name, u'') def represent_module(self, data): return self.represent_scalar( u'tag:yaml.org,2002:python/module:'+data.__name__, u'') def represent_instance(self, data): # For instances of classic classes, we use __getinitargs__ and # __getstate__ to serialize the data. # If data.__getinitargs__ exists, the object must be reconstructed by # calling cls(**args), where args is a tuple returned by # __getinitargs__. Otherwise, the cls.__init__ method should never be # called and the class instance is created by instantiating a trivial # class and assigning to the instance's __class__ variable. # If data.__getstate__ exists, it returns the state of the object. # Otherwise, the state of the object is data.__dict__. # We produce either a !!python/object or !!python/object/new node. # If data.__getinitargs__ does not exist and state is a dictionary, we # produce a !!python/object node . Otherwise we produce a # !!python/object/new node. cls = data.__class__ class_name = u'%s.%s' % (cls.__module__, cls.__name__) args = None state = None if hasattr(data, '__getinitargs__'): args = list(data.__getinitargs__()) if hasattr(data, '__getstate__'): state = data.__getstate__() else: state = data.__dict__ if args is None and isinstance(state, dict): return self.represent_mapping( u'tag:yaml.org,2002:python/object:'+class_name, state) if isinstance(state, dict) and not state: return self.represent_sequence( u'tag:yaml.org,2002:python/object/new:'+class_name, args) value = {} if args: value['args'] = args value['state'] = state return self.represent_mapping( u'tag:yaml.org,2002:python/object/new:'+class_name, value) def represent_object(self, data): # We use __reduce__ API to save the data. data.__reduce__ returns # a tuple of length 2-5: # (function, args, state, listitems, dictitems) # For reconstructing, we calls function(*args), then set its state, # listitems, and dictitems if they are not None. # A special case is when function.__name__ == '__newobj__'. In this # case we create the object with args[0].__new__(*args). # Another special case is when __reduce__ returns a string - we don't # support it. # We produce a !!python/object, !!python/object/new or # !!python/object/apply node. cls = type(data) if cls in copy_reg.dispatch_table: reduce = copy_reg.dispatch_table[cls](data) elif hasattr(data, '__reduce_ex__'): reduce = data.__reduce_ex__(2) elif hasattr(data, '__reduce__'): reduce = data.__reduce__() else: raise RepresenterError("cannot represent object: %r" % data) reduce = (list(reduce)+[None]*5)[:5] function, args, state, listitems, dictitems = reduce args = list(args) if state is None: state = {} if listitems is not None: listitems = list(listitems) if dictitems is not None: dictitems = dict(dictitems) if function.__name__ == '__newobj__': function = args[0] args = args[1:] tag = u'tag:yaml.org,2002:python/object/new:' newobj = True else: tag = u'tag:yaml.org,2002:python/object/apply:' newobj = False function_name = u'%s.%s' % (function.__module__, function.__name__) if not args and not listitems and not dictitems \ and isinstance(state, dict) and newobj: return self.represent_mapping( u'tag:yaml.org,2002:python/object:'+function_name, state) if not listitems and not dictitems \ and isinstance(state, dict) and not state: return self.represent_sequence(tag+function_name, args) value = {} if args: value['args'] = args if state or not isinstance(state, dict): value['state'] = state if listitems: value['listitems'] = listitems if dictitems: value['dictitems'] = dictitems return self.represent_mapping(tag+function_name, value) Representer.add_representer(str, Representer.represent_str) Representer.add_representer(unicode, Representer.represent_unicode) Representer.add_representer(long, Representer.represent_long) Representer.add_representer(complex, Representer.represent_complex) Representer.add_representer(tuple, Representer.represent_tuple) Representer.add_representer(type, Representer.represent_name) Representer.add_representer(types.ClassType, Representer.represent_name) Representer.add_representer(types.FunctionType, Representer.represent_name) Representer.add_representer(types.BuiltinFunctionType, Representer.represent_name) Representer.add_representer(types.ModuleType, Representer.represent_module) Representer.add_multi_representer(types.InstanceType, Representer.represent_instance) Representer.add_multi_representer(object, Representer.represent_object)
mrwulff/shair-gui
refs/heads/master
simpleui.py
1
import pygame import socket from string import * UDP_IP = "127.0.0.1" UDP_PORT =5555 sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.bind((UDP_IP, UDP_PORT)) pygame.init() #screen = pygame.display.set_mode((640, 480),pygame.FULLSCREEN) screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() done = False font = pygame.font.SysFont("comicsansms", 72) songd='song' artistd='artist' albumd='album' coreasal while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True quit() if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: done = True quit() screen.fill((0,0,0)) data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes if "coreminm" in data: songd= data junk,songd=split(songd,'coreminm') if "coreasar" in data: artistd=data junk,artistd=split(artistd,"coreasar") if "coreasal" in data: albumd=data junk,albumd=split(albumd,"coreasal") text = font.render(songd, True, (0, 128, 0)) #screen.fill((255, 255, 255)) screen.blit(text,(320 - text.get_width() // 2, 50)) text2 = font.render(artistd, True, (0, 128, 0)) #screen.fill((255, 255, 255)) screen.blit(text2,(320 - text2.get_width() // 2, 150)) text3 = font.render(albumd, True, (0, 128, 0)) #screen.fill((255, 255, 255)) screen.blit(text3,(320 - text3.get_width() // 2, 250)) pygame.display.flip() clock.tick(60)
apporc/neutron
refs/heads/master
neutron/tests/api/test_networks_negative.py
47
# Copyright 2013 Huawei Technologies Co.,LTD. # 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. from tempest_lib.common.utils import data_utils from tempest_lib import exceptions as lib_exc from neutron.tests.api import base from neutron.tests.tempest import test class NetworksNegativeTestJSON(base.BaseNetworkTest): @test.attr(type=['negative', 'smoke']) @test.idempotent_id('9293e937-824d-42d2-8d5b-e985ea67002a') def test_show_non_existent_network(self): non_exist_id = data_utils.rand_name('network') self.assertRaises(lib_exc.NotFound, self.client.show_network, non_exist_id) @test.attr(type=['negative', 'smoke']) @test.idempotent_id('d746b40c-5e09-4043-99f7-cba1be8b70df') def test_show_non_existent_subnet(self): non_exist_id = data_utils.rand_name('subnet') self.assertRaises(lib_exc.NotFound, self.client.show_subnet, non_exist_id) @test.attr(type=['negative', 'smoke']) @test.idempotent_id('a954861d-cbfd-44e8-b0a9-7fab111f235d') def test_show_non_existent_port(self): non_exist_id = data_utils.rand_name('port') self.assertRaises(lib_exc.NotFound, self.client.show_port, non_exist_id) @test.attr(type=['negative', 'smoke']) @test.idempotent_id('98bfe4e3-574e-4012-8b17-b2647063de87') def test_update_non_existent_network(self): non_exist_id = data_utils.rand_name('network') self.assertRaises(lib_exc.NotFound, self.client.update_network, non_exist_id, name="new_name") @test.attr(type=['negative', 'smoke']) @test.idempotent_id('03795047-4a94-4120-a0a1-bd376e36fd4e') def test_delete_non_existent_network(self): non_exist_id = data_utils.rand_name('network') self.assertRaises(lib_exc.NotFound, self.client.delete_network, non_exist_id)
melphi/algobox
refs/heads/master
python/algobox/src/algobox/client/generated/api/models/strategy_registration_request_dto.py
1
# coding: utf-8 """ No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) Generated by: https://github.com/swagger-api/swagger-codegen.git 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 pprint import pformat from six import iteritems import re class StrategyRegistrationRequestDto(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, strategy_id=None, title=None, parameters=None, instruments_mapping=None): """ StrategyRegistrationRequestDto - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'strategy_id': 'str', 'title': 'str', 'parameters': 'dict(str, str)', 'instruments_mapping': 'list[InstrumentMapping]' } self.attribute_map = { 'strategy_id': 'strategyId', 'title': 'title', 'parameters': 'parameters', 'instruments_mapping': 'instrumentsMapping' } self._strategy_id = strategy_id self._title = title self._parameters = parameters self._instruments_mapping = instruments_mapping @property def strategy_id(self): """ Gets the strategy_id of this StrategyRegistrationRequestDto. :return: The strategy_id of this StrategyRegistrationRequestDto. :rtype: str """ return self._strategy_id @strategy_id.setter def strategy_id(self, strategy_id): """ Sets the strategy_id of this StrategyRegistrationRequestDto. :param strategy_id: The strategy_id of this StrategyRegistrationRequestDto. :type: str """ self._strategy_id = strategy_id @property def title(self): """ Gets the title of this StrategyRegistrationRequestDto. :return: The title of this StrategyRegistrationRequestDto. :rtype: str """ return self._title @title.setter def title(self, title): """ Sets the title of this StrategyRegistrationRequestDto. :param title: The title of this StrategyRegistrationRequestDto. :type: str """ self._title = title @property def parameters(self): """ Gets the parameters of this StrategyRegistrationRequestDto. :return: The parameters of this StrategyRegistrationRequestDto. :rtype: dict(str, str) """ return self._parameters @parameters.setter def parameters(self, parameters): """ Sets the parameters of this StrategyRegistrationRequestDto. :param parameters: The parameters of this StrategyRegistrationRequestDto. :type: dict(str, str) """ self._parameters = parameters @property def instruments_mapping(self): """ Gets the instruments_mapping of this StrategyRegistrationRequestDto. :return: The instruments_mapping of this StrategyRegistrationRequestDto. :rtype: list[InstrumentMapping] """ return self._instruments_mapping @instruments_mapping.setter def instruments_mapping(self, instruments_mapping): """ Sets the instruments_mapping of this StrategyRegistrationRequestDto. :param instruments_mapping: The instruments_mapping of this StrategyRegistrationRequestDto. :type: list[InstrumentMapping] """ self._instruments_mapping = instruments_mapping def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
srluge/SickRage
refs/heads/master
lib/unidecode/x06a.py
252
data = ( 'Di ', # 0x00 'Zhuang ', # 0x01 'Le ', # 0x02 'Lang ', # 0x03 'Chen ', # 0x04 'Cong ', # 0x05 'Li ', # 0x06 'Xiu ', # 0x07 'Qing ', # 0x08 'Shuang ', # 0x09 'Fan ', # 0x0a 'Tong ', # 0x0b 'Guan ', # 0x0c 'Ji ', # 0x0d 'Suo ', # 0x0e 'Lei ', # 0x0f 'Lu ', # 0x10 'Liang ', # 0x11 'Mi ', # 0x12 'Lou ', # 0x13 'Chao ', # 0x14 'Su ', # 0x15 'Ke ', # 0x16 'Shu ', # 0x17 'Tang ', # 0x18 'Biao ', # 0x19 'Lu ', # 0x1a 'Jiu ', # 0x1b 'Shu ', # 0x1c 'Zha ', # 0x1d 'Shu ', # 0x1e 'Zhang ', # 0x1f 'Men ', # 0x20 'Mo ', # 0x21 'Niao ', # 0x22 'Yang ', # 0x23 'Tiao ', # 0x24 'Peng ', # 0x25 'Zhu ', # 0x26 'Sha ', # 0x27 'Xi ', # 0x28 'Quan ', # 0x29 'Heng ', # 0x2a 'Jian ', # 0x2b 'Cong ', # 0x2c '[?] ', # 0x2d 'Hokuso ', # 0x2e 'Qiang ', # 0x2f 'Tara ', # 0x30 'Ying ', # 0x31 'Er ', # 0x32 'Xin ', # 0x33 'Zhi ', # 0x34 'Qiao ', # 0x35 'Zui ', # 0x36 'Cong ', # 0x37 'Pu ', # 0x38 'Shu ', # 0x39 'Hua ', # 0x3a 'Kui ', # 0x3b 'Zhen ', # 0x3c 'Zun ', # 0x3d 'Yue ', # 0x3e 'Zhan ', # 0x3f 'Xi ', # 0x40 'Xun ', # 0x41 'Dian ', # 0x42 'Fa ', # 0x43 'Gan ', # 0x44 'Mo ', # 0x45 'Wu ', # 0x46 'Qiao ', # 0x47 'Nao ', # 0x48 'Lin ', # 0x49 'Liu ', # 0x4a 'Qiao ', # 0x4b 'Xian ', # 0x4c 'Run ', # 0x4d 'Fan ', # 0x4e 'Zhan ', # 0x4f 'Tuo ', # 0x50 'Lao ', # 0x51 'Yun ', # 0x52 'Shun ', # 0x53 'Tui ', # 0x54 'Cheng ', # 0x55 'Tang ', # 0x56 'Meng ', # 0x57 'Ju ', # 0x58 'Cheng ', # 0x59 'Su ', # 0x5a 'Jue ', # 0x5b 'Jue ', # 0x5c 'Tan ', # 0x5d 'Hui ', # 0x5e 'Ji ', # 0x5f 'Nuo ', # 0x60 'Xiang ', # 0x61 'Tuo ', # 0x62 'Ning ', # 0x63 'Rui ', # 0x64 'Zhu ', # 0x65 'Chuang ', # 0x66 'Zeng ', # 0x67 'Fen ', # 0x68 'Qiong ', # 0x69 'Ran ', # 0x6a 'Heng ', # 0x6b 'Cen ', # 0x6c 'Gu ', # 0x6d 'Liu ', # 0x6e 'Lao ', # 0x6f 'Gao ', # 0x70 'Chu ', # 0x71 'Zusa ', # 0x72 'Nude ', # 0x73 'Ca ', # 0x74 'San ', # 0x75 'Ji ', # 0x76 'Dou ', # 0x77 'Shou ', # 0x78 'Lu ', # 0x79 '[?] ', # 0x7a '[?] ', # 0x7b 'Yuan ', # 0x7c 'Ta ', # 0x7d 'Shu ', # 0x7e 'Jiang ', # 0x7f 'Tan ', # 0x80 'Lin ', # 0x81 'Nong ', # 0x82 'Yin ', # 0x83 'Xi ', # 0x84 'Sui ', # 0x85 'Shan ', # 0x86 'Zui ', # 0x87 'Xuan ', # 0x88 'Cheng ', # 0x89 'Gan ', # 0x8a 'Ju ', # 0x8b 'Zui ', # 0x8c 'Yi ', # 0x8d 'Qin ', # 0x8e 'Pu ', # 0x8f 'Yan ', # 0x90 'Lei ', # 0x91 'Feng ', # 0x92 'Hui ', # 0x93 'Dang ', # 0x94 'Ji ', # 0x95 'Sui ', # 0x96 'Bo ', # 0x97 'Bi ', # 0x98 'Ding ', # 0x99 'Chu ', # 0x9a 'Zhua ', # 0x9b 'Kuai ', # 0x9c 'Ji ', # 0x9d 'Jie ', # 0x9e 'Jia ', # 0x9f 'Qing ', # 0xa0 'Zhe ', # 0xa1 'Jian ', # 0xa2 'Qiang ', # 0xa3 'Dao ', # 0xa4 'Yi ', # 0xa5 'Biao ', # 0xa6 'Song ', # 0xa7 'She ', # 0xa8 'Lin ', # 0xa9 'Kunugi ', # 0xaa 'Cha ', # 0xab 'Meng ', # 0xac 'Yin ', # 0xad 'Tao ', # 0xae 'Tai ', # 0xaf 'Mian ', # 0xb0 'Qi ', # 0xb1 'Toan ', # 0xb2 'Bin ', # 0xb3 'Huo ', # 0xb4 'Ji ', # 0xb5 'Qian ', # 0xb6 'Mi ', # 0xb7 'Ning ', # 0xb8 'Yi ', # 0xb9 'Gao ', # 0xba 'Jian ', # 0xbb 'Yin ', # 0xbc 'Er ', # 0xbd 'Qing ', # 0xbe 'Yan ', # 0xbf 'Qi ', # 0xc0 'Mi ', # 0xc1 'Zhao ', # 0xc2 'Gui ', # 0xc3 'Chun ', # 0xc4 'Ji ', # 0xc5 'Kui ', # 0xc6 'Po ', # 0xc7 'Deng ', # 0xc8 'Chu ', # 0xc9 '[?] ', # 0xca 'Mian ', # 0xcb 'You ', # 0xcc 'Zhi ', # 0xcd 'Guang ', # 0xce 'Qian ', # 0xcf 'Lei ', # 0xd0 'Lei ', # 0xd1 'Sa ', # 0xd2 'Lu ', # 0xd3 'Li ', # 0xd4 'Cuan ', # 0xd5 'Lu ', # 0xd6 'Mie ', # 0xd7 'Hui ', # 0xd8 'Ou ', # 0xd9 'Lu ', # 0xda 'Jie ', # 0xdb 'Gao ', # 0xdc 'Du ', # 0xdd 'Yuan ', # 0xde 'Li ', # 0xdf 'Fei ', # 0xe0 'Zhuo ', # 0xe1 'Sou ', # 0xe2 'Lian ', # 0xe3 'Tamo ', # 0xe4 'Chu ', # 0xe5 '[?] ', # 0xe6 'Zhu ', # 0xe7 'Lu ', # 0xe8 'Yan ', # 0xe9 'Li ', # 0xea 'Zhu ', # 0xeb 'Chen ', # 0xec 'Jie ', # 0xed 'E ', # 0xee 'Su ', # 0xef 'Huai ', # 0xf0 'Nie ', # 0xf1 'Yu ', # 0xf2 'Long ', # 0xf3 'Lai ', # 0xf4 '[?] ', # 0xf5 'Xian ', # 0xf6 'Kwi ', # 0xf7 'Ju ', # 0xf8 'Xiao ', # 0xf9 'Ling ', # 0xfa 'Ying ', # 0xfb 'Jian ', # 0xfc 'Yin ', # 0xfd 'You ', # 0xfe 'Ying ', # 0xff )
nocarryr/python-slack
refs/heads/master
python_slack/slackobjects/timeutils.py
1
import datetime import numbers try: import pytz UTC = pytz.UTC except ImportError: UTC = None from python_slack.slackobjects.base import AttributeValue def make_dt_aware(dt): if UTC is not None: if dt.tzinfo is not None: dt = UTC.normalize(dt) else: dt = UTC.localize(dt) return dt EPOCH = make_dt_aware(datetime.datetime(1970, 1, 1)) def dt_to_ts(dt): dt = make_dt_aware(dt) td = dt - EPOCH return td.total_seconds() def ts_to_dt(ts): ts = float(ts) dt = datetime.datetime.utcfromtimestamp(ts) return make_dt_aware(dt) class Timestamp(AttributeValue): def get_value(self): return getattr(self, 'value_dt', None) def set_value(self, value): if value is None: self.value = value return if isinstance(value, basestring): value = float(value) if isinstance(value, numbers.Number): ts = value dt = ts_to_dt(ts) elif isinstance(value, datetime.datetime): dt = make_dt_aware(value) ts = dt_to_ts(dt) self.value_dt = dt self.value_ts = ts
Jajcus/cjc
refs/heads/master
plugins/roster_ei.py
1
# Console Jabber Client # Copyright (C) 2004-2010 Jacek Konieczny # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as published # by the Free Software Foundation # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """Roster export/import""" import libxml2 import pyxmpp import pyxmpp.roster import copy from cjc.plugin import PluginBase from cjc import common from cjc import ui import os class Plugin(PluginBase): def __init__(self, app, name): PluginBase.__init__(self, app, name) ui.activate_cmdtable("roster_ei", self) def cmd_export_roster(self, args): filename = args.shift() if args.all(): self.error(u"Too many arguments.") return filename = os.path.expanduser(filename) if os.path.exists(filename): self.error(u"File exists.") return try: f = file(filename, "w") xml = self.cjc.roster.as_xml() f.write(xml.serialize(format=1)) f.close() except IOError, e: self.error(u"Error writting roster: %s", unicode(e)) return return self.info(u"Roster written: %s", unicode(filename)) def cmd_import_roster(self, args): filename = args.shift() if args.all(): self.error(u"Too many arguments.") return filename = os.path.expanduser(filename) try: xml = libxml2.parseFile(filename) except (IOError, libxml2.libxmlError), e: self.error(u"Error reading roster: %s", unicode(e)) return return roster = pyxmpp.roster.Roster(xml.getRootElement()) self.info(u"Roster read: %i items", len(roster.items)) for item in roster: if item.jid in self.cjc.roster: local_item = self.cjc.roster.get_item_by_jid(item.jid) else: self.info(u"Adding entry: %s (%s)", unicode(item.jid), unicode(item.name)) local_item = self.cjc.roster.add_item(item.jid, name = item.name, groups = item.groups) iq = local_item.make_roster_push() self.cjc.stream.send(iq) if item.subscription in ('both', 'to') and local_item.subscription in ('none', 'from'): self.info(u"Sending supscription request to: %s", unicode(local_item.jid)) p = pyxmpp.Presence(stanza_type = 'subscribe', to_jid = local_item.jid) self.cjc.stream.send(p) ui.CommandTable("roster_ei",50,( ui.Command("export_roster",Plugin.cmd_export_roster, "/export_roster filename", "Export roster as an XML file.", ("filename",)), ui.Command("import_roster",Plugin.cmd_import_roster, "/import_roster filename", "Import roster as an XML file.", ("filename",)), )).install() # vi: sts=4 et sw=4
maxziv/SEApp
refs/heads/master
server/lib/werkzeug/contrib/iterio.py
89
# -*- coding: utf-8 -*- r""" werkzeug.contrib.iterio ~~~~~~~~~~~~~~~~~~~~~~~ This module implements a :class:`IterIO` that converts an iterator into a stream object and the other way round. Converting streams into iterators requires the `greenlet`_ module. To convert an iterator into a stream all you have to do is to pass it directly to the :class:`IterIO` constructor. In this example we pass it a newly created generator:: def foo(): yield "something\n" yield "otherthings" stream = IterIO(foo()) print stream.read() # read the whole iterator The other way round works a bit different because we have to ensure that the code execution doesn't take place yet. An :class:`IterIO` call with a callable as first argument does two things. The function itself is passed an :class:`IterIO` stream it can feed. The object returned by the :class:`IterIO` constructor on the other hand is not an stream object but an iterator:: def foo(stream): stream.write("some") stream.write("thing") stream.flush() stream.write("otherthing") iterator = IterIO(foo) print iterator.next() # prints something print iterator.next() # prints otherthing iterator.next() # raises StopIteration .. _greenlet: http://codespeak.net/py/dist/greenlet.html :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ try: import greenlet except ImportError: greenlet = None class IterIO(object): """Instances of this object implement an interface compatible with the standard Python :class:`file` object. Streams are either read-only or write-only depending on how the object is created. """ def __new__(cls, obj): try: iterator = iter(obj) except TypeError: return IterI(obj) return IterO(iterator) def __iter__(self): return self def tell(self): if self.closed: raise ValueError('I/O operation on closed file') return self.pos def isatty(self): if self.closed: raise ValueError('I/O operation on closed file') return False def seek(self, pos, mode=0): if self.closed: raise ValueError('I/O operation on closed file') raise IOError(9, 'Bad file descriptor') def truncate(self, size=None): if self.closed: raise ValueError('I/O operation on closed file') raise IOError(9, 'Bad file descriptor') def write(self, s): if self.closed: raise ValueError('I/O operation on closed file') raise IOError(9, 'Bad file descriptor') def writelines(self, list): if self.closed: raise ValueError('I/O operation on closed file') raise IOError(9, 'Bad file descriptor') def read(self, n=-1): if self.closed: raise ValueError('I/O operation on closed file') raise IOError(9, 'Bad file descriptor') def readlines(self, sizehint=0): if self.closed: raise ValueError('I/O operation on closed file') raise IOError(9, 'Bad file descriptor') def readline(self, length=None): if self.closed: raise ValueError('I/O operation on closed file') raise IOError(9, 'Bad file descriptor') def flush(self): if self.closed: raise ValueError('I/O operation on closed file') raise IOError(9, 'Bad file descriptor') def next(self): if self.closed: raise StopIteration() line = self.readline() if not line: raise StopIteration() return line class IterI(IterIO): """Convert an stream into an iterator.""" def __new__(cls, func): if greenlet is None: raise RuntimeError('IterI requires greenlet support') stream = object.__new__(cls) stream._parent = greenlet.getcurrent() stream._buffer = [] stream.closed = False stream.pos = 0 def run(): func(stream) stream.flush() g = greenlet.greenlet(run, stream._parent) while 1: rv = g.switch() if not rv: return yield rv[0] def close(self): if not self.closed: self.closed = True def write(self, s): if self.closed: raise ValueError('I/O operation on closed file') self.pos += len(s) self._buffer.append(s) def writelines(self, list): self.write(''.join(list)) def flush(self): if self.closed: raise ValueError('I/O operation on closed file') data = ''.join(self._buffer) self._buffer = [] self._parent.switch((data,)) class IterO(IterIO): """Iter output. Wrap an iterator and give it a stream like interface.""" def __new__(cls, gen): self = object.__new__(cls) self._gen = gen self._buf = '' self.closed = False self.pos = 0 return self def __iter__(self): return self def close(self): if not self.closed: self.closed = True if hasattr(self._gen, 'close'): self._gen.close() def seek(self, pos, mode=0): if self.closed: raise ValueError('I/O operation on closed file') if mode == 1: pos += self.pos elif mode == 2: self.read() self.pos = min(self.pos, self.pos + pos) return elif mode != 0: raise IOError('Invalid argument') buf = [] try: tmp_end_pos = len(self._buf) while pos > tmp_end_pos: item = self._gen.next() tmp_end_pos += len(item) buf.append(item) except StopIteration: pass if buf: self._buf += ''.join(buf) self.pos = max(0, pos) def read(self, n=-1): if self.closed: raise ValueError('I/O operation on closed file') if n < 0: self._buf += ''.join(self._gen) result = self._buf[self.pos:] self.pos += len(result) return result new_pos = self.pos + n buf = [] try: tmp_end_pos = len(self._buf) while new_pos > tmp_end_pos: item = self._gen.next() tmp_end_pos += len(item) buf.append(item) except StopIteration: pass if buf: self._buf += ''.join(buf) new_pos = max(0, new_pos) try: return self._buf[self.pos:new_pos] finally: self.pos = min(new_pos, len(self._buf)) def readline(self, length=None): if self.closed: raise ValueError('I/O operation on closed file') nl_pos = self._buf.find('\n', self.pos) buf = [] try: pos = self.pos while nl_pos < 0: item = self._gen.next() local_pos = item.find('\n') buf.append(item) if local_pos >= 0: nl_pos = pos + local_pos break pos += len(item) except StopIteration: pass if buf: self._buf += ''.join(buf) if nl_pos < 0: new_pos = len(self._buf) else: new_pos = nl_pos + 1 if length is not None and self.pos + length < new_pos: new_pos = self.pos + length try: return self._buf[self.pos:new_pos] finally: self.pos = min(new_pos, len(self._buf)) def readlines(self, sizehint=0): total = 0 lines = [] line = self.readline() while line: lines.append(line) total += len(line) if 0 < sizehint <= total: break line = self.readline() return lines
brunoliveira8/distributed-systems
refs/heads/master
StorageServer.py
1
# -*- coding: utf-8 -*- import os from abc import ABCMeta, abstractmethod import Pyro4 import serpent class AbstractStorage(object): """Implementa a interface Storage""" __metaclass__ = ABCMeta @abstractmethod def save(self, file, filename): """Colocar definição aqui.""" return @abstractmethod def delete(self): """Colocar definição aqui.""" return @abstractmethod def retrieve(self, filename): """Colocar definição aqui.""" return @abstractmethod def list(self): """Colocar definição aqui.""" return @Pyro4.expose class StorageSecundary(AbstractStorage): def __init__(self, proxy): self.proxy = proxy self.pk = self.proxy.n_servers self.db = "storage-secondary-{0}".format(self.pk) self.name = "storage.server.secundary.id-{0}".format(self.pk) self.proxy.register(self.name) try: os.mkdir(self.db) except: pass self._sync() @Pyro4.oneway def save(self, file, filename): with open(os.path.join(self.db, filename), "wb") as f: f.write(serpent.tobytes(file)) def delete(self, filename): response = {'code': '404', 'content': 'Not found.'} try: os.remove(os.path.join(self.db, filename)) response['code'] = '200' response['content'] = 'Arquivo deletado.' except: pass return response def retrieve(self, filename): response = {'code': '404', 'content': 'Not found.'} try: with open(os.path.join(self.db, filename), "rb") as f: response['code'] = '200' response['content'] = f.read() except: self._sync() return response def list(self): response = {'code': '404', 'content': 'Not found.'} response['code'] = '200' response['content'] = os.listdir(self.db) return response def _sync(self): with Pyro4.Proxy("PYRONAME:storage.server.primary") as primary: primary_files = set(primary.list()['content']) my_files = set(self.list()['content']) sync_files = primary_files - my_files for filename in sync_files: response = primary.retrieve(filename) self.save(serpent.tobytes(response['content']), filename) delete_files = my_files - primary_files for filename in delete_files: os.remove(os.path.join(self.db, filename)) @Pyro4.expose class StoragePrimary(AbstractStorage): def __init__(self, proxy): self.db = "storage-primary" self.name = "storage.server.primary" self.proxy = proxy self.proxy.register(self.name) try: os.mkdir(self.db) except: pass @Pyro4.oneway def save(self, file, filename): with open(os.path.join(self.db, filename), "wb") as f: f.write(serpent.tobytes(file)) for server_name in self.proxy.servers: if server_name != self.name: with Pyro4.Proxy("PYRONAME:" + server_name) as storage: try: storage._pyroBind() storage.save(serpent.tobytes(file), filename) except: print("Err: Objeto não encontrado...") def delete(self, filename): response = {'code': '404', 'content': 'Not found.'} try: os.remove(os.path.join(self.db, filename)) response['code'] = '200' response['content'] = 'Arquivo deletado.' except: pass for server_name in self.proxy.servers: if server_name != self.name: with Pyro4.Proxy("PYRONAME:" + server_name) as storage: try: storage._pyroBind() storage.delete(filename) except: print("Err: Objeto não encontrado...") return response def retrieve(self, filename): response = {'code': '404', 'content': 'Not found.'} try: with open(os.path.join(self.db, filename), "rb") as f: response['code'] = '200' response['content'] = f.read() except: pass return response def list(self): response = {'code': '404', 'content': 'Not found.'} response['code'] = '200' response['content'] = os.listdir(self.db) return response @Pyro4.expose class StorageProxy(AbstractStorage): def __init__(self): self._servers = list() self._n_servers = 0 @Pyro4.oneway def save(self, file, filename): """Colocar definição aqui.""" with Pyro4.Proxy("PYRONAME:storage.server.primary") as primary: primary.save(file, filename) def delete(self, filename): """Colocar definição aqui.""" response = {'code': '404', 'content': 'Not found.'} with Pyro4.Proxy("PYRONAME:storage.server.primary") as primary: response = primary.delete(filename) return response def retrieve(self, filename): """Colocar definição aqui.""" ctrl = True while ctrl: server_name = self._servers.pop() self._servers.insert(0, server_name) storage = Pyro4.Proxy("PYRONAME:" + server_name) try: storage._pyroBind() print("Lendo do server: " + server_name) ctrl = False except: pass if filename in self.list()['content']: response = storage.retrieve(filename) if response['code'] == '404' and server_name != 'storage.server.primary': with Pyro4.Proxy("PYRONAME:storage.server.primary") as primary: response = primary.retrieve(filename) print('Server {0} falhou. Recebendo resposta do primário...'.format( server_name)) return response else: response = {'code': '404', 'content': 'Not found.'} return response def list(self): """Colocar definição aqui.""" with Pyro4.Proxy("PYRONAME:storage.server.primary") as primary: response = primary.list() return response def register(self, server_name): self._servers.append(server_name) self._n_servers += 1 @property def servers(self): return self._servers @property def n_servers(self): return self._n_servers
DirtyUnicorns/android_external_chromium-org
refs/heads/kitkat
build/win/setup_cygwin_mount.py
92
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import sys def main(): if len(sys.argv) != 2 or sys.argv[1] != '--win-only': return 1 if sys.platform in ('win32', 'cygwin'): self_dir = os.path.dirname(sys.argv[0]) mount_path = os.path.join(self_dir, "../../third_party/cygwin") batch_path = os.path.join(mount_path, "setup_mount.bat") return os.system(os.path.normpath(batch_path) + ">nul") return 0 if __name__ == "__main__": sys.exit(main())
adambrenecki/django
refs/heads/master
django/contrib/gis/gdal/srs.py
219
""" The Spatial Reference class, represensents OGR Spatial Reference objects. Example: >>> from django.contrib.gis.gdal import SpatialReference >>> srs = SpatialReference('WGS84') >>> print(srs) GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], TOWGS84[0,0,0,0,0,0,0], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["degree",0.01745329251994328, AUTHORITY["EPSG","9122"]], AUTHORITY["EPSG","4326"]] >>> print(srs.proj) +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs >>> print(srs.ellipsoid) (6378137.0, 6356752.3142451793, 298.25722356300003) >>> print(srs.projected, srs.geographic) False True >>> srs.import_epsg(32140) >>> print(srs.name) NAD83 / Texas South Central """ from ctypes import byref, c_char_p, c_int # Getting the error checking routine and exceptions from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import SRSException from django.contrib.gis.gdal.prototypes import srs as capi from django.utils import six from django.utils.encoding import force_bytes #### Spatial Reference class. #### class SpatialReference(GDALBase): """ A wrapper for the OGRSpatialReference object. According to the GDAL Web site, the SpatialReference object "provide[s] services to represent coordinate systems (projections and datums) and to transform between them." """ #### Python 'magic' routines #### def __init__(self, srs_input=''): """ Creates a GDAL OSR Spatial Reference object from the given input. The input may be string of OGC Well Known Text (WKT), an integer EPSG code, a PROJ.4 string, and/or a projection "well known" shorthand string (one of 'WGS84', 'WGS72', 'NAD27', 'NAD83'). """ srs_type = 'user' if isinstance(srs_input, six.string_types): # Encoding to ASCII if unicode passed in. if isinstance(srs_input, six.text_type): srs_input = srs_input.encode('ascii') try: # If SRID is a string, e.g., '4326', then make acceptable # as user input. srid = int(srs_input) srs_input = 'EPSG:%d' % srid except ValueError: pass elif isinstance(srs_input, six.integer_types): # EPSG integer code was input. srs_type = 'epsg' elif isinstance(srs_input, self.ptr_type): srs = srs_input srs_type = 'ogr' else: raise TypeError('Invalid SRS type "%s"' % srs_type) if srs_type == 'ogr': # Input is already an SRS pointer. srs = srs_input else: # Creating a new SRS pointer, using the string buffer. buf = c_char_p(b'') srs = capi.new_srs(buf) # If the pointer is NULL, throw an exception. if not srs: raise SRSException('Could not create spatial reference from: %s' % srs_input) else: self.ptr = srs # Importing from either the user input string or an integer SRID. if srs_type == 'user': self.import_user_input(srs_input) elif srs_type == 'epsg': self.import_epsg(srs_input) def __del__(self): "Destroys this spatial reference." if self._ptr: capi.release_srs(self._ptr) def __getitem__(self, target): """ Returns the value of the given string attribute node, None if the node doesn't exist. Can also take a tuple as a parameter, (target, child), where child is the index of the attribute in the WKT. For example: >>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]') >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326 >>> print(srs['GEOGCS']) WGS 84 >>> print(srs['DATUM']) WGS_1984 >>> print(srs['AUTHORITY']) EPSG >>> print(srs['AUTHORITY', 1]) # The authority value 4326 >>> print(srs['TOWGS84', 4]) # the fourth value in this wkt 0 >>> print(srs['UNIT|AUTHORITY']) # For the units authority, have to use the pipe symbole. EPSG >>> print(srs['UNIT|AUTHORITY', 1]) # The authority value for the untis 9122 """ if isinstance(target, tuple): return self.attr_value(*target) else: return self.attr_value(target) def __str__(self): "The string representation uses 'pretty' WKT." return self.pretty_wkt #### SpatialReference Methods #### def attr_value(self, target, index=0): """ The attribute value for the given target node (e.g. 'PROJCS'). The index keyword specifies an index of the child node to return. """ if not isinstance(target, six.string_types) or not isinstance(index, int): raise TypeError return capi.get_attr_value(self.ptr, force_bytes(target), index) def auth_name(self, target): "Returns the authority name for the given string target node." return capi.get_auth_name(self.ptr, force_bytes(target)) def auth_code(self, target): "Returns the authority code for the given string target node." return capi.get_auth_code(self.ptr, force_bytes(target)) def clone(self): "Returns a clone of this SpatialReference object." return SpatialReference(capi.clone_srs(self.ptr)) def from_esri(self): "Morphs this SpatialReference from ESRI's format to EPSG." capi.morph_from_esri(self.ptr) def identify_epsg(self): """ This method inspects the WKT of this SpatialReference, and will add EPSG authority nodes where an EPSG identifier is applicable. """ capi.identify_epsg(self.ptr) def to_esri(self): "Morphs this SpatialReference to ESRI's format." capi.morph_to_esri(self.ptr) def validate(self): "Checks to see if the given spatial reference is valid." capi.srs_validate(self.ptr) #### Name & SRID properties #### @property def name(self): "Returns the name of this Spatial Reference." if self.projected: return self.attr_value('PROJCS') elif self.geographic: return self.attr_value('GEOGCS') elif self.local: return self.attr_value('LOCAL_CS') else: return None @property def srid(self): "Returns the SRID of top-level authority, or None if undefined." try: return int(self.attr_value('AUTHORITY', 1)) except (TypeError, ValueError): return None #### Unit Properties #### @property def linear_name(self): "Returns the name of the linear units." units, name = capi.linear_units(self.ptr, byref(c_char_p())) return name @property def linear_units(self): "Returns the value of the linear units." units, name = capi.linear_units(self.ptr, byref(c_char_p())) return units @property def angular_name(self): "Returns the name of the angular units." units, name = capi.angular_units(self.ptr, byref(c_char_p())) return name @property def angular_units(self): "Returns the value of the angular units." units, name = capi.angular_units(self.ptr, byref(c_char_p())) return units @property def units(self): """ Returns a 2-tuple of the units value and the units name, and will automatically determines whether to return the linear or angular units. """ units, name = None, None if self.projected or self.local: units, name = capi.linear_units(self.ptr, byref(c_char_p())) elif self.geographic: units, name = capi.angular_units(self.ptr, byref(c_char_p())) if name is not None: name.decode() return (units, name) #### Spheroid/Ellipsoid Properties #### @property def ellipsoid(self): """ Returns a tuple of the ellipsoid parameters: (semimajor axis, semiminor axis, and inverse flattening) """ return (self.semi_major, self.semi_minor, self.inverse_flattening) @property def semi_major(self): "Returns the Semi Major Axis for this Spatial Reference." return capi.semi_major(self.ptr, byref(c_int())) @property def semi_minor(self): "Returns the Semi Minor Axis for this Spatial Reference." return capi.semi_minor(self.ptr, byref(c_int())) @property def inverse_flattening(self): "Returns the Inverse Flattening for this Spatial Reference." return capi.invflattening(self.ptr, byref(c_int())) #### Boolean Properties #### @property def geographic(self): """ Returns True if this SpatialReference is geographic (root node is GEOGCS). """ return bool(capi.isgeographic(self.ptr)) @property def local(self): "Returns True if this SpatialReference is local (root node is LOCAL_CS)." return bool(capi.islocal(self.ptr)) @property def projected(self): """ Returns True if this SpatialReference is a projected coordinate system (root node is PROJCS). """ return bool(capi.isprojected(self.ptr)) #### Import Routines ##### def import_epsg(self, epsg): "Imports the Spatial Reference from the EPSG code (an integer)." capi.from_epsg(self.ptr, epsg) def import_proj(self, proj): "Imports the Spatial Reference from a PROJ.4 string." capi.from_proj(self.ptr, proj) def import_user_input(self, user_input): "Imports the Spatial Reference from the given user input string." capi.from_user_input(self.ptr, force_bytes(user_input)) def import_wkt(self, wkt): "Imports the Spatial Reference from OGC WKT (string)" capi.from_wkt(self.ptr, byref(c_char_p(wkt))) def import_xml(self, xml): "Imports the Spatial Reference from an XML string." capi.from_xml(self.ptr, xml) #### Export Properties #### @property def wkt(self): "Returns the WKT representation of this Spatial Reference." return capi.to_wkt(self.ptr, byref(c_char_p())) @property def pretty_wkt(self, simplify=0): "Returns the 'pretty' representation of the WKT." return capi.to_pretty_wkt(self.ptr, byref(c_char_p()), simplify) @property def proj(self): "Returns the PROJ.4 representation for this Spatial Reference." return capi.to_proj(self.ptr, byref(c_char_p())) @property def proj4(self): "Alias for proj()." return self.proj @property def xml(self, dialect=''): "Returns the XML representation of this Spatial Reference." return capi.to_xml(self.ptr, byref(c_char_p()), dialect) class CoordTransform(GDALBase): "The coordinate system transformation object." def __init__(self, source, target): "Initializes on a source and target SpatialReference objects." if not isinstance(source, SpatialReference) or not isinstance(target, SpatialReference): raise TypeError('source and target must be of type SpatialReference') self.ptr = capi.new_ct(source._ptr, target._ptr) self._srs1_name = source.name self._srs2_name = target.name def __del__(self): "Deletes this Coordinate Transformation object." if self._ptr: capi.destroy_ct(self._ptr) def __str__(self): return 'Transform from "%s" to "%s"' % (self._srs1_name, self._srs2_name)
m-weigand/ccd_tools
refs/heads/master
tests/ccd_single/Fitquality/StartingModelsCC/generate_test_cases.py
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Generate multiple SIP spectra by varying the Cole-Cole parameters m, tau, and c """ import os import numpy as np import lib_cc.main frequencies = np.logspace(-2, 4, 20) cc_obj = lib_cc.main.get('logrho0_m_logtau_c', {'frequencies': frequencies}) data_list = [] for m in (0.1, 0.8): for c in np.linspace(0.05, 1.0, 4): for tau in np.logspace(np.log10(frequencies.min()), np.log10(frequencies.max()), 4): pars = [np.log(100), m, np.log(tau), c] rlnmag_rpha = cc_obj.forward(pars) rmag_rpha = rlnmag_rpha.copy() rmag_rpha[:, 0] = np.exp(rmag_rpha[:, 0]) data_list.append(rmag_rpha.flatten(order='F')) if not os.path.isdir('data'): os.makedirs('data') np.savetxt('data/frequencies.dat', frequencies) np.savetxt('data/data.dat', np.array(data_list))
joalder/bill-angels
refs/heads/master
bills/models.py
10644
from django.db import models # Create your models here.
dorotan/pythontraining
refs/heads/master
env/Lib/hmac.py
142
"""HMAC (Keyed-Hashing for Message Authentication) Python module. Implements the HMAC algorithm as described by RFC 2104. """ import warnings as _warnings from _operator import _compare_digest as compare_digest import hashlib as _hashlib trans_5C = bytes((x ^ 0x5C) for x in range(256)) trans_36 = bytes((x ^ 0x36) for x in range(256)) # The size of the digests returned by HMAC depends on the underlying # hashing module used. Use digest_size from the instance of HMAC instead. digest_size = None class HMAC: """RFC 2104 HMAC class. Also complies with RFC 4231. This supports the API for Cryptographic Hash Functions (PEP 247). """ blocksize = 64 # 512-bit HMAC; can be changed in subclasses. def __init__(self, key, msg = None, digestmod = None): """Create a new HMAC object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. *OR* A hashlib constructor returning a new hash object. *OR* A hash name suitable for hashlib.new(). Defaults to hashlib.md5. Implicit default to hashlib.md5 is deprecated and will be removed in Python 3.6. Note: key and msg must be a bytes or bytearray objects. """ if not isinstance(key, (bytes, bytearray)): raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__) if digestmod is None: _warnings.warn("HMAC() without an explicit digestmod argument " "is deprecated.", PendingDeprecationWarning, 2) digestmod = _hashlib.md5 if callable(digestmod): self.digest_cons = digestmod elif isinstance(digestmod, str): self.digest_cons = lambda d=b'': _hashlib.new(digestmod, d) else: self.digest_cons = lambda d=b'': digestmod.new(d) self.outer = self.digest_cons() self.inner = self.digest_cons() self.digest_size = self.inner.digest_size if hasattr(self.inner, 'block_size'): blocksize = self.inner.block_size if blocksize < 16: _warnings.warn('block_size of %d seems too small; using our ' 'default of %d.' % (blocksize, self.blocksize), RuntimeWarning, 2) blocksize = self.blocksize else: _warnings.warn('No block_size attribute on given digest object; ' 'Assuming %d.' % (self.blocksize), RuntimeWarning, 2) blocksize = self.blocksize # self.blocksize is the default blocksize. self.block_size is # effective block size as well as the public API attribute. self.block_size = blocksize if len(key) > blocksize: key = self.digest_cons(key).digest() key = key + bytes(blocksize - len(key)) self.outer.update(key.translate(trans_5C)) self.inner.update(key.translate(trans_36)) if msg is not None: self.update(msg) @property def name(self): return "hmac-" + self.inner.name def update(self, msg): """Update this hashing object with the string msg. """ self.inner.update(msg) def copy(self): """Return a separate copy of this hashing object. An update to this copy won't affect the original object. """ # Call __new__ directly to avoid the expensive __init__. other = self.__class__.__new__(self.__class__) other.digest_cons = self.digest_cons other.digest_size = self.digest_size other.inner = self.inner.copy() other.outer = self.outer.copy() return other def _current(self): """Return a hash object for the current state. To be used only internally with digest() and hexdigest(). """ h = self.outer.copy() h.update(self.inner.digest()) return h def digest(self): """Return the hash value of this hashing object. This returns a string containing 8-bit data. The object is not altered in any way by this function; you can continue updating the object after calling this function. """ h = self._current() return h.digest() def hexdigest(self): """Like digest(), but returns a string of hexadecimal digits instead. """ h = self._current() return h.hexdigest() def new(key, msg = None, digestmod = None): """Create a new hashing object and return it. key: The starting key for the hash. msg: if available, will immediately be hashed into the object's starting state. You can now feed arbitrary strings into the object using its update() method, and can ask for the hash value at any time by calling its digest() method. """ return HMAC(key, msg, digestmod)
scylladb/scylla-longevity-tests
refs/heads/master
sdcm/results_analyze.py
1
import os import logging import math import jinja2 import pprint from es import ES from send_email import Email from datetime import datetime from db_stats import TestStatsMixin log = logging.getLogger(__name__) pp = pprint.PrettyPrinter(indent=2) class QueryFilter(object): """ Definition of query filtering parameters """ SETUP_PARAMS = ['n_db_nodes', 'n_loaders', 'n_monitor_nodes'] SETUP_INSTANCE_PARAMS = ['instance_type_db', 'instance_type_loader', 'instance_type_monitor'] def __init__(self, test_doc, is_gce=False): self.test_doc = test_doc self.test_name = test_doc["_source"]["test_details"]["test_name"] self.is_gce = is_gce self.date_re = '/2018-*/' def setup_instance_params(self): return ['gce_' + param for param in self.SETUP_INSTANCE_PARAMS] if self.is_gce else self.SETUP_INSTANCE_PARAMS def filter_setup_details(self): setup_details = '' for param in self.SETUP_PARAMS + self.setup_instance_params(): if setup_details: setup_details += ' AND ' setup_details += 'setup_details.{}: {}'.format(param, self.test_doc['_source']['setup_details'][param]) return setup_details def filter_test_details(self): test_details = 'test_details.job_name:\"{}\" '.format( self.test_doc['_source']['test_details']['job_name'].split('/')[0]) test_details += self.test_cmd_details() test_details += ' AND test_details.time_completed: {}'.format(self.date_re) test_details += ' AND test_details.test_name: {}'.format(self.test_name.replace(":", "\:")) return test_details def test_cmd_details(self): raise NotImplementedError('Derived classes must implement this method.') def __call__(self, *args, **kwargs): try: return '{} AND {}'.format(self.filter_test_details(), self.filter_setup_details()) except KeyError: log.exception('Expected parameters for filtering are not found , test {}'.format(self.test_doc['_id'])) return None class QueryFilterCS(QueryFilter): _CMD = ('cassandra-stress', ) _PRELOAD_CMD = ('preload-cassandra-stress', ) _PARAMS = ('command', 'cl', 'rate threads', 'schema', 'mode', 'pop', 'duration') _PROFILE_PARAMS = ('command', 'profile', 'ops', 'rate threads', 'duration') def test_details_params(self): return self._CMD + self._PRELOAD_CMD if \ self.test_doc['_source']['test_details'].get(self._PRELOAD_CMD[0]) else self._CMD def cs_params(self): return self._PROFILE_PARAMS if self.test_name.endswith('profiles') else self._PARAMS def test_cmd_details(self): test_details = "" for cs in self.test_details_params(): for param in self.cs_params(): if param == 'rate threads': test_details += ' AND test_details.{}.rate\ threads: {}'.format( cs, self.test_doc['_source']['test_details'][cs][param]) elif param == 'duration' and cs.startswith('preload'): continue else: param_val = self.test_doc['_source']['test_details'][cs][param] if param in ['profile', 'ops']: param_val = "\"{}\"".format(param_val) test_details += ' AND test_details.{}.{}: {}'.format(cs, param, param_val) return test_details class QueryFilterScyllaBench(QueryFilter): _CMD = ('scylla-bench', ) _PARAMS = ('mode', 'workload', 'partition-count', 'clustering-row-count', 'concurrency', 'connection-count', 'replication-factor', 'duration') def test_cmd_details(self): test_details = ['AND test_details.{}.{}: {}'.format( cmd, param, self.test_doc['_source']['test_details'][cmd][param]) for param in self._PARAMS for cmd in self._CMD] return ' '.join(test_details) class BaseResultsAnalyzer(object): def __init__(self, es_index, es_doc_type, send_email=False, email_recipients=(), email_template_fp="", query_limit=1000, logger=None): self._es = ES() self._conf = self._es._conf self._es_index = es_index self._es_doc_type = es_doc_type self._limit = query_limit self._send_email = send_email self._email_recipients = email_recipients self._email_template_fp = email_template_fp self.log = logger if logger else log def get_all(self): """ Get all the test results in json format """ return self._es.search(index=self._es_index, size=self._limit) def get_test_by_id(self, test_id): """ Get test results by test id :param test_id: test id created by performance test :return: test results in json format """ if not self._es.exists(index=self._es_index, doc_type=self._es_doc_type, id=test_id): self.log.error('Test results not found: {}'.format(test_id)) return None return self._es.get(index=self._es_index, doc_type=self._es_doc_type, id=test_id) def _test_version(self, test_doc): if test_doc['_source'].get('versions'): for v in ('scylla-server', 'scylla-enterprise-server'): k = test_doc['_source']['versions'].get(v) if k: return k self.log.error('Scylla version is not found for test %s', test_doc['_id']) return None def render_to_html(self, results, html_file_path=""): """ Render analysis results to html template :param results: results dictionary :param html_file_path: Boolean, whether to save html file on disk :return: html string """ self.log.info("Rendering results to html using '%s' template...", self._email_template_fp) loader = jinja2.FileSystemLoader(os.path.dirname(os.path.abspath(__file__))) env = jinja2.Environment(loader=loader, autoescape=True) template = env.get_template(self._email_template_fp) html = template.render(results) if html_file_path: with open(html_file_path, "w") as f: f.write(html) self.log.info("HTML report saved to '%s'.", html_file_path) return html def send_email(self, subject, content, html=True, files=()): if self._send_email and self._email_recipients: self.log.debug('Send email to {}'.format(self._email_recipients)) em = Email() em.send(subject, content, html=html, recipients=self._email_recipients, files=files) else: self.log.warning("Won't send email (send_email: %s, recipients: %s)", self._send_email, self._email_recipients) def gen_kibana_dashboard_url(self, dashboard_path=""): return "%s/%s" % (self._conf.get('kibana_url'), dashboard_path) def check_regression(self): return NotImplementedError("check_regression should be implemented!") class PerformanceResultsAnalyzer(BaseResultsAnalyzer): """ Get performance test results from elasticsearch DB and analyze it to find a regression """ PARAMS = ['op rate', 'latency mean', 'latency 99th percentile'] def __init__(self, es_index, es_doc_type, send_email, email_recipients, logger=None): super(PerformanceResultsAnalyzer, self).__init__( es_index=es_index, es_doc_type=es_doc_type, send_email=send_email, email_recipients=email_recipients, email_template_fp="results_performance.html", logger=logger ) def _remove_non_stat_keys(self, stats): for non_stat_key in ['loader_idx', 'cpu_idx', 'keyspace_idx']: if non_stat_key in stats: del stats[non_stat_key] return stats def _test_stats(self, test_doc): # check if stats exists if 'results' not in test_doc['_source'] or 'stats_average' not in test_doc['_source']['results'] or \ 'stats_total' not in test_doc['_source']['results']: self.log.error('Cannot find one of the fields: results, results.stats_average, ' 'results.stats_total for test id: {}!'.format(test_doc['_id'])) return None stats_average = self._remove_non_stat_keys(test_doc['_source']['results']['stats_average']) stats_total = test_doc['_source']['results']['stats_total'] if not stats_average or not stats_total: self.log.error('Cannot find average/total results for test: {}!'.format(test_doc['_id'])) return None # replace average by total value for op rate stats_average['op rate'] = stats_total['op rate'] return stats_average def _test_version(self, test_doc): if test_doc['_source'].get('versions'): for v in ('scylla-server', 'scylla-enterprise-server'): k = test_doc['_source']['versions'].get(v) if k: return k self.log.error('Scylla version is not found for test %s', test_doc['_id']) return None def _get_grafana_snapshot(self, test_doc): grafana_snapshot = test_doc['_source']['test_details'].get('grafana_snapshot') return grafana_snapshot if isinstance(grafana_snapshot, list) else [grafana_snapshot] def _get_setup_details(self, test_doc, is_gce): setup_details = {'cluster_backend': test_doc['_source']['setup_details'].get('cluster_backend')} if "aws" in setup_details['cluster_backend']: setup_details['ami_id_db_scylla'] = test_doc['_source']['setup_details']['ami_id_db_scylla'] for sp in QueryFilter(test_doc, is_gce).setup_instance_params(): setup_details.update([(sp.replace('gce_', ''), test_doc['_source']['setup_details'].get(sp))]) return setup_details def _get_best_value(self, key, val1, val2): if key == self.PARAMS[0]: # op rate return val1 if val1 > val2 else val2 return val1 if val2 == 0 or val1 < val2 else val2 # latency def _query_filter(self, test_doc, is_gce): return QueryFilterScyllaBench(test_doc, is_gce)() if test_doc['_source']['test_details'].get('scylla-bench')\ else QueryFilterCS(test_doc, is_gce)() def cmp(self, src, dst, version_dst, best_test_id): """ Compare current test results with the best results :param src: current test results :param dst: previous best test results :param version_dst: scylla server version to compare with :param best_test_id: the best results test id(for each parameter) :return: dictionary with compare calculation results """ cmp_res = dict(version_dst=version_dst, res=dict()) for param in self.PARAMS: param_key_name = param.replace(' ', '_') status = 'Progress' try: delta = src[param] - dst[param] change_perc = int(math.fabs(delta) * 100 / dst[param]) best_id = best_test_id[param] if (param.startswith('latency') and delta > 0) or (param == 'op rate' and delta < 0): status = 'Regression' if change_perc == 0: status = "Difference" cmp_res['res'][param_key_name] = dict(percent='{}%'.format(change_perc), val=src[param], best_val=dst[param], best_id=best_id, status=status) except TypeError: self.log.exception('Failed to compare {} results: {} vs {}, version {}'.format( param, src[param], dst[param], version_dst)) return cmp_res def check_regression(self, test_id, is_gce=False): """ Get test results by id, filter similar results and calculate max values for each version, then compare with max in the test version and all the found versions. Save the analysis in log and send by email. :param test_id: test id created by performance test :param is_gce: is gce instance :return: True/False """ # get test res from sortedcontainers import SortedDict doc = self.get_test_by_id(test_id) if not doc: self.log.error('Cannot find test by id: {}!'.format(test_id)) return False self.log.debug(pp.pformat(doc)) test_stats = self._test_stats(doc) if not test_stats: return False # filter tests query = self._query_filter(doc, is_gce) if not query: return False self.log.debug("Query to ES: %s", query) filter_path = ['hits.hits._id', 'hits.hits._source.results.stats_average', 'hits.hits._source.results.stats_total', 'hits.hits._source.results.throughput', 'hits.hits._source.versions'] tests_filtered = self._es.search(index=self._es_index, q=query, filter_path=filter_path, size=self._limit) if not tests_filtered: self.log.info('Cannot find tests with the same parameters as {}'.format(test_id)) return False # get the best res for all versions of this job group_by_version = dict() # Example: # group_by_version = { # "2.3.rc1": { # "tests": { # SortedDict(), # "20180726": { # "latency 99th percentile": 10.3, # "op rate": 15034.3 # #... # } # }, # # "stats_best": { # "op rate": 0, # "latency mean": 0, # }, # "best_test_id": { # "op rate": "9b4a0a287", # "latency mean": "9b4a0a287", # # } # } # } # Find best results for each version for tr in tests_filtered['hits']['hits']: if tr['_id'] == test_id: # filter the current test continue if '_source' not in tr: # non-valid record? self.log.error('Skip non-valid test: %s', tr['_id']) continue version_info = self._test_version(tr) version = version_info['version'] if not version: continue curr_test_stats = self._test_stats(tr) if not curr_test_stats: continue if version not in group_by_version: group_by_version[version] = dict(tests=SortedDict(), stats_best=dict(), best_test_id=dict()) group_by_version[version]['stats_best'] = {k: 0 for k in self.PARAMS} group_by_version[version]['best_test_id'] = {k: version_info["commit_id"] for k in self.PARAMS} group_by_version[version]['tests'][version_info['date']] = curr_test_stats old_best = group_by_version[version]['stats_best'] group_by_version[version]['stats_best'] =\ {k: self._get_best_value(k, curr_test_stats[k], old_best[k]) for k in self.PARAMS if k in curr_test_stats and k in old_best} # replace best test id if best value changed for k in self.PARAMS: if k in curr_test_stats and k in old_best and\ group_by_version[version]['stats_best'][k] == curr_test_stats[k]: group_by_version[version]['best_test_id'][k] = version_info["commit_id"] res_list = list() # compare with the best in the test version and all the previous versions test_version_info = self._test_version(doc) test_version = test_version_info['version'] for version in group_by_version.keys(): if version == test_version and not len(group_by_version[test_version]['tests']): self.log.info('No previous tests in the current version {} to compare'.format(test_version)) continue cmp_res = self.cmp(test_stats, group_by_version[version]['stats_best'], version, group_by_version[version]['best_test_id']) res_list.append(cmp_res) if not res_list: self.log.info('No test results to compare with') return False # send results by email full_test_name = doc["_source"]["test_details"]["test_name"] test_start_time = datetime.utcfromtimestamp(float(doc["_source"]["test_details"]["start_time"])) cassandra_stress = doc['_source']['test_details'].get('cassandra-stress') dashboard_path = "app/kibana#/dashboard/03414b70-0e89-11e9-a976-2fe0f5890cd0?_g=()" results = dict(test_name=full_test_name, test_start_time=str(test_start_time), test_version=test_version_info, res_list=res_list, setup_details=self._get_setup_details(doc, is_gce), prometheus_stats={stat: doc["_source"]["results"].get(stat, {}) for stat in TestStatsMixin.PROMETHEUS_STATS}, prometheus_stats_units=TestStatsMixin.PROMETHEUS_STATS_UNITS, grafana_snapshot=self._get_grafana_snapshot(doc), cs_raw_cmd=cassandra_stress.get('raw_cmd', "") if cassandra_stress else "", job_url=doc['_source']['test_details'].get('job_url', ""), dashboard_master=self.gen_kibana_dashboard_url(dashboard_path), ) self.log.debug('Regression analysis:') self.log.debug(pp.pformat(results)) test_name = full_test_name.split('.')[-1] # Example: longevity_test.py:LongevityTest.test_custom_time subject = 'Performance Regression Compare Results - {} - {}'.format(test_name, test_version) html = self.render_to_html(results) self.send_email(subject, html) return True
163gal/Time-Line
refs/heads/master
libs/wx/lib/agw/ultimatelistctrl.py
2
# -*- coding: utf-8 -*- # --------------------------------------------------------------------------------- # # ULTIMATELISTCTRL wxPython IMPLEMENTATION # Inspired by and heavily based on the wxWidgets C++ generic version of wxListCtrl. # # Andrea Gavana, @ 08 May 2009 # Latest Revision: 16 Apr 2010, 23.00 GMT # # # TODO List # # 1) Subitem selection; # 2) Watermark? (almost, does not work very well :-( ); # 3) Groups? (Maybe, check ObjectListView); # 4) Scrolling items as headers and footers; # 5) Alpha channel for text/background of items; # 6) Custom renderers for headers/footers (done); # 7) Fading in and out on mouse motion (a la Windows Vista Aero); # 8) Sub-text for headers/footers (grey text below the header/footer text); # 9) Fixing the columns to the left or right side of the control layout; # 10) Skins for header and scrollbars (implemented for headers/footers). # # # For all kind of problems, requests of enhancements and bug reports, please # write to me at: # # andrea.gavana@gmail.com # gavana@kpo.kz # # Or, obviously, to the wxPython mailing list!!! # # # End Of Comments # --------------------------------------------------------------------------------- # """ Description =========== UltimateListCtrl is a class that mimics the behaviour of `wx.ListCtrl`, with almost the same base functionalities plus some more enhancements. This class does not rely on the native control, as it is a full owner-drawn list control. In addition to the standard `wx.ListCtrl` behaviour this class supports: Appearance ========== * Multiple images for items/subitems; * Images can be of any size and not limited to a single specific pair of `width`, `height` as it is the case of `wx.ImageList`. Simply use L{PyImageList} instead of `wx.ImageList` to add your images. * Font, colour, background, custom renderers and formatting for items and subitems; * Ability to add persistent data to an item using L{SetItemPyData} and L{GetItemPyData}: the data can be any Python object and not necessarily an integer as in `wx.ListCtrl`; * CheckBox-type items and subitems; * RadioButton-type items and subitems; * Overflowing items/subitems, a la `wx.grid.Grid`, i.e. an item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it; * Hyperlink-type items and subitems: they look like an hyperlink, with the proper mouse cursor on hovering; * Multiline text items and subitems; * Variable row heights depending on the item/subitem kind/text/window; * User defined item/subitem renderers: these renderer classes **must** implement the methods `DrawSubItem`, `GetLineHeight` and `GetSubItemWidth` (see the demo); * Enabling/disabling items (together with their plain or grayed out icons); * Whatever non-toplevel widget can be attached next to an item/subitem; * Column headers are fully customizable in terms of icons, colour, font, alignment etc...; * Column headers can have their own checkbox/radiobutton; * Column footers are fully customizable in terms of icons, colour, font, alignment etc...; * Column footers can have their own checkbox/radiobutton; * Ability to hide/show columns; * Default selection style, gradient (horizontal/vertical) selection style and Windows Vista selection style. And a lot more. Check the demo for an almost complete review of the functionalities. Window Styles ============= This class supports the following window styles: =============================== =========== ==================================================================================================== Window Styles Hex Value Description =============================== =========== ==================================================================================================== ``ULC_VRULES`` 0x1 Draws light vertical rules between rows in report mode. ``ULC_HRULES`` 0x2 Draws light horizontal rules between rows in report mode. ``ULC_ICON`` 0x4 Large icon view, with optional labels. ``ULC_SMALL_ICON`` 0x8 Small icon view, with optional labels. ``ULC_LIST`` 0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a `wx.ListBox`. ``ULC_REPORT`` 0x20 Single or multicolumn report view, with optional header. ``ULC_ALIGN_TOP`` 0x40 Icons align to the top. Win32 default, Win32 only. ``ULC_ALIGN_LEFT`` 0x80 Icons align to the left. ``ULC_AUTOARRANGE`` 0x100 Icons arrange themselves. Win32 only. ``ULC_VIRTUAL`` 0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``. ``ULC_EDIT_LABELS`` 0x400 Labels are editable: the application will be notified when editing starts. ``ULC_NO_HEADER`` 0x800 No header in report mode. ``ULC_NO_SORT_HEADER`` 0x1000 No Docs. ``ULC_SINGLE_SEL`` 0x2000 Single selection (default is multiple). ``ULC_SORT_ASCENDING`` 0x4000 Sort in ascending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.) ``ULC_SORT_DESCENDING`` 0x8000 Sort in descending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.) ``ULC_TILE`` 0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented). ``ULC_NO_HIGHLIGHT`` 0x20000 No highlight when an item is selected. ``ULC_STICKY_HIGHLIGHT`` 0x40000 Items are selected by simply hovering on them, with no need to click on them. ``ULC_STICKY_NOSELEVENT`` 0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style. ``ULC_SEND_LEFTCLICK`` 0x100000 Send a left click event when an item is selected. ``ULC_HAS_VARIABLE_ROW_HEIGHT`` 0x200000 The list has variable row heights. ``ULC_AUTO_CHECK_CHILD`` 0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column. ``ULC_AUTO_TOGGLE_CHILD`` 0x800000 When a column header has a checkbox associated, toggle all the subitems in that column. ``ULC_AUTO_CHECK_PARENT`` 0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well. ``ULC_SHOW_TOOLTIPS`` 0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text. ``ULC_HOT_TRACKING`` 0x4000000 Enable hot tracking of items on mouse motion. ``ULC_BORDER_SELECT`` 0x8000000 Changes border colour whan an item is selected, instead of highlighting the item. ``ULC_TRACK_SELECT`` 0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`. ``ULC_HEADER_IN_ALL_VIEWS`` 0x20000000 Show column headers in all view modes. ``ULC_NO_FULL_ROW_SELECT`` 0x40000000 When an item is selected, the only the item in the first column is highlighted. ``ULC_FOOTER`` 0x80000000 Show a footer too (only when header is present). =============================== =========== ==================================================================================================== Events Processing ================= This class processes the following events: ======================================== ==================================================================================================== Event Name Description ======================================== ==================================================================================================== ``EVT_LIST_BEGIN_DRAG`` Begin dragging with the left mouse button. ``EVT_LIST_BEGIN_RDRAG`` Begin dragging with the right mouse button. ``EVT_LIST_BEGIN_LABEL_EDIT`` Begin editing a label. This can be prevented by calling `Veto()`. ``EVT_LIST_END_LABEL_EDIT`` Finish editing a label. This can be prevented by calling `Veto()`. ``EVT_LIST_DELETE_ITEM`` An item was deleted. ``EVT_LIST_DELETE_ALL_ITEMS`` All items were deleted. ``EVT_LIST_KEY_DOWN`` A key has been pressed. ``EVT_LIST_INSERT_ITEM`` An item has been inserted. ``EVT_LIST_COL_CLICK`` A column (`m_col`) has been left-clicked. ``EVT_LIST_COL_RIGHT_CLICK`` A column (`m_col`) has been right-clicked. ``EVT_LIST_COL_BEGIN_DRAG`` The user started resizing a column - can be vetoed. ``EVT_LIST_COL_END_DRAG`` The user finished resizing a column. ``EVT_LIST_COL_DRAGGING`` The divider between columns is being dragged. ``EVT_LIST_ITEM_SELECTED`` The item has been selected. ``EVT_LIST_ITEM_DESELECTED`` The item has been deselected. ``EVT_LIST_ITEM_RIGHT_CLICK`` The right mouse button has been clicked on an item. ``EVT_LIST_ITEM_MIDDLE_CLICK`` The middle mouse button has been clicked on an item. ``EVT_LIST_ITEM_ACTIVATED`` The item has been activated (``ENTER`` or double click). ``EVT_LIST_ITEM_FOCUSED`` The currently focused item has changed. ``EVT_LIST_CACHE_HINT`` Prepare cache for a virtual list control. ``EVT_LIST_ITEM_CHECKING`` An item/subitem is being checked. ``EVT_LIST_ITEM_CHECKED`` An item/subitem has been checked. ``EVT_LIST_COL_CHECKING`` A column header is being checked. ``EVT_LIST_COL_CHECKED`` A column header has being checked. ``EVT_LIST_FOOTER_CHECKING`` A column footer is being checked. ``EVT_LIST_FOOTER_CHECKED`` A column footer has being checked. ``EVT_LIST_ITEM_HYPERLINK`` An hyperlink item has been clicked. ``EVT_LIST_FOOTER_CLICK`` The user left-clicked on a column footer. ``EVT_LIST_FOOTER_RIGHT_CLICK`` The user right-clicked on a column footer. ``EVT_LIST_ITEM_LEFT_CLICK`` Send a left-click event after an item is selected. ``EVT_LIST_END_DRAG`` Notify an end-drag operation. ======================================== ==================================================================================================== Supported Platforms =================== UltimateListCtrl has been tested on the following platforms: * Windows (Windows XP); License And Version =================== UltimateListCtrl is distributed under the wxPython license. Latest Revision: Andrea Gavana @ 16 Apr 2010, 23.00 GMT Version 0.6 """ import wx import math import bisect import types import zlib import cStringIO from wx.lib.expando import ExpandoTextCtrl # Version Info __version__ = "0.6" # ---------------------------------------------------------------------------- # UltimateListCtrl constants # ---------------------------------------------------------------------------- # style flags ULC_VRULES = wx.LC_VRULES ULC_HRULES = wx.LC_HRULES ULC_ICON = wx.LC_ICON ULC_SMALL_ICON = wx.LC_SMALL_ICON ULC_LIST = wx.LC_LIST ULC_REPORT = wx.LC_REPORT ULC_TILE = 0x10000 ULC_ALIGN_TOP = wx.LC_ALIGN_TOP ULC_ALIGN_LEFT = wx.LC_ALIGN_LEFT ULC_AUTOARRANGE = wx.LC_AUTOARRANGE ULC_VIRTUAL = wx.LC_VIRTUAL ULC_EDIT_LABELS = wx.LC_EDIT_LABELS ULC_NO_HEADER = wx.LC_NO_HEADER ULC_NO_SORT_HEADER = wx.LC_NO_SORT_HEADER ULC_SINGLE_SEL = wx.LC_SINGLE_SEL ULC_SORT_ASCENDING = wx.LC_SORT_ASCENDING ULC_SORT_DESCENDING = wx.LC_SORT_DESCENDING ULC_NO_HIGHLIGHT = 0x20000 ULC_STICKY_HIGHLIGHT = 0x40000 ULC_STICKY_NOSELEVENT = 0x80000 ULC_SEND_LEFTCLICK = 0x100000 ULC_HAS_VARIABLE_ROW_HEIGHT = 0x200000 ULC_AUTO_CHECK_CHILD = 0x400000 # only meaningful for checkboxes ULC_AUTO_TOGGLE_CHILD = 0x800000 # only meaningful for checkboxes ULC_AUTO_CHECK_PARENT = 0x1000000 # only meaningful for checkboxes ULC_SHOW_TOOLTIPS = 0x2000000 # shows tooltips on items with ellipsis (...) ULC_HOT_TRACKING = 0x4000000 # enable hot tracking on mouse motion ULC_BORDER_SELECT = 0x8000000 # changes border colour whan an item is selected, instead of highlighting the item ULC_TRACK_SELECT = 0x10000000 # Enables hot-track selection in a list control. Hot track selection means that an item # is automatically selected when the cursor remains over the item for a certain period # of time. The delay is retrieved on Windows using the win32api call # win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME), and is defaulted to 400ms # on other platforms. This style applies to all styles of UltimateListCtrl. ULC_HEADER_IN_ALL_VIEWS = 0x20000000 # Show column headers in all view modes ULC_NO_FULL_ROW_SELECT = 0x40000000 # When an item is selected, the only the item in the first column is highlighted ULC_FOOTER = 0x80000000 # Show a footer too (only when header is present) ULC_MASK_TYPE = ULC_ICON | ULC_SMALL_ICON | ULC_LIST | ULC_REPORT | ULC_TILE ULC_MASK_ALIGN = ULC_ALIGN_TOP | ULC_ALIGN_LEFT ULC_MASK_SORT = ULC_SORT_ASCENDING | ULC_SORT_DESCENDING # for compatibility only ULC_USER_TEXT = ULC_VIRTUAL # Omitted because # (a) too much detail # (b) not enough style flags # (c) not implemented anyhow in the generic version # # ULC_NO_SCROLL # ULC_NO_LABEL_WRAP # ULC_OWNERDRAW_FIXED # ULC_SHOW_SEL_ALWAYS # Mask flags to tell app/GUI what fields of UltimateListItem are valid ULC_MASK_STATE = wx.LIST_MASK_STATE ULC_MASK_TEXT = wx.LIST_MASK_TEXT ULC_MASK_IMAGE = wx.LIST_MASK_IMAGE ULC_MASK_DATA = wx.LIST_MASK_DATA ULC_SET_ITEM = wx.LIST_SET_ITEM ULC_MASK_WIDTH = wx.LIST_MASK_WIDTH ULC_MASK_FORMAT = wx.LIST_MASK_FORMAT ULC_MASK_FONTCOLOUR = 0x0080 ULC_MASK_FONT = 0x0100 ULC_MASK_BACKCOLOUR = 0x0200 ULC_MASK_KIND = 0x0400 ULC_MASK_ENABLE = 0x0800 ULC_MASK_CHECK = 0x1000 ULC_MASK_HYPERTEXT = 0x2000 ULC_MASK_WINDOW = 0x4000 ULC_MASK_PYDATA = 0x8000 ULC_MASK_SHOWN = 0x10000 ULC_MASK_RENDERER = 0x20000 ULC_MASK_OVERFLOW = 0x40000 ULC_MASK_FOOTER_TEXT = 0x80000 ULC_MASK_FOOTER_IMAGE = 0x100000 ULC_MASK_FOOTER_FORMAT = 0x200000 ULC_MASK_FOOTER_FONT = 0x400000 ULC_MASK_FOOTER_CHECK = 0x800000 ULC_MASK_FOOTER_KIND = 0x1000000 # State flags for indicating the state of an item ULC_STATE_DONTCARE = wx.LIST_STATE_DONTCARE ULC_STATE_DROPHILITED = wx.LIST_STATE_DROPHILITED # MSW only ULC_STATE_FOCUSED = wx.LIST_STATE_FOCUSED ULC_STATE_SELECTED = wx.LIST_STATE_SELECTED ULC_STATE_CUT = wx.LIST_STATE_CUT # MSW only ULC_STATE_DISABLED = wx.LIST_STATE_DISABLED # OS2 only ULC_STATE_FILTERED = wx.LIST_STATE_FILTERED # OS2 only ULC_STATE_INUSE = wx.LIST_STATE_INUSE # OS2 only ULC_STATE_PICKED = wx.LIST_STATE_PICKED # OS2 only ULC_STATE_SOURCE = wx.LIST_STATE_SOURCE # OS2 only # Hit test flags, used in HitTest ULC_HITTEST_ABOVE = wx.LIST_HITTEST_ABOVE # Above the client area. ULC_HITTEST_BELOW = wx.LIST_HITTEST_BELOW # Below the client area. ULC_HITTEST_NOWHERE = wx.LIST_HITTEST_NOWHERE # In the client area but below the last item. ULC_HITTEST_ONITEMICON = wx.LIST_HITTEST_ONITEMICON # On the bitmap associated with an item. ULC_HITTEST_ONITEMLABEL = wx.LIST_HITTEST_ONITEMLABEL # On the label (string) associated with an item. ULC_HITTEST_ONITEMRIGHT = wx.LIST_HITTEST_ONITEMRIGHT # In the area to the right of an item. ULC_HITTEST_ONITEMSTATEICON = wx.LIST_HITTEST_ONITEMSTATEICON # On the state icon for a tree view item that is in a user-defined state. ULC_HITTEST_TOLEFT = wx.LIST_HITTEST_TOLEFT # To the left of the client area. ULC_HITTEST_TORIGHT = wx.LIST_HITTEST_TORIGHT # To the right of the client area. ULC_HITTEST_ONITEMCHECK = 0x1000 # On the checkbox (if any) ULC_HITTEST_ONITEM = ULC_HITTEST_ONITEMICON | ULC_HITTEST_ONITEMLABEL | ULC_HITTEST_ONITEMSTATEICON | ULC_HITTEST_ONITEMCHECK # Flags for GetNextItem (MSW only except ULC_NEXT_ALL) ULC_NEXT_ABOVE = wx.LIST_NEXT_ABOVE # Searches for an item above the specified item ULC_NEXT_ALL = wx.LIST_NEXT_ALL # Searches for subsequent item by index ULC_NEXT_BELOW = wx.LIST_NEXT_BELOW # Searches for an item below the specified item ULC_NEXT_LEFT = wx.LIST_NEXT_LEFT # Searches for an item to the left of the specified item ULC_NEXT_RIGHT = wx.LIST_NEXT_RIGHT # Searches for an item to the right of the specified item # Alignment flags for Arrange (MSW only except ULC_ALIGN_LEFT) ULC_ALIGN_DEFAULT = wx.LIST_ALIGN_DEFAULT ULC_ALIGN_SNAP_TO_GRID = wx.LIST_ALIGN_SNAP_TO_GRID # Column format (MSW only except ULC_FORMAT_LEFT) ULC_FORMAT_LEFT = wx.LIST_FORMAT_LEFT ULC_FORMAT_RIGHT = wx.LIST_FORMAT_RIGHT ULC_FORMAT_CENTRE = wx.LIST_FORMAT_CENTRE ULC_FORMAT_CENTER = ULC_FORMAT_CENTRE # Autosize values for SetColumnWidth ULC_AUTOSIZE = wx.LIST_AUTOSIZE ULC_AUTOSIZE_USEHEADER = wx.LIST_AUTOSIZE_USEHEADER # partly supported by generic version ULC_AUTOSIZE_FILL = -3 # Flag values for GetItemRect ULC_RECT_BOUNDS = wx.LIST_RECT_BOUNDS ULC_RECT_ICON = wx.LIST_RECT_ICON ULC_RECT_LABEL = wx.LIST_RECT_LABEL # Flag values for FindItem (MSW only) ULC_FIND_UP = wx.LIST_FIND_UP ULC_FIND_DOWN = wx.LIST_FIND_DOWN ULC_FIND_LEFT = wx.LIST_FIND_LEFT ULC_FIND_RIGHT = wx.LIST_FIND_RIGHT # Items/subitems rect ULC_GETSUBITEMRECT_WHOLEITEM = wx.LIST_GETSUBITEMRECT_WHOLEITEM # ---------------------------------------------------------------------------- # UltimateListCtrl event macros # ---------------------------------------------------------------------------- wxEVT_COMMAND_LIST_BEGIN_DRAG = wx.wxEVT_COMMAND_LIST_BEGIN_DRAG wxEVT_COMMAND_LIST_BEGIN_RDRAG = wx.wxEVT_COMMAND_LIST_BEGIN_RDRAG wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT = wx.wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT wxEVT_COMMAND_LIST_END_LABEL_EDIT = wx.wxEVT_COMMAND_LIST_END_LABEL_EDIT wxEVT_COMMAND_LIST_DELETE_ITEM = wx.wxEVT_COMMAND_LIST_DELETE_ITEM wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS = wx.wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS wxEVT_COMMAND_LIST_ITEM_SELECTED = wx.wxEVT_COMMAND_LIST_ITEM_SELECTED wxEVT_COMMAND_LIST_ITEM_DESELECTED = wx.wxEVT_COMMAND_LIST_ITEM_DESELECTED wxEVT_COMMAND_LIST_KEY_DOWN = wx.wxEVT_COMMAND_LIST_KEY_DOWN wxEVT_COMMAND_LIST_INSERT_ITEM = wx.wxEVT_COMMAND_LIST_INSERT_ITEM wxEVT_COMMAND_LIST_COL_CLICK = wx.wxEVT_COMMAND_LIST_COL_CLICK wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK = wx.wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK = wx.wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK wxEVT_COMMAND_LIST_ITEM_ACTIVATED = wx.wxEVT_COMMAND_LIST_ITEM_ACTIVATED wxEVT_COMMAND_LIST_CACHE_HINT = wx.wxEVT_COMMAND_LIST_CACHE_HINT wxEVT_COMMAND_LIST_COL_RIGHT_CLICK = wx.wxEVT_COMMAND_LIST_COL_RIGHT_CLICK wxEVT_COMMAND_LIST_COL_BEGIN_DRAG = wx.wxEVT_COMMAND_LIST_COL_BEGIN_DRAG wxEVT_COMMAND_LIST_COL_DRAGGING = wx.wxEVT_COMMAND_LIST_COL_DRAGGING wxEVT_COMMAND_LIST_COL_END_DRAG = wx.wxEVT_COMMAND_LIST_COL_END_DRAG wxEVT_COMMAND_LIST_ITEM_FOCUSED = wx.wxEVT_COMMAND_LIST_ITEM_FOCUSED wxEVT_COMMAND_LIST_FOOTER_CLICK = wx.NewEventType() wxEVT_COMMAND_LIST_FOOTER_RIGHT_CLICK = wx.NewEventType() wxEVT_COMMAND_LIST_FOOTER_CHECKING = wx.NewEventType() wxEVT_COMMAND_LIST_FOOTER_CHECKED = wx.NewEventType() wxEVT_COMMAND_LIST_ITEM_LEFT_CLICK = wx.NewEventType() wxEVT_COMMAND_LIST_ITEM_CHECKING = wx.NewEventType() wxEVT_COMMAND_LIST_ITEM_CHECKED = wx.NewEventType() wxEVT_COMMAND_LIST_ITEM_HYPERLINK = wx.NewEventType() wxEVT_COMMAND_LIST_END_DRAG = wx.NewEventType() wxEVT_COMMAND_LIST_COL_CHECKING = wx.NewEventType() wxEVT_COMMAND_LIST_COL_CHECKED = wx.NewEventType() EVT_LIST_BEGIN_DRAG = wx.EVT_LIST_BEGIN_DRAG EVT_LIST_BEGIN_RDRAG = wx.EVT_LIST_BEGIN_RDRAG EVT_LIST_BEGIN_LABEL_EDIT = wx.EVT_LIST_BEGIN_LABEL_EDIT EVT_LIST_END_LABEL_EDIT = wx.EVT_LIST_END_LABEL_EDIT EVT_LIST_DELETE_ITEM = wx.EVT_LIST_DELETE_ITEM EVT_LIST_DELETE_ALL_ITEMS = wx.EVT_LIST_DELETE_ALL_ITEMS EVT_LIST_KEY_DOWN = wx.EVT_LIST_KEY_DOWN EVT_LIST_INSERT_ITEM = wx.EVT_LIST_INSERT_ITEM EVT_LIST_COL_CLICK = wx.EVT_LIST_COL_CLICK EVT_LIST_COL_RIGHT_CLICK = wx.EVT_LIST_COL_RIGHT_CLICK EVT_LIST_COL_BEGIN_DRAG = wx.EVT_LIST_COL_BEGIN_DRAG EVT_LIST_COL_END_DRAG = wx.EVT_LIST_COL_END_DRAG EVT_LIST_COL_DRAGGING = wx.EVT_LIST_COL_DRAGGING EVT_LIST_ITEM_SELECTED = wx.EVT_LIST_ITEM_SELECTED EVT_LIST_ITEM_DESELECTED = wx.EVT_LIST_ITEM_DESELECTED EVT_LIST_ITEM_RIGHT_CLICK = wx.EVT_LIST_ITEM_RIGHT_CLICK EVT_LIST_ITEM_MIDDLE_CLICK = wx.EVT_LIST_ITEM_MIDDLE_CLICK EVT_LIST_ITEM_ACTIVATED = wx.EVT_LIST_ITEM_ACTIVATED EVT_LIST_ITEM_FOCUSED = wx.EVT_LIST_ITEM_FOCUSED EVT_LIST_CACHE_HINT = wx.EVT_LIST_CACHE_HINT EVT_LIST_ITEM_LEFT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_LEFT_CLICK, 1) EVT_LIST_ITEM_CHECKING = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_CHECKING, 1) EVT_LIST_ITEM_CHECKED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_CHECKED, 1) EVT_LIST_ITEM_HYPERLINK = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_HYPERLINK, 1) EVT_LIST_END_DRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_END_DRAG, 1) EVT_LIST_COL_CHECKING = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_CHECKING, 1) EVT_LIST_COL_CHECKED = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_CHECKED, 1) EVT_LIST_FOOTER_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_CLICK, 1) EVT_LIST_FOOTER_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_RIGHT_CLICK, 1) EVT_LIST_FOOTER_CHECKING = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_CHECKING, 1) EVT_LIST_FOOTER_CHECKED = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_CHECKED, 1) # NOTE: If using the wxExtListBox visual attributes works everywhere then this can # be removed, as well as the #else case below. _USE_VISATTR = 0 # ---------------------------------------------------------------------------- # Constants # ---------------------------------------------------------------------------- SCROLL_UNIT_X = 15 SCROLL_UNIT_Y = 15 # the spacing between the lines (in report mode) LINE_SPACING = 0 # extra margins around the text label EXTRA_WIDTH = 4 EXTRA_HEIGHT = 4 if wx.Platform == "__WXGTK__": EXTRA_HEIGHT = 6 # margin between the window and the items EXTRA_BORDER_X = 2 EXTRA_BORDER_Y = 2 # offset for the header window HEADER_OFFSET_X = 1 HEADER_OFFSET_Y = 1 # margin between rows of icons in [small] icon view MARGIN_BETWEEN_ROWS = 6 # when autosizing the columns, add some slack AUTOSIZE_COL_MARGIN = 10 # default and minimal widths for the header columns WIDTH_COL_DEFAULT = 80 WIDTH_COL_MIN = 10 # the space between the image and the text in the report mode IMAGE_MARGIN_IN_REPORT_MODE = 5 # the space between the image and the text in the report mode in header HEADER_IMAGE_MARGIN_IN_REPORT_MODE = 2 # and the width of the icon, if any MARGIN_BETWEEN_TEXT_AND_ICON = 2 # Background Image Style _StyleTile = 0 _StyleStretch = 1 # Windows Vista Colours _rgbSelectOuter = wx.Colour(170, 200, 245) _rgbSelectInner = wx.Colour(230, 250, 250) _rgbSelectTop = wx.Colour(210, 240, 250) _rgbSelectBottom = wx.Colour(185, 215, 250) _rgbNoFocusTop = wx.Colour(250, 250, 250) _rgbNoFocusBottom = wx.Colour(235, 235, 235) _rgbNoFocusOuter = wx.Colour(220, 220, 220) _rgbNoFocusInner = wx.Colour(245, 245, 245) # Mouse hover time for track selection HOVER_TIME = 400 if wx.Platform == "__WXMSW__": try: import win32gui, win32con HOVER_TIME = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME) except ImportError: pass # For PyImageList IL_FIXED_SIZE = 0 IL_VARIABLE_SIZE = 1 # ---------------------------------------------------------------------------- # Functions # ---------------------------------------------------------------------------- # Utility method def to_list(input): """ Converts the input data into a Python list. :param `input`: can be an integer or a Python list (in which case nothing will be done to `input`. """ if isinstance(input, types.ListType): return input elif isinstance(input, types.IntType): return [input] else: raise Exception("Invalid parameter passed to `to_list`: only integers and list are accepted.") def CheckVariableRowHeight(listCtrl, text): """ Checks whether a text contains multiline strings and if the `listCtrl` window style is compatible with multiline strings. :param `listCtrl`: an instance of L{UltimateListCtrl}; :param `text`: the text to analyze. """ if not listCtrl.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): if "\n" in text: raise Exception("Multiline text items are not allowed without the ULC_HAS_VARIABLE_ROW_HEIGHT style.") def CreateListItem(itemOrId, col): """ Creates a new instance of L{UltimateListItem}. :param `itemOrId`: can be an instance of L{UltimateListItem} or an integer; :param `col`: the item column. """ if type(itemOrId) == types.IntType: item = UltimateListItem() item._itemId = itemOrId item._col = col else: item = itemOrId return item # ---------------------------------------------------------------------------- def MakeDisabledBitmap(original): """ Creates a disabled-looking bitmap starting from the input one. :param `original`: an instance of `wx.Bitmap` to be greyed-out. """ img = original.ConvertToImage() return wx.BitmapFromImage(img.ConvertToGreyscale()) # ---------------------------------------------------------------------------- #---------------------------------------------------------------------- def GetdragcursorData(): return zlib.decompress( "x\xda\xeb\x0c\xf0s\xe7\xe5\x92\xe2b``\xe0\xf5\xf4p\t\x02\xd2\xa2@,\xcf\xc1\ \x06$9z\xda>\x00)\xce\x02\x8f\xc8b\x06\x06na\x10fd\x985G\x02(\xd8W\xe2\x1aQ\ \xe2\x9c\x9f\x9b\x9b\x9aW\xc2\x90\xec\x11\xe4\xab\x90\x9cQ\x9a\x97\x9d\x93\ \x9a\xa7`l\xa4\x90\x99\x9e\x97_\x94\x9a\xc2\xeb\x18\xec\xec\xe9i\xa5\xa0\xa7\ W\xa5\xaa\x07\x01P:7\x1eH\xe4\xe8\xe9\xd9\x808\x11\xbc\x1e\xae\x11V\n\x06@`\ \xeehd\n\xa2-\x0c,\x8cA\xb4\x9b\t\x94o\xe2b\x08\xa2\xcd\\L\xdd@\xb4\xab\x85\ \x993\x886v\xb6p\x02\xd1\x86N\xa6\x16\x12\xf7~\xdf\x05\xbal\xa9\xa7\x8bcH\ \xc5\x9c3W9\xb9\x1a\x14\x04X/\xec\xfc\xbft\xed\x02\xa5\xf4\xc2m\xfa*<N\x17??\ \x0frqy\x9c\xd3\xb2f5\xaf\x89\x8f9Gk\xbc\x08\xa7\xbf\x06\x97\x98\x06S\xd8E\ \xbd\x9cE\xb2\x15\x9da\x89\xe2k\x0f\x9c\xb6|\x1a\xea\x14X\x1d6G\x83E\xe7\x9c\ \x1dO\xa8\xde\xb6\x84l\x15\x9eS\xcf\xc2tf\x15\xde\xf7\xb5\xb2]\xf0\x96+\xf5@\ D\x90\x1d\xef19_\xf5\xde5y\xb6+\xa7\xdeZ\xfbA\x9bu\x9f`\xffD\xafYn\xf6\x9eW\ \xeb>\xb6\x7f\x98\\U\xcb\xf5\xd5\xcb\x9a'\xe7\xf4\xd7\x0b\xba\x9e\xdb\x17E\ \xfdf\x97Z\xcb\xcc\xc0\xf0\xff?3\xc3\x92\xabN\x8arB\xc7\x8f\x03\x1d\xcc\xe0\ \xe9\xea\xe7\xb2\xce)\xa1\t\x00B7|\x00" ) def GetdragcursorBitmap(): return wx.BitmapFromImage(GetdragcursorImage()) def GetdragcursorImage(): stream = cStringIO.StringIO(GetdragcursorData()) return wx.ImageFromStream(stream) #----------------------------------------------------------------------------- # PyImageList #----------------------------------------------------------------------------- class PyImageList(object): """ A L{PyImageList} contains a list of images. Images can have masks for transparent drawing, and can be made from a variety of sources including bitmaps and icons. L{PyImageList} is used in conjunction with L{UltimateListCtrl}. :note: The main improvements that L{PyImageList} introduces is the removal of the limitation of same-size images inside the image list. If you use the style ``IL_VARIABLE_SIZE`` then each image can have any size (in terms of width and height). """ def __init__(self, width, height, mask=True, initialCount=1, style=IL_VARIABLE_SIZE): """ Default class constructor. :param `width`: the width of the images in the image list, in pixels (unused if you specify the ``IL_VARIABLE_SIZE`` style; :param `height`: the height of the images in the image list, in pixels (unused if you specify the ``IL_VARIABLE_SIZE`` style; :param `mask`: ``True`` if masks should be created for all images (unused in L{PyImageList}; :param `initialCount`: the initial size of the list (unused in L{PyImageList}); :param `style`: can be one of the following bits: ==================== ===== ================================= Style Flag Value Description ==================== ===== ================================= ``IL_FIXED_SIZE`` 0 All the images in L{PyImageList} have the same size (width, height) ``IL_VARIABLE_SIZE`` 1 Each image can have any size (in terms of width and height) ==================== ===== ================================= """ self._width = width self._height = height self._mask = mask self._initialCount = 1 self._style = style self._images = [] def GetImageCount(self): """ Returns the number of images in the list. """ return len(self._images) def Add(self, bitmap): """ Adds a new image or images using a bitmap. :param `bitmap`: a valid `wx.Bitmap` object. :return: The new zero-based image index. :note: If the bitmap is wider than the images in the list and you are not using the ``IL_VARIABLE_SIZE`` style, then the bitmap will automatically be split into smaller images, each matching the dimensions of the image list. """ index = len(self._images) # Mimic behavior of Windows ImageList_Add that automatically breaks up the added # bitmap into sub-images of the correct size if self._style & IL_FIXED_SIZE: if self._width > 0 and bitmap.GetWidth() > self._width and \ bitmap.GetHeight() >= self._height: numImages = bitmap.GetWidth()/self._width for subIndex in xrange(numImages): rect = wx.Rect(self._width * subIndex, 0, self._width, self._height) tmpBmp = bitmap.GetSubBitmap(rect) self._images.append(tmpBmp) else: self._images.append(bitmap) else: self._images.append(bitmap) if self._width == 0 and self._height == 0: self._width = bitmap.GetWidth() self._height = bitmap.GetHeight() return index def AddIcon(self, icon): """ Adds a new image using an icon. :param `icon`: a valid `wx.Icon` object. :return: The new zero-based image index. :note: If the icon is wider than the images in the list and you are not using the ``IL_VARIABLE_SIZE`` style, then the icon will automatically be split into smaller images, each matching the dimensions of the image list. """ return self.Add(wx.BitmapFromIcon(icon)) def AddWithColourMask(self, bitmap, maskColour): """ Adds a new image or images using a bitmap and a colour mask. :param `bitmap`: a valid `wx.Bitmap` object; :param `colour`: an instance of `wx.Colour`, a colour indicating which parts of the image are transparent. :return: The new zero-based image index. :note: If the bitmap is wider than the images in the list and you are not using the ``IL_VARIABLE_SIZE`` style, then the bitmap will automatically be split into smaller images, each matching the dimensions of the image list. """ img = bitmap.ConvertToImage() img.SetMaskColour(maskColour.Red(), maskColour.Green(), maskColour.Blue()) return self.Add(wx.BitmapFromImage(img)) def GetBitmap(self, index): """ Returns the bitmap corresponding to the given `index`, or `wx.NullBitmap` if the index is invalid. :param `index`: the bitmap index. """ if index >= len(self._images): return wx.NullBitmap return self._images[index] def GetIcon(self, index): """ Returns the icon corresponding to the given `index`, or `wx.NullIcon` if the index is invalid. :param `index`: the icon index. """ if index >= len(self._images): return wx.NullIcon return wx.IconFromBitmap(self._images[index]) def Replace(self, index, bitmap): """ Replaces the existing image with the new bitmap. :param `index`: the index at which the image should be replaced; :param `bitmap`: the new bitmap to add to the image list, an instance of `wx.Bitmap`. """ if index >= len(self._images): raise Exception("Wrong index in image list") self._images[index] = bitmap return True def ReplaceIcon(self, index, icon): """ Replaces the existing image with the new icon. :param `index`: the index at which the image should be replaced; :param `icon`: the new icon to add to the image list, an instance of `wx.Icon`. """ return self.Replace(index, wx.BitmapFromIcon(icon)) def Remove(self, index): """ Removes the image at the given position. :param `index`: the zero-based index of the image to be removed. """ if index >= len(self._images): raise Exception("Wrong index in image list") self._images.pop(index) return True def RemoveAll(self): """ Removes all the images in the list. """ self._images = [] return True def GetSize(self, index): """ Retrieves the size of an image in the list. :param `index`: the zero-based index of the image. :return: a tuple of `(width, height)` properties of the chosen bitmap. """ if index >= len(self._images): raise Exception("Wrong index in image list") bmp = self._images[index] return bmp.GetWidth(), bmp.GetHeight() def Draw(self, index, dc, x, y, flags, solidBackground=True): """ Draws a specified image onto a device context. :param `index`: the image index, starting from zero; :param `dc`: an instance of `wx.DC`; :param `x`: x position on the device context; :param `y`: y position on the device context; :param `flags`: how to draw the image. A bitlist of a selection of the following: ================================= ======================================= Flag Paarameter Description ================================= ======================================= ``wx.IMAGELIST_DRAW_NORMAL`` Draw the image normally ``wx.IMAGELIST_DRAW_TRANSPARENT`` Draw the image with transparency ``wx.IMAGELIST_DRAW_SELECTED`` Draw the image in selected state ``wx.IMAGELIST_DRAW_FOCUSED`` Draw the image in a focused state ================================= ======================================= :param `solidBackground`: currently unused. """ if index >= len(self._images): raise Exception("Wrong index in image list") bmp = self._images[index] dc.DrawBitmap(bmp, x, y, (flags & wx.IMAGELIST_DRAW_TRANSPARENT) > 0) return True class SelectionStore(object): """ SelectionStore is used to store the selected items in the virtual controls, i.e. it is well suited for storing even when the control contains a huge (practically infinite) number of items. Of course, internally it still has to store the selected items somehow (as an array currently) but the advantage is that it can handle the selection of all items (common operation) efficiently and that it could be made even smarter in the future (e.g. store the selections as an array of ranges + individual items) without changing its API. """ def __init__(self): """ Default class constructor. """ # the array of items whose selection state is different from default self._itemsSel = [] # the default state: normally, False (i.e. off) but maybe set to true if # there are more selected items than non selected ones - this allows to # handle selection of all items efficiently self._defaultState = False # the total number of items we handle self._count = 0 # special case of SetItemCount(0) def Clear(self): """ Clears the number of selected items. """ self._itemsSel = [] self._count = 0 self._defaultState = False # return the total number of selected items def GetSelectedCount(self): """ Return the total number of selected items. """ return (self._defaultState and [self._count - len(self._itemsSel)] or [len(self._itemsSel)])[0] def IsSelected(self, item): """ Returns ``True`` if the given item is selected. :param `item`: the item to check for selection state. """ isSel = item in self._itemsSel # if the default state is to be selected, being in m_itemsSel means that # the item is not selected, so we have to inverse the logic return (self._defaultState and [not isSel] or [isSel])[0] def SelectItem(self, item, select=True): """ Selects the given item. :param `item`: the item to select; :param `select`: ``True`` to select the item, ``False`` otherwise. :return: ``True`` if the items selection really changed. """ # search for the item ourselves as like this we get the index where to # insert it later if needed, so we do only one search in the array instead # of two (adding item to a sorted array requires a search) index = bisect.bisect_right(self._itemsSel, item) isSel = index < len(self._itemsSel) and self._itemsSel[index] == item if select != self._defaultState: if item not in self._itemsSel: bisect.insort_right(self._itemsSel, item) return True else: # reset to default state if item in self._itemsSel: self._itemsSel.remove(item) return True return False def SelectRange(self, itemFrom, itemTo, select=True): """ Selects a range of items. :param `itemFrom`: the first index of the selection range; :param `itemTo`: the last index of the selection range; :param `select`: ``True`` to select the items, ``False`` otherwise. :return: ``True`` and fill the `itemsChanged` array with the indices of items which have changed state if "few" of them did, otherwise return ``False`` (meaning that too many items changed state to bother counting them individually). """ # 100 is hardcoded but it shouldn't matter much: the important thing is # that we don't refresh everything when really few (e.g. 1 or 2) items # change state MANY_ITEMS = 100 # many items (> half) changed state itemsChanged = [] # are we going to have more [un]selected items than the other ones? if itemTo - itemFrom > self._count/2: if select != self._defaultState: # the default state now becomes the same as 'select' self._defaultState = select # so all the old selections (which had state select) shouldn't be # selected any more, but all the other ones should selOld = self._itemsSel[:] self._itemsSel = [] # TODO: it should be possible to optimize the searches a bit # knowing the possible range for item in xrange(itemFrom): if item not in selOld: self._itemsSel.append(item) for item in xrange(itemTo + 1, self._count): if item not in selOld: self._itemsSel.append(item) else: # select == self._defaultState # get the inclusive range of items between itemFrom and itemTo count = len(self._itemsSel) start = bisect.bisect_right(self._itemsSel, itemFrom) end = bisect.bisect_right(self._itemsSel, itemTo) if start == count or self._itemsSel[start] < itemFrom: start += 1 if end == count or self._itemsSel[end] > itemTo: end -= 1 if start <= end: # delete all of them (from end to avoid changing indices) for i in xrange(end, start-1, -1): if itemsChanged: if len(itemsChanged) > MANY_ITEMS: # stop counting (see comment below) itemsChanged = [] else: itemsChanged.append(self._itemsSel[i]) self._itemsSel.pop(i) else: self._itemsSel = [] else: # "few" items change state if itemsChanged: itemsChanged = [] # just add the items to the selection for item in xrange(itemFrom, itemTo+1): if self.SelectItem(item, select) and itemsChanged: itemsChanged.append(item) if len(itemsChanged) > MANY_ITEMS: # stop counting them, we'll just eat gobs of memory # for nothing at all - faster to refresh everything in # this case itemsChanged = [] # we set it to None if there are many items changing state return itemsChanged def OnItemDelete(self, item): """ Must be called when an item is deleted. :param `item`: the item that is being deleted. """ count = len(self._itemsSel) i = bisect.bisect_right(self._itemsSel, item) if i < count and self._itemsSel[i] == item: # this item itself was in m_itemsSel, remove it from there self._itemsSel.pop(i) count -= 1 # and adjust the index of all which follow it while i < count: i += 1 self._itemsSel[i] -= 1 def SetItemCount(self, count): """ Sets the total number of items we handle. :param `count`: the total number of items we handle. """ # forget about all items whose indices are now invalid if the size # decreased if count < self._count: for i in xrange(len(self._itemsSel), 0, -1): if self._itemsSel[i - 1] >= count: self._itemsSel.pop(i - 1) # remember the new number of items self._count = count # ---------------------------------------------------------------------------- # UltimateListItemAttr: a structure containing the visual attributes of an item # ---------------------------------------------------------------------------- class UltimateListItemAttr(object): """ Represents the attributes (colour, font, ...) of a L{UltimateListCtrl} L{UltimateListItem}. """ def __init__(self, colText=wx.NullColour, colBack=wx.NullColour, font=wx.NullFont, enabled=True, footerColText=wx.NullColour, footerColBack=wx.NullColour, footerFont=wx.NullFont): """ Default class constructor. :param `colText`: the item text colour; :param `colBack`: the item background colour; :param `font`: the item font; :param `enabled`: ``True`` if the item should be enabled, ``False`` if it is disabled; :param `footerColText`: for footer items, the item text colour; :param `footerColBack`: for footer items, the item background colour; :param `footerFont`: for footer items, the item font. """ self._colText = colText self._colBack = colBack self._font = font self._enabled = enabled self._footerColText = footerColText self._footerColBack = footerColBack self._footerFont = footerFont # setters def SetTextColour(self, colText): """ Sets a new text colour. :param `colText`: an instance of `wx.Colour`. """ self._colText = colText def SetBackgroundColour(self, colBack): """ Sets a new background colour. :param `colBack`: an instance of `wx.Colour`. """ self._colBack = colBack def SetFont(self, font): """ Sets a new font for the item. :param `font`: an instance of `wx.Font`. """ self._font = font def Enable(self, enable=True): """ Enables or disables the item. :param `enable`: ``True`` to enable the item, ``False`` to disable it. """ self._enabled = enable def SetFooterTextColour(self, colText): """ Sets a new footer item text colour. :param `colText`: an instance of `wx.Colour`. """ self._footerColText = colText def SetFooterBackgroundColour(self, colBack): """ Sets a new footer item background colour. :param `colBack`: an instance of `wx.Colour`. """ self._footerColBack = colBack def SetFooterFont(self, font): """ Sets a new font for the footer item. :param `font`: an instance of `wx.Font`. """ self._footerFont = font # accessors def HasTextColour(self): """ Returns ``True`` if the currently set text colour is valid. """ return self._colText.Ok() def HasBackgroundColour(self): """ Returns ``True`` if the currently set background colour is valid. """ return self._colBack.Ok() def HasFont(self): """ Returns ``True`` if the currently set font is valid. """ return self._font.Ok() def HasFooterTextColour(self): """ Returns ``True`` if the currently set text colour for the footer item is valid. """ return self._footerColText.Ok() def HasFooterBackgroundColour(self): """ Returns ``True`` if the currently set background colour for the footer item is valid. """ return self._footerColBack.Ok() def HasFooterFont(self): """ Returns ``True`` if the currently set font for the footer item is valid. """ return self._footerFont.Ok() # getters def GetTextColour(self): """ Returns the currently set text colour. """ return self._colText def GetBackgroundColour(self): """ Returns the currently set background colour. """ return self._colBack def GetFont(self): """ Returns the currently set item font. """ return self._font def GetFooterTextColour(self): """ Returns the currently set text colour for a footer item. """ return self._footerColText def GetFooterBackgroundColour(self): """ Returns the currently set background colour for a footer item. """ return self._footerColBack def GetFooterFont(self): """ Returns the currently set font for a footer item. """ return self._footerFont def IsEnabled(self): """ Returns ``True`` if the item is enabled. """ return self._enabled # ---------------------------------------------------------------------------- # UltimateListItem: the item or column info, used to exchange data with UltimateListCtrl # ---------------------------------------------------------------------------- class UltimateListItem(wx.Object): """ This class stores information about a L{UltimateListCtrl} item or column. """ def __init__(self, item=None): """ Default class constructor. :param `item`: if not ``None``, another instance of L{UltimateListItem}. """ if not item: self.Init() self._attr = None else: self._mask = item._mask # Indicates what fields are valid self._itemId = item._itemId # The zero-based item position self._col = item._col # Zero-based column, if in report mode self._state = item._state # The state of the item self._stateMask = item._stateMask # Which flags of self._state are valid (uses same flags) self._text = item._text # The label/header text self._image = item._image[:] # The zero-based indexes into an image list self._data = item._data # App-defined data self._pyData = item._pyData # Python-specific data self._format = item._format # left, right, centre self._width = item._width # width of column self._colour = item._colour # item text colour self._font = item._font # item font self._checked = item._checked # The checking state for the item (if kind > 0) self._kind = item._kind # Whether it is a normal, checkbox-like or a radiobutton-like item self._enabled = item._enabled # Whether the item is enabled or not self._hypertext = item._hypertext # indicates if the item is hypertext self._visited = item._visited # visited state for an hypertext item self._wnd = item._wnd self._windowenabled = item._windowenabled self._windowsize = item._windowsize self._isColumnShown = item._isColumnShown self._customRenderer = item._customRenderer self._overFlow = item._overFlow self._footerChecked = item._footerChecked self._footerFormat = item._footerFormat self._footerImage = item._footerImage self._footerKind = item._footerKind self._footerText = item._footerText self._expandWin = item._expandWin self._attr = None # copy list item attributes if item.HasAttributes(): self._attr = item.GetAttributes()[:] # resetting def Clear(self): """ Resets the item state to the default. """ self.Init() self._text = "" self.ClearAttributes() def ClearAttributes(self): """ Deletes the item attributes if they have been stored. """ if self._attr: del self._attr self._attr = None # setters def SetMask(self, mask): """ Sets the mask of valid fields. :param `mask`: any combination of the following bits: ============================ ========= ============================== Mask Bits Hex Value Description ============================ ========= ============================== ``ULC_MASK_STATE`` 0x1 L{GetState} is valid ``ULC_MASK_TEXT`` 0x2 L{GetText} is valid ``ULC_MASK_IMAGE`` 0x4 L{GetImage} is valid ``ULC_MASK_DATA`` 0x8 L{GetData} is valid ``ULC_MASK_WIDTH`` 0x20 L{GetWidth} is valid ``ULC_MASK_FORMAT`` 0x40 L{GetFormat} is valid ``ULC_MASK_FONTCOLOUR`` 0x80 L{GetTextColour} is valid ``ULC_MASK_FONT`` 0x100 L{GetFont} is valid ``ULC_MASK_BACKCOLOUR`` 0x200 L{GetBackgroundColour} is valid ``ULC_MASK_KIND`` 0x400 L{GetKind} is valid ``ULC_MASK_ENABLE`` 0x800 L{IsEnabled} is valid ``ULC_MASK_CHECK`` 0x1000 L{IsChecked} is valid ``ULC_MASK_HYPERTEXT`` 0x2000 L{IsHyperText} is valid ``ULC_MASK_WINDOW`` 0x4000 L{GetWindow} is valid ``ULC_MASK_PYDATA`` 0x8000 L{GetPyData} is valid ``ULC_MASK_SHOWN`` 0x10000 L{IsShown} is valid ``ULC_MASK_RENDERER`` 0x20000 L{GetCustomRenderer} is valid ``ULC_MASK_OVERFLOW`` 0x40000 L{GetOverFlow} is valid ``ULC_MASK_FOOTER_TEXT`` 0x80000 L{GetFooterText} is valid ``ULC_MASK_FOOTER_IMAGE`` 0x100000 L{GetFooterImage} is valid ``ULC_MASK_FOOTER_FORMAT`` 0x200000 L{GetFooterFormat} is valid ``ULC_MASK_FOOTER_FONT`` 0x400000 L{GetFooterFont} is valid ``ULC_MASK_FOOTER_CHECK`` 0x800000 L{IsFooterChecked} is valid ``ULC_MASK_FOOTER_KIND`` 0x1000000 L{GetFooterKind} is valid ============================ ========= ============================== """ self._mask = mask def SetId(self, id): """ Sets the zero-based item position. :param `id`: the zero-based item position. """ self._itemId = id def SetColumn(self, col): """ Sets the zero-based column. :param `col`: the zero-based column. :note: This method is neaningful only in report mode. """ self._col = col def SetState(self, state): """ Sets the item state flags. :param `state`: any combination of the following bits: ============================ ========= ============================== State Bits Hex Value Description ============================ ========= ============================== ``ULC_STATE_DONTCARE`` 0x0 Don't care what the state is ``ULC_STATE_DROPHILITED`` 0x1 The item is highlighted to receive a drop event ``ULC_STATE_FOCUSED`` 0x2 The item has the focus ``ULC_STATE_SELECTED`` 0x4 The item is selected ``ULC_STATE_CUT`` 0x8 The item is in the cut state ``ULC_STATE_DISABLED`` 0x10 The item is disabled ``ULC_STATE_FILTERED`` 0x20 The item has been filtered ``ULC_STATE_INUSE`` 0x40 The item is in use ``ULC_STATE_PICKED`` 0x80 The item has been picked ``ULC_STATE_SOURCE`` 0x100 The item is a drag and drop source ============================ ========= ============================== :note: The valid state flags are influenced by the value of the state mask. :see: L{SetStateMask} """ self._mask |= ULC_MASK_STATE self._state = state self._stateMask |= state def SetStateMask(self, stateMask): """ Sets the bitmask that is used to determine which of the state flags are to be set. :param `stateMask`: the state bitmask. :see: L{SetState} for a list of valid state bits. """ self._stateMask = stateMask def SetText(self, text): """ Sets the text label for the item. :param `text`: the text label for the item. """ self._mask |= ULC_MASK_TEXT self._text = text def SetImage(self, image): """ Sets the zero-based indexes of the images associated with the item into the image list. :param `image`: a Python list with the zero-based indexes of the images associated with the item into the image list. """ self._mask |= ULC_MASK_IMAGE if image is None: image = [] self._image = to_list(image) def SetData(self, data): """ Sets client data for the item. :param `data`: the client data associated to the item. :note: Please note that client data is associated with the item and not with subitems. """ self._mask |= ULC_MASK_DATA self._data = data def SetPyData(self, pyData): """ Sets data for the item, which can be any Python object. :param `data`: any Python object associated to the item. :note: Please note that Python data is associated with the item and not with subitems. """ self._mask |= ULC_MASK_PYDATA self._pyData = pyData def SetWidth(self, width): """ Sets the column width. :param `width`: the column width. :note: This method is meaningful only for column headers in report mode. """ self._mask |= ULC_MASK_WIDTH self._width = width def SetAlign(self, align): """ Sets the alignment for the item. :param `align`: one of the following bits: ============================ ========= ============================== Alignment Bits Hex Value Description ============================ ========= ============================== ``ULC_FORMAT_LEFT`` 0x0 The item is left-aligned ``ULC_FORMAT_RIGHT`` 0x1 The item is right-aligned ``ULC_FORMAT_CENTRE`` 0x2 The item is centre-aligned ``ULC_FORMAT_CENTER`` 0x2 The item is center-aligned ============================ ========= ============================== """ self._mask |= ULC_MASK_FORMAT self._format = align def SetTextColour(self, colText): """ Sets the text colour for the item. :param `colText`: a valid `wx.Colour` object. """ self.Attributes().SetTextColour(colText) def SetBackgroundColour(self, colBack): """ Sets the background colour for the item. :param `colBack`: a valid `wx.Colour` object. """ self.Attributes().SetBackgroundColour(colBack) def SetFont(self, font): """ Sets the font for the item. :param `font`: a valid `wx.Font` object. """ self.Attributes().SetFont(font) def SetFooterTextColour(self, colText): """ Sets the text colour for the footer item. :param `colText`: a valid `wx.Colour` object. """ self.Attributes().SetFooterTextColour(colText) def SetFooterBackgroundColour(self, colBack): """ Sets the background colour for the footer item. :param `colBack`: a valid `wx.Colour` object. """ self.Attributes().SetFooterBackgroundColour(colBack) def SetFooterFont(self, font): """ Sets the font for the footer item. :param `font`: a valid `wx.Font` object. """ self.Attributes().SetFooterFont(font) def Enable(self, enable=True): """ Enables or disables the item. :param `enable`: ``True`` to enable the item, ``False`` to disable it. """ self.Attributes().Enable(enable) # accessors def GetMask(self): """ Returns a bit mask indicating which fields of the structure are valid. :see: L{SetMask} for a list of valid bit masks. """ return self._mask def GetId(self): """ Returns the zero-based item position. """ return self._itemId def GetColumn(self): """ Returns the zero-based column. :note: This method is meaningful only in report mode. """ return self._col def GetFormat(self): """ Returns the header item format. """ return self._format def GetState(self): """ Returns a bit field representing the state of the item. :see: L{SetState} for a list of valid item states. """ return self._state & self._stateMask def GetText(self): """ Returns the label/header text. """ return self._text def GetImage(self): """ Returns a Python list with the zero-based indexes of the images associated with the item into the image list. """ return self._image def GetData(self): """ Returns client data associated with the control. :note: Please note that client data is associated with the item and not with subitems. """ return self._data def GetPyData(self): """ Returns data for the item, which can be any Python object. :note: Please note that Python data is associated with the item and not with subitems. """ return self._pyData def GetWidth(self): """ Returns the column width. :note: This method is meaningful only for column headers in report mode. """ return self._width def GetAlign(self): """ Returns the alignment for the item. :see: L{SetAlign} for a list of valid alignment bits. """ return self._format def GetAttributes(self): """ Returns the associated L{UltimateListItemAttr} attributes. """ return self._attr def HasAttributes(self): """ Returns ``True`` if the item has attributes associated with it. """ return self._attr != None def GetTextColour(self): """ Returns the text colour. """ return (self.HasAttributes() and [self._attr.GetTextColour()] or [wx.NullColour])[0] def GetBackgroundColour(self): """ Returns the background colour. """ return (self.HasAttributes() and [self._attr.GetBackgroundColour()] or [wx.NullColour])[0] def GetFont(self): """ Returns the item font. """ return (self.HasAttributes() and [self._attr.GetFont()] or [wx.NullFont])[0] def IsEnabled(self): """ Returns ``True`` if the item is enabled. """ return (self.HasAttributes() and [self._attr.IsEnabled()] or [True])[0] # creates self._attr if we don't have it yet def Attributes(self): """ Returns the associated attributes if they exist, or create a new L{UltimateListItemAttr} structure and associate it with this item. """ if not self._attr: self._attr = UltimateListItemAttr() return self._attr def SetKind(self, kind): """ Sets the item kind. :param `kind`: may be one of the following integers: =============== ========================== Item Kind Description =============== ========================== 0 A normal item 1 A checkbox-like item 2 A radiobutton-type item =============== ========================== """ self._mask |= ULC_MASK_KIND self._kind = kind def GetKind(self): """ Returns the item kind. :see: L{SetKind} for a valid list of item's kind. """ return self._kind def IsChecked(self): """ Returns whether the item is checked or not. """ return self._checked def Check(self, checked=True): """ Checks/unchecks an item. :param `checked`: ``True`` to check an item, ``False`` to uncheck it. :note: This method is meaningful only for check and radio items. """ self._mask |= ULC_MASK_CHECK self._checked = checked def IsShown(self): """ Returns ``True`` if the item is shown, or ``False`` if it is hidden. """ return self._isColumnShown def SetShown(self, shown=True): """ Sets an item as shown/hidden. :param `shown`: ``True`` to show the item, ``False`` to hide it. """ self._mask |= ULC_MASK_SHOWN self._isColumnShown = shown def SetHyperText(self, hyper=True): """ Sets whether the item is hypertext or not. :param `hyper`: ``True`` to set hypertext behaviour, ``False`` otherwise. """ self._mask |= ULC_MASK_HYPERTEXT self._hypertext = hyper def SetVisited(self, visited=True): """ Sets whether an hypertext item was visited or not. :param `visited`: ``True`` to set a hypertext item as visited, ``False`` otherwise. """ self._mask |= ULC_MASK_HYPERTEXT self._visited = visited def GetVisited(self): """ Returns whether an hypertext item was visited or not. """ return self._visited def IsHyperText(self): """ Returns whether the item is hypetext or not. """ return self._hypertext def SetWindow(self, wnd, expand=False): """ Sets the window associated to the item. :param `wnd`: a non-toplevel window to be displayed next to the item; :param `expand`: ``True`` to expand the column where the item/subitem lives, so that the window will be fully visible. """ self._mask |= ULC_MASK_WINDOW self._wnd = wnd listCtrl = wnd.GetParent() mainWin = listCtrl._mainWin wnd.Reparent(mainWin) if wnd.GetSizer(): # the window is a complex one hold by a sizer size = wnd.GetBestSize() else: # simple window, without sizers size = wnd.GetSize() # We have to bind the wx.EVT_SET_FOCUS for the associated window # No other solution to handle the focus changing from an item in # UltimateListCtrl and the window associated to an item # Do better strategies exist? self._wnd.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self._windowsize = size # The window is enabled only if the item is enabled self._wnd.Enable(self._enabled) self._windowenabled = self._enabled self._expandWin = expand mainWin._hasWindows = True mainWin._itemWithWindow.append(self) # This is needed as otherwise widgets that should be invisible # are shown at the top left corner of ULC mainWin.HideWindows() mainWin.Refresh() def GetWindow(self): """ Returns the window associated to the item. """ return self._wnd def DeleteWindow(self): """ Deletes the window associated to the item (if any). """ if self._wnd: listCtrl = self._wnd.GetParent() if self in listCtrl._itemWithWindow: listCtrl._itemWithWindow.remove(self) self._wnd.Destroy() self._wnd = None def GetWindowEnabled(self): """ Returns whether the associated window is enabled or not. """ if not self._wnd: raise Exception("\nERROR: This Item Has No Window Associated") return self._windowenabled def SetWindowEnabled(self, enable=True): """ Sets whether the associated window is enabled or not. :param `enable`: ``True`` to enable the associated window, ``False`` to disable it. """ if not self._wnd: raise Exception("\nERROR: This Item Has No Window Associated") self._windowenabled = enable self._wnd.Enable(enable) def GetWindowSize(self): """ Returns the associated window size. """ return self._windowsize def SetCustomRenderer(self, renderer): """ Associate a custom renderer to this item. :param `renderer`: a class able to correctly render the item. :note: the renderer class **must** implement the methods `DrawSubItem`, `GetLineHeight` and `GetSubItemWidth`. """ self._mask |= ULC_MASK_RENDERER self._customRenderer = renderer def GetCustomRenderer(self): """ Returns the custom renderer associated with this item (if any). """ return self._customRenderer def SetOverFlow(self, over=True): """ Sets the item in the overflow/non overflow state. An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it. :param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise. """ self._mask |= ULC_MASK_OVERFLOW self._overFlow = over def GetOverFlow(self): """ Returns if the item is in the overflow state. An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it. """ return self._overFlow def Init(self): """ Initializes an empty L{UltimateListItem}. """ self._mask = 0 self._itemId = 0 self._col = 0 self._state = 0 self._stateMask = 0 self._image = [] self._data = 0 self._pyData = None self._text = "" self._format = ULC_FORMAT_CENTRE self._width = 0 self._colour = wx.Colour(0, 0, 0) self._font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) self._kind = 0 self._checked = False self._enabled = True self._hypertext = False # indicates if the item is hypertext self._visited = False # visited state for an hypertext item self._wnd = None self._windowenabled = False self._windowsize = wx.Size() self._isColumnShown = True self._customRenderer = None self._overFlow = False self._footerChecked = False self._footerFormat = ULC_FORMAT_CENTRE self._footerImage = [] self._footerKind = 0 self._footerText = "" self._expandWin = False def SetFooterKind(self, kind): """ Sets the footer item kind. :see: L{SetKind} for a list of valid items kind. """ self._mask |= ULC_MASK_FOOTER_KIND self._footerKind = kind def GetFooterKind(self): """ Returns the footer item kind. :see: L{SetKind} for a list of valid items kind. """ return self._footerKind def IsFooterChecked(self): """ Returns whether the footer item is checked or not. """ return self._footerChecked def CheckFooter(self, checked=True): """ Checks/unchecks a footer item. :param `checked`: ``True`` to check an item, ``False`` to uncheck it. :note: This method is meaningful only for check and radio footer items. """ self._mask |= ULC_MASK_FOOTER_CHECK self._footerChecked = checked def GetFooterFormat(self): """ Returns the footer item format. """ return self._footerFormat def SetFooterFormat(self, format): """ Sets the footer item format. :param `format`: the footer item format. """ self._mask |= ULC_MASK_FOOTER_FORMAT self._footerFormat = format def GetFooterText(self): """ Returns the footer text. """ return self._footerText def SetFooterText(self, text): """ Sets the text label for the footer item. :param `text`: the text label for the footer item. """ self._mask |= ULC_MASK_FOOTER_TEXT self._footerText = text def GetFooterImage(self): """ Returns the zero-based index of the image associated with the footer item into the image list. """ return self._footerImage def SetFooterImage(self, image): """ Sets the zero-based index of the image associated with the footer item into the image list. :param `image`: the zero-based index of the image associated with the footer item into the image list. """ self._mask |= ULC_MASK_FOOTER_IMAGE self._footerImage = to_list(image) def GetFooterTextColour(self): """ Returns the footer item text colour. """ return (self.HasAttributes() and [self._attr.GetFooterTextColour()] or [wx.NullColour])[0] def GetFooterBackgroundColour(self): """ Returns the footer item background colour. """ return (self.HasAttributes() and [self._attr.GetFooterBackgroundColour()] or [wx.NullColour])[0] def GetFooterFont(self): """ Returns the footer item font. """ return (self.HasAttributes() and [self._attr.GetFooterFont()] or [wx.NullFont])[0] def SetFooterAlign(self, align): """ Sets the alignment for the footer item. :see: L{SetAlign} for a list of valid alignment flags. """ self._mask |= ULC_MASK_FOOTER_FORMAT self._footerFormat = align def GetFooterAlign(self): """ Returns the alignment for the footer item. :see: L{SetAlign} for a list of valid alignment flags. """ return self._footerFormat def OnSetFocus(self, event): """ Handles the ``wx.EVT_SET_FOCUS`` event for the window associated to an item. :param `event`: a `wx.FocusEvent` event to be processed. """ listCtrl = self._wnd.GetParent() select = listCtrl.GetItemState(self._itemId, ULC_STATE_SELECTED) # If the window is associated to an item that currently is selected # (has focus) we don't kill the focus. Otherwise we do it. if not select: listCtrl._hasFocus = False else: listCtrl._hasFocus = True listCtrl.SetFocus() event.Skip() # ---------------------------------------------------------------------------- # ListEvent - the event class for the UltimateListCtrl notifications # ---------------------------------------------------------------------------- class CommandListEvent(wx.PyCommandEvent): """ A list event holds information about events associated with L{UltimateListCtrl} objects. """ def __init__(self, commandTypeOrEvent=None, winid=0): """ Default class constructor. For internal use: do not call it in your code! :param `commandTypeOrEvent`: the event type or another instance of `wx.PyCommandEvent`; :param `winid`: the event identifier. """ if type(commandTypeOrEvent) == types.IntType: wx.PyCommandEvent.__init__(self, commandTypeOrEvent, winid) self.m_code = 0 self.m_oldItemIndex = 0 self.m_itemIndex = 0 self.m_col = 0 self.m_pointDrag = wx.Point() self.m_item = UltimateListItem() self.m_editCancelled = False else: wx.PyCommandEvent.__init__(self, commandTypeOrEvent.GetEventType(), commandTypeOrEvent.GetId()) self.m_code = commandTypeOrEvent.m_code self.m_oldItemIndex = commandTypeOrEvent.m_oldItemIndex self.m_itemIndex = commandTypeOrEvent.m_itemIndex self.m_col = commandTypeOrEvent.m_col self.m_pointDrag = commandTypeOrEvent.m_pointDrag self.m_item = commandTypeOrEvent.m_item self.m_editCancelled = commandTypeOrEvent.m_editCancelled def GetKeyCode(self): """ Returns the key code if the event is a keypress event. """ return self.m_code def GetIndex(self): """ Returns the item index. """ return self.m_itemIndex def GetColumn(self): """ Returns the column position: it is only used with ``COL`` events. For the column dragging events, it is the column to the left of the divider being dragged, for the column click events it may be -1 if the user clicked in the list control header outside any column. """ return self.m_col def GetPoint(self): """ Returns the position of the mouse pointer if the event is a drag event. """ return self.m_pointDrag def GetLabel(self): """ Returns the (new) item label for ``EVT_LIST_END_LABEL_EDIT`` event. """ return self.m_item._text def GetText(self): """ Returns the item text. """ return self.m_item._text def GetImage(self): """ Returns the item image. """ return self.m_item._image def GetData(self): """ Returns the item data. """ return self.m_item._data def GetMask(self): """ Returns the item mask. """ return self.m_item._mask def GetItem(self): """ Returns the item itself. """ return self.m_item # for wxEVT_COMMAND_LIST_CACHE_HINT only def GetCacheFrom(self): """ Returns the first item which the list control advises us to cache. :note: This method is meaningful for ``EVT_LIST_CACHE_HINT`` event only. """ return self.m_oldItemIndex def GetCacheTo(self): """ Returns the last item (inclusive) which the list control advises us to cache. :note: This method is meaningful for ``EVT_LIST_CACHE_HINT`` event only. """ return self.m_itemIndex # was label editing canceled? (for wxEVT_COMMAND_LIST_END_LABEL_EDIT only) def IsEditCancelled(self): """ Returns ``True`` if it the label editing has been cancelled by the user (L{GetLabel} returns an empty string in this case but it doesn't allow the application to distinguish between really cancelling the edit and the admittedly rare case when the user wants to rename it to an empty string). :note: This method only makes sense for ``EVT_LIST_END_LABEL_EDIT`` messages. """ return self.m_editCancelled def SetEditCanceled(self, editCancelled): """ Sets the item editing as cancelled/not cancelled. :param `editCancelled`: ``True`` to set the item editing as cancelled, ``False`` otherwise. :note: This method only makes sense for ``EVT_LIST_END_LABEL_EDIT`` messages. """ self.m_editCancelled = editCancelled def Clone(self): """ Returns a copy of the event. Any event that is posted to the wxPython event system for later action (via `wx.EvtHandler.AddPendingEvent` or `wx.PostEvent`) must implement this method. All wxPython events fully implement this method, but any derived events implemented by the user should also implement this method just in case they (or some event derived from them) are ever posted. All wxPython events implement a copy constructor, so the easiest way of implementing the L{Clone} function is to implement a copy constructor for a new event (call it `MyEvent`) and then define the L{Clone} function like this:: def Clone(self): return MyEvent(self) """ return UltimateListEvent(self) # ---------------------------------------------------------------------------- # UltimateListEvent is a special class for all events associated with list controls # # NB: note that not all accessors make sense for all events, see the event # descriptions below # ---------------------------------------------------------------------------- class UltimateListEvent(CommandListEvent): """ A list event holds information about events associated with L{UltimateListCtrl} objects. """ def __init__(self, commandTypeOrEvent=None, winid=0): """ Default class constructor. For internal use: do not call it in your code! :param `commandTypeOrEvent`: the event type or another instance of `wx.PyCommandEvent`; :param `winid`: the event identifier. """ CommandListEvent.__init__(self, commandTypeOrEvent, winid) if type(commandTypeOrEvent) == types.IntType: self.notify = wx.NotifyEvent(commandTypeOrEvent, winid) else: self.notify = wx.NotifyEvent(commandTypeOrEvent.GetEventType(), commandTypeOrEvent.GetId()) def GetNotifyEvent(self): """ Returns the actual `wx.NotifyEvent`. """ return self.notify def IsAllowed(self): """ Returns ``True`` if the change is allowed (L{Veto} hasn't been called) or ``False`` otherwise (if it was). """ return self.notify.IsAllowed() def Veto(self): """ Prevents the change announced by this event from happening. :note: It is in general a good idea to notify the user about the reasons for vetoing the change because otherwise the applications behaviour (which just refuses to do what the user wants) might be quite surprising. """ self.notify.Veto() def Allow(self): """ This is the opposite of L{Veto}: it explicitly allows the event to be processed. For most events it is not necessary to call this method as the events are allowed anyhow but some are forbidden by default (this will be mentioned in the corresponding event description). """ self.notify.Allow() # ============================================================================ # private classes # ============================================================================ #----------------------------------------------------------------------------- # ColWidthInfo (internal) #----------------------------------------------------------------------------- class ColWidthInfo(object): """ A simple class which holds information about L{UltimateListCtrl} columns. """ def __init__(self, w=0, needsUpdate=True): """ Default class constructor :param `w`: the initial width of the column; :param `needsUpdate`: ``True`` if the column needs refreshing, ``False`` otherwise. """ self._nMaxWidth = w self._bNeedsUpdate = needsUpdate #----------------------------------------------------------------------------- # UltimateListItemData (internal) #----------------------------------------------------------------------------- class UltimateListItemData(object): """ A simple class which holds information about L{UltimateListItem} visual attributes (client ractangles, positions, etc...). """ def __init__(self, owner): """ Default class constructor :param `owner`: an instance of L{UltimateListCtrl}. """ # the list ctrl we are in self._owner = owner self.Init() # the item coordinates are not used in report mode, instead this pointer # is None and the owner window is used to retrieve the item position and # size if owner.InReportView(): self._rect = None else: self._rect = wx.Rect() def SetImage(self, image): """ Sets the zero-based indexes of the images associated with the item into the image list. :param `image`: a Python list with the zero-based indexes of the images associated with the item into the image list. """ self._image = to_list(image) def SetData(self, data): """ Sets client data for the item. :param `data`: the client data associated to the item. :note: Please note that client data is associated with the item and not with subitems. """ self._data = data def HasText(self): """ Returns ``True`` if the item text is not the empty string. """ return self._text != "" def GetText(self): """ Returns the item text. """ return self._text def GetBackgroundColour(self): """ Returns the currently set background colour. """ return self._backColour def GetColour(self): """ Returns the currently set text colour. """ return self._colour def GetFont(self): """ Returns the currently set font. """ return (self._hasFont and [self._font] or [wx.NullFont])[0] def SetText(self, text): """ Sets the text label for the item. :param `text`: the text label for the item. """ self._text = text def SetColour(self, colour): """ Sets the text colour for the item. :param `colour`: an instance of `wx.Colour`. """ if colour == wx.NullColour: self._hasColour = False del self._colour return self._hasColour = True self._colour = colour def SetFont(self, font): """ Sets the text font for the item. :param `font`: an instance of `wx.Font`. """ if font == wx.NullFont: self._hasFont = False del self._font return self._hasFont = True self._font = font def SetBackgroundColour(self, colour): """ Sets the background colour for the item. :param `colour`: an instance of `wx.Colour`. """ if colour == wx.NullColour: self._hasBackColour = False del self._backColour return self._hasBackColour = True self._backColour = colour # we can't use empty string for measuring the string width/height, so # always return something def GetTextForMeasuring(self): """ Returns the item text or a simple string if the item text is the empty string. """ s = self.GetText() if not s.strip(): s = 'H' return s def GetImage(self): """ Returns a Python list with the zero-based indexes of the images associated with the item into the image list. """ return self._image def HasImage(self): """ Returns ``True`` if the item has at least one image associated with it. """ return len(self._image) > 0 def SetKind(self, kind): """ Sets the item kind. :param `kind`: may be one of the following integers: =============== ========================== Item Kind Description =============== ========================== 0 A normal item 1 A checkbox-like item 2 A radiobutton-type item =============== ========================== """ self._kind = kind def GetKind(self): """ Returns the item kind. :see: L{SetKind} for a list of valid item kinds. """ return self._kind def IsChecked(self): """ Returns whether the item is checked or not. """ return self._checked def Check(self, checked=True): """ Checks/unchecks an item. :param `checked`: ``True`` to check an item, ``False`` to uncheck it. :note: This method is meaningful only for check and radio items. """ self._checked = checked def SetHyperText(self, hyper=True): """ Sets whether the item is hypertext or not. :param `hyper`: ``True`` to set hypertext behaviour, ``False`` otherwise. """ self._hypertext = hyper def SetVisited(self, visited=True): """ Sets whether an hypertext item was visited or not. :param `visited`: ``True`` to set a hypertext item as visited, ``False`` otherwise. """ self._visited = visited def GetVisited(self): """Returns whether an hypertext item was visited or not.""" return self._visited def IsHyperText(self): """Returns whether the item is hypetext or not.""" return self._hypertext def SetWindow(self, wnd, expand=False): """ Sets the window associated to the item. :param `wnd`: a non-toplevel window to be displayed next to the item; :param `expand`: ``True`` to expand the column where the item/subitem lives, so that the window will be fully visible. """ self._mask |= ULC_MASK_WINDOW self._wnd = wnd if wnd.GetSizer(): # the window is a complex one hold by a sizer size = wnd.GetBestSize() else: # simple window, without sizers size = wnd.GetSize() # We have to bind the wx.EVT_SET_FOCUS for the associated window # No other solution to handle the focus changing from an item in # UltimateListCtrl and the window associated to an item # Do better strategies exist? self._windowsize = size # The window is enabled only if the item is enabled self._wnd.Enable(self._enabled) self._windowenabled = self._enabled self._expandWin = expand def GetWindow(self): """ Returns the window associated to the item. """ return self._wnd def DeleteWindow(self): """ Deletes the window associated to the item (if any). """ if self._wnd: self._wnd.Destroy() self._wnd = None def GetWindowEnabled(self): """ Returns whether the associated window is enabled or not. """ if not self._wnd: raise Exception("\nERROR: This Item Has No Window Associated") return self._windowenabled def SetWindowEnabled(self, enable=True): """ Sets whether the associated window is enabled or not. :param `enable`: ``True`` to enable the associated window, ``False`` to disable it. """ if not self._wnd: raise Exception("\nERROR: This Item Has No Window Associated") self._windowenabled = enable self._wnd.Enable(enable) def GetWindowSize(self): """ Returns the associated window size. """ return self._windowsize def SetAttr(self, attr): """ Sets the item attributes. :param `attr`: an instance of L{UltimateListItemAttr}. """ self._attr = attr def GetAttr(self): """ Returns the item attributes. """ return self._attr def HasColour(self): """ Returns ``True`` if the currently set text colour is valid. """ return self._hasColour def HasFont(self): """ Returns ``True`` if the currently set font is valid. """ return self._hasFont def HasBackgroundColour(self): """ Returns ``True`` if the currently set background colour is valid. """ return self._hasBackColour def SetCustomRenderer(self, renderer): """ Associate a custom renderer to this item. :param `renderer`: a class able to correctly render the item. :note: the renderer class **must** implement the methods `DrawSubItem`, `GetLineHeight` and `GetSubItemWidth`. """ self._mask |= ULC_MASK_RENDERER self._customRenderer = renderer def GetCustomRenderer(self): """ Returns the custom renderer associated with this item (if any). """ return self._customRenderer def SetOverFlow(self, over=True): """ Sets the item in the overflow/non overflow state. An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it. :param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise. """ self._mask |= ULC_MASK_OVERFLOW self._overFlow = over def GetOverFlow(self): """ Returns if the item is in the overflow state. An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it. """ return self._overFlow def Init(self): """ Initializes the item data structure. """ # the item image or -1 self._image = [] # user data associated with the item self._data = 0 self._pyData = None self._colour = wx.Colour(0, 0, 0) self._hasColour = False self._hasFont = False self._hasBackColour = False self._text = "" # kind = 0: normal item # kind = 1: checkbox-type item self._kind = 0 self._checked = False self._enabled = True # custom attributes or None self._attr = None self._hypertext = False self._visited = False self._wnd = None self._windowenabled = True self._windowsize = wx.Size() self._isColumnShown = True self._customRenderer = None self._overFlow = False self._expandWin = False def SetItem(self, info): """ Sets information about the item. :param `info`: an instance of L{UltimateListItemData}. """ if info._mask & ULC_MASK_TEXT: CheckVariableRowHeight(self._owner, info._text) self.SetText(info._text) if info._mask & ULC_MASK_KIND: self._kind = info._kind if info._mask & ULC_MASK_CHECK: self._checked = info._checked if info._mask & ULC_MASK_ENABLE: self._enabled = info._enabled if info._mask & ULC_MASK_IMAGE: self._image = info._image[:] if info._mask & ULC_MASK_DATA: self._data = info._data if info._mask & ULC_MASK_PYDATA: self._pyData = info._pyData if info._mask & ULC_MASK_HYPERTEXT: self._hypertext = info._hypertext self._visited = info._visited if info._mask & ULC_MASK_FONTCOLOUR: self.SetColour(info.GetTextColour()) if info._mask & ULC_MASK_FONT: self.SetFont(info.GetFont()) if info._mask & ULC_MASK_BACKCOLOUR: self.SetBackgroundColour(info.GetBackgroundColour()) if info._mask & ULC_MASK_WINDOW: self._wnd = info._wnd self._windowenabled = info._windowenabled self._windowsize = info._windowsize self._expandWin = info._expandWin if info._mask & ULC_MASK_SHOWN: self._isColumnShown = info._isColumnShown if info._mask & ULC_MASK_RENDERER: self._customRenderer = info._customRenderer if info._mask & ULC_MASK_OVERFLOW: self._overFlow = info._overFlow if info.HasAttributes(): if self._attr: self._attr = info.GetAttributes() else: self._attr = UltimateListItemAttr(info.GetTextColour(), info.GetBackgroundColour(), info.GetFont(), info.IsEnabled(), info.GetFooterTextColour(), info.GetFooterBackgroundColour(), info.GetFooterFont()) if self._rect: self._rect.x = -1 self._rect.y = -1 self._rect.height = 0 self._rect.width = info._width def SetPosition(self, x, y): """ Sets the item position. :param `x`: the item x position; :param `y`: the item y position. """ self._rect.x = x self._rect.y = y def SetSize(self, width, height): """ Sets the item size. :param `width`: the item width; :param `height`: the item height. """ if width != -1: self._rect.width = width if height != -1: self._rect.height = height def IsHit(self, x, y): """ Returns ``True`` if the input position is inside the item client rectangle. :param `x`: the x mouse position; :param `y`: the y mouse position. """ return wx.Rect(self.GetX(), self.GetY(), self.GetWidth(), self.GetHeight()).Contains((x, y)) def GetX(self): """ Returns the item x position. """ return self._rect.x def GetY(self): """ Returns the item y position. """ return self._rect.y def GetWidth(self): """ Returns the item width. """ return self._rect.width def GetHeight(self): """ Returns the item height. """ return self._rect.height def GetItem(self, info): """ Returns information about the item. :param `info`: an instance of L{UltimateListItemData}. """ mask = info._mask if not mask: # by default, get everything for backwards compatibility mask = -1 if mask & ULC_MASK_TEXT: info._text = self._text if mask & ULC_MASK_IMAGE: info._image = self._image[:] if mask & ULC_MASK_DATA: info._data = self._data if mask & ULC_MASK_PYDATA: info._pyData = self._pyData if info._mask & ULC_MASK_FONT: info.SetFont(self.GetFont()) if mask & ULC_MASK_KIND: info._kind = self._kind if mask & ULC_MASK_CHECK: info._checked = self._checked if mask & ULC_MASK_ENABLE: info._enabled = self._enabled if mask & ULC_MASK_HYPERTEXT: info._hypertext = self._hypertext info._visited = self._visited if mask & ULC_MASK_WINDOW: info._wnd = self._wnd info._windowenabled = self._windowenabled info._windowsize = self._windowsize info._expandWin = self._expandWin if mask & ULC_MASK_SHOWN: info._isColumnShown = self._isColumnShown if mask & ULC_MASK_RENDERER: info._customRenderer = self._customRenderer if mask & ULC_MASK_OVERFLOW: info._overFlow = self._overFlow if self._attr: if self._attr.HasTextColour(): info.SetTextColour(self._attr.GetTextColour()) if self._attr.HasBackgroundColour(): info.SetBackgroundColour(self._attr.GetBackgroundColour()) if self._attr.HasFont(): info.SetFont(self._attr.GetFont()) info.Enable(self._attr.IsEnabled()) return info def IsEnabled(self): """ Returns ``True`` if the item is enabled, ``False`` if it is disabled. """ return self._enabled def Enable(self, enable=True): """ Enables or disables the item. :param `enable`: ``True`` to enable the item, ``False`` to disable it. """ self._enabled = enable #----------------------------------------------------------------------------- # UltimateListHeaderData (internal) #----------------------------------------------------------------------------- class UltimateListHeaderData(object): """ A simple class which holds information about L{UltimateListItem} visual attributes for the header/footer items (client ractangles, positions, etc...). """ def __init__(self, item=None): """ Default class constructor. :param `item`: another instance of L{UltimateListHeaderData}. """ self.Init() if item: self.SetItem(item) def HasText(self): """ Returns ``True`` if the currently set text colour is valid. """ return self._text != "" def GetText(self): """ Returns the header/footer item text. """ return self._text def SetText(self, text): """ Sets the header/footer item text. :param `text`: the new header/footer text. """ self._text = text def GetFont(self): """ Returns the header/footer item font. """ return self._font def Init(self): """ Initializes the header/footer item. """ self._mask = 0 self._image = [] self._format = 0 self._width = 0 self._xpos = 0 self._ypos = 0 self._height = 0 self._text = "" self._kind = 0 self._checked = False self._font = wx.NullFont self._state = 0 self._isColumnShown = True self._customRenderer = None self._footerImage = [] self._footerFormat = 0 self._footerText = "" self._footerKind = 0 self._footerChecked = False self._footerFont = wx.NullFont def SetItem(self, item): """ Sets information about the header/footer item. :param `info`: an instance of L{UltimateListHeaderData}. """ self._mask = item._mask if self._mask & ULC_MASK_TEXT: self._text = item._text if self._mask & ULC_MASK_FOOTER_TEXT: self._footerText = item._footerText if self._mask & ULC_MASK_IMAGE: self._image = item._image[:] if self._mask & ULC_MASK_FOOTER_IMAGE: self._footerImage = item._footerImage[:] if self._mask & ULC_MASK_FORMAT: self._format = item._format if self._mask & ULC_MASK_FOOTER_FORMAT: self._footerFormat = item._footerFormat if self._mask & ULC_MASK_WIDTH: self.SetWidth(item._width) if self._mask & ULC_MASK_FONT: self._font = item._font if self._mask & ULC_MASK_FOOTER_FONT: self._footerFont = item._footerFont if self._mask & ULC_MASK_FOOTER_KIND: self._footerKind = item._footerKind self._footerChecked = item._footerChecked if self._mask & ULC_MASK_KIND: self._kind = item._kind self._checked = item._checked if self._mask & ULC_MASK_CHECK: self._kind = item._kind self._checked = item._checked if self._mask & ULC_MASK_FOOTER_CHECK: self._footerKind = item._footerKind self._footerChecked = item._footerChecked if self._mask & ULC_MASK_STATE: self.SetState(item._state) if self._mask & ULC_MASK_SHOWN: self._isColumnShown = item._isColumnShown if self._mask & ULC_MASK_RENDERER: self._customRenderer = item._customRenderer def SetState(self, flag): """ Sets the item state flags. :param `state`: any combination of the following bits: ============================ ========= ============================== State Bits Hex Value Description ============================ ========= ============================== ``ULC_STATE_DONTCARE`` 0x0 Don't care what the state is ``ULC_STATE_DROPHILITED`` 0x1 The item is highlighted to receive a drop event ``ULC_STATE_FOCUSED`` 0x2 The item has the focus ``ULC_STATE_SELECTED`` 0x4 The item is selected ``ULC_STATE_CUT`` 0x8 The item is in the cut state ``ULC_STATE_DISABLED`` 0x10 The item is disabled ``ULC_STATE_FILTERED`` 0x20 The item has been filtered ``ULC_STATE_INUSE`` 0x40 The item is in use ``ULC_STATE_PICKED`` 0x80 The item has been picked ``ULC_STATE_SOURCE`` 0x100 The item is a drag and drop source ============================ ========= ============================== """ self._state = flag def SetPosition(self, x, y): """ Sets the header/footer item position. :param `x`: the item x position; :param `y`: the item y position. """ self._xpos = x self._ypos = y def SetHeight(self, h): """ Sets the header/footer item height. :param `h`: an integer value representing the header/footer height. """ self._height = h def SetWidth(self, w): """ Sets the header/footer item width. :param `w`: an integer value representing the header/footer width. """ self._width = w if self._width < 0: self._width = WIDTH_COL_DEFAULT elif self._width < WIDTH_COL_MIN: self._width = WIDTH_COL_MIN def SetFormat(self, format): """ Sets the header item format. :param `format`: the header item format. """ self._format = format def SetFooterFormat(self, format): """ Sets the footer item format. :param `format`: the footer item format. """ self._footerFormat = format def HasImage(self): """ Returns ``True`` if the header item has at least one image associated with it. """ return len(self._image) > 0 def HasFooterImage(self): """ Returns ``True`` if the footer item has at least one image associated with it. """ return len(self._footerImage) > 0 def IsHit(self, x, y): """ Returns ``True`` if the input position is inside the item client rectangle. :param `x`: the x mouse position; :param `y`: the y mouse position. """ return ((x >= self._xpos) and (x <= self._xpos+self._width) and (y >= self._ypos) and (y <= self._ypos+self._height)) def GetItem(self, item): """ Returns information about the item. :param `item`: an instance of L{UltimateListHeaderData}. """ item._mask = self._mask item._text = self._text item._image = self._image[:] item._format = self._format item._width = self._width if self._font: item._font = self._font item.Attributes().SetFont(self._font) item._kind = self._kind item._checked = self._checked item._state = self._state item._isColumnShown = self._isColumnShown item._footerImage = self._footerImage item._footerFormat = self._footerFormat item._footerText = self._footerText item._footerKind = self._footerKind item._footerChecked = self._footerChecked item._footerFont = self._footerFont item._customRenderer = self._customRenderer return item def GetState(self): """ Returns a bit field representing the state of the item. :see: L{SetState} for a list of valid item states. """ return self._state def GetImage(self): """ Returns a Python list with the zero-based indexes of the images associated with the header item into the image list. """ return self._image def GetFooterImage(self): """ Returns a Python list with the zero-based indexes of the images associated with the footer item into the image list. """ return self._footerImage def GetWidth(self): """ Returns the header/footer item width. """ return self._width def GetFormat(self): """ Returns the header item format. """ return self._format def GetFooterFormat(self): """ Returns the footer item format. """ return self._footerFormat def SetFont(self, font): """ Sets a new font for the header item. :param `font`: an instance of `wx.Font`. """ self._font = font def SetFooterFont(self, font): """ Sets a new font for the footer item. :param `font`: an instance of `wx.Font`. """ self._footerFont = font def SetKind(self, kind): """ Sets the header item kind. :param `kind`: may be one of the following integers: =============== ========================== Item Kind Description =============== ========================== 0 A normal item 1 A checkbox-like item 2 A radiobutton-type item =============== ========================== """ self._kind = kind def SetFooterKind(self, kind): """ Sets the footer item kind. :param `kind`: the footer item kind. :see: L{SetKind} for a list of valid item kinds. """ self._footerKind = kind def GetKind(self): """ Returns the header item kind. :see: L{SetKind} for a list of valid item kinds. """ return self._kind def GetFooterKind(self): """ Returns the footer item kind. :see: L{SetKind} for a list of valid item kinds. """ return self._footerKind def IsChecked(self): """ Returns whether the header item is checked or not. """ return self._checked def Check(self, checked=True): """ Checks/unchecks a header item. :param `checked`: ``True`` to check an item, ``False`` to uncheck it. :note: This method is meaningful only for check and radio header items. """ self._checked = checked def IsFooterChecked(self): """ Returns whether the footer item is checked or not. """ return self._footerChecked def CheckFooter(self, check=True): """ Checks/unchecks a footer item. :param `checked`: ``True`` to check an item, ``False`` to uncheck it. :note: This method is meaningful only for check and radio footer items. """ self._footerChecked = check def SetCustomRenderer(self, renderer): """ Associate a custom renderer to this item. :param `renderer`: a class able to correctly render the item. :note: the renderer class **must** implement the methods `DrawHeaderButton` and `GetForegroundColor`. """ self._mask |= ULC_MASK_RENDERER self._customRenderer = renderer def GetCustomRenderer(self): """ Returns the custom renderer associated with this item (if any). """ return self._customRenderer #----------------------------------------------------------------------------- # GeometryInfo (internal) # this is not used in report view #----------------------------------------------------------------------------- class GeometryInfo(object): """ A simple class which holds items geometries for L{UltimateListCtrl} not in report mode. """ def __init__(self): """ Default class constructor. """ # total item rect self._rectAll = wx.Rect() # label only self._rectLabel = wx.Rect() # icon only self._rectIcon = wx.Rect() # the part to be highlighted self._rectHighlight = wx.Rect() # the checkbox/radiobutton rect (if any) self._rectCheck = wx.Rect() # extend all our rects to be centered inside the one of given width def ExtendWidth(self, w): """ Extends all our rectangles to be centered inside the one of given width. :param `w`: the given width. """ if self._rectAll.width > w: raise Exception("width can only be increased") self._rectAll.width = w self._rectLabel.x = self._rectAll.x + (w - self._rectLabel.width)/2 self._rectIcon.x = self._rectAll.x + (w - self._rectIcon.width)/2 self._rectHighlight.x = self._rectAll.x + (w - self._rectHighlight.width)/2 #----------------------------------------------------------------------------- # UltimateListLineData (internal) #----------------------------------------------------------------------------- class UltimateListLineData(object): """ A simple class which holds line geometries for L{UltimateListCtrl}. """ def __init__(self, owner): """ Default class constructor. :param `owner`: an instance of L{UltimateListCtrl}. """ # the list of subitems: only may have more than one item in report mode self._items = [] # is this item selected? [NB: not used in virtual mode] self._highlighted = False # back pointer to the list ctrl self._owner = owner self._height = self._width = self._x = self._y = -1 if self.InReportView(): self._gi = None else: self._gi = GeometryInfo() if self.GetMode() in [ULC_REPORT, ULC_TILE] or self.HasMode(ULC_HEADER_IN_ALL_VIEWS): self.InitItems(self._owner.GetColumnCount()) else: self.InitItems(1) def SetReportView(self, inReportView): """ Sets whether L{UltimateListLineData} is in report view or not. :param `inReportView`: ``True`` to set L{UltimateListLineData} in report view, ``False`` otherwise. """ # we only need m_gi when we're not in report view so update as needed if inReportView: del self._gi self._gi = None else: self._gi = GeometryInfo() def GetHeight(self): """ Returns the line height. """ return self._height def SetHeight(self, height): """ Sets the line height. :param `height`: the new line height. """ self._height = height def GetWidth(self): """ Returns the line width. """ return self._width def SetWidth(self, width): """ Sets the line width. :param `width`: the new line width. """ self._width = width def GetX(self): """ Returns the line x position. """ return self._x def SetX(self, x): """ Sets the line x position. :param `x`: the new line x position. """ self._x = x def GetY(self): """ Returns the line y position. """ return self._y def SetY(self, y): """ Sets the line y position. :param `y`: the new line y position. """ self._y = y def ResetDimensions(self): """ Resets the line dimensions (client rectangle). """ self._height = self._width = self._x = self._y = -1 def HasImage(self): """ Returns ``True`` if the first item in the line has at least one image associated with it. """ return self.GetImage() != [] def HasText(self): """ Returns ``True`` if the text of first item in the line is not the empty string. """ return self.GetText(0) != "" def IsHighlighted(self): """ Returns ``True`` if the line is highlighted. """ if self.IsVirtual(): raise Exception("unexpected call to IsHighlighted") return self._highlighted def GetMode(self): """ Returns the current highlighting mode. """ return self._owner.GetListCtrl().GetAGWWindowStyleFlag() & ULC_MASK_TYPE def HasMode(self, mode): """ Returns ``True`` if the parent L{UltimateListCtrl} has the window style specified by `mode`. :param `mode`: the window style to check. """ return self._owner.GetListCtrl().HasAGWFlag(mode) def InReportView(self): """ Returns ``True`` if the parent L{UltimateListCtrl} is in report view. """ return self._owner.HasAGWFlag(ULC_REPORT) def IsVirtual(self): """ Returns ``True`` if the parent L{UltimateListCtrl} has the ``ULC_VIRTUAL`` style set. """ return self._owner.IsVirtual() def CalculateSize(self, dc, spacing): """ Calculates the line size and item positions. :param `dc`: an instance of `wx.DC`; :param `spacing`: the spacing between the items, in pixels. """ item = self._items[0] mode = self.GetMode() if mode in [ULC_ICON, ULC_SMALL_ICON]: self._gi._rectAll.width = spacing s = item.GetText() if not s: lh = -1 self._gi._rectLabel.width = 0 self._gi._rectLabel.height = 0 else: lw, lh = dc.GetTextExtent(s) lw += EXTRA_WIDTH lh += EXTRA_HEIGHT self._gi._rectAll.height = spacing + lh if lw > spacing: self._gi._rectAll.width = lw self._gi._rectLabel.width = lw self._gi._rectLabel.height = lh if item.HasImage(): w, h = self._owner.GetImageSize(item.GetImage()) self._gi._rectIcon.width = w + 8 self._gi._rectIcon.height = h + 8 if self._gi._rectIcon.width > self._gi._rectAll.width: self._gi._rectAll.width = self._gi._rectIcon.width if self._gi._rectIcon.height + lh > self._gi._rectAll.height - 4: self._gi._rectAll.height = self._gi._rectIcon.height + lh + 4 if item.HasText(): self._gi._rectHighlight.width = self._gi._rectLabel.width self._gi._rectHighlight.height = self._gi._rectLabel.height else: self._gi._rectHighlight.width = self._gi._rectIcon.width self._gi._rectHighlight.height = self._gi._rectIcon.height elif mode == ULC_LIST: s = item.GetTextForMeasuring() lw, lh = dc.GetTextExtent(s) lw += EXTRA_WIDTH lh += EXTRA_HEIGHT self._gi._rectLabel.width = lw self._gi._rectLabel.height = lh self._gi._rectAll.width = lw self._gi._rectAll.height = lh if item.HasImage(): w, h = self._owner.GetImageSize(item.GetImage()) h += 4 self._gi._rectIcon.width = w self._gi._rectIcon.height = h self._gi._rectAll.width += 4 + w if h > self._gi._rectAll.height: self._gi._rectAll.height = h if item.GetKind() in [1, 2]: w, h = self._owner.GetCheckboxImageSize() h += 4 self._gi._rectCheck.width = w self._gi._rectCheck.height = h self._gi._rectAll.width += 4 + w if h > self._gi._rectAll.height: self._gi._rectAll.height = h self._gi._rectHighlight.width = self._gi._rectAll.width self._gi._rectHighlight.height = self._gi._rectAll.height elif mode == ULC_REPORT: raise Exception("unexpected call to SetSize") else: raise Exception("unknown mode") def SetPosition(self, x, y, spacing): """ Sets the line position. :param `x`: the current x coordinate; :param `y`: the current y coordinate; :param `spacing`: the spacing between items, in pixels. """ item = self._items[0] mode = self.GetMode() if mode in [ULC_ICON, ULC_SMALL_ICON]: self._gi._rectAll.x = x self._gi._rectAll.y = y if item.HasImage(): self._gi._rectIcon.x = self._gi._rectAll.x + 4 + (self._gi._rectAll.width - self._gi._rectIcon.width)/2 self._gi._rectIcon.y = self._gi._rectAll.y + 4 if item.HasText(): if self._gi._rectAll.width > spacing: self._gi._rectLabel.x = self._gi._rectAll.x + 2 else: self._gi._rectLabel.x = self._gi._rectAll.x + 2 + (spacing/2) - (self._gi._rectLabel.width/2) self._gi._rectLabel.y = self._gi._rectAll.y + self._gi._rectAll.height + 2 - self._gi._rectLabel.height self._gi._rectHighlight.x = self._gi._rectLabel.x - 2 self._gi._rectHighlight.y = self._gi._rectLabel.y - 2 else: self._gi._rectHighlight.x = self._gi._rectIcon.x - 4 self._gi._rectHighlight.y = self._gi._rectIcon.y - 4 elif mode == ULC_LIST: self._gi._rectAll.x = x self._gi._rectAll.y = y wcheck = hcheck = 0 if item.GetKind() in [1, 2]: wcheck, hcheck = self._owner.GetCheckboxImageSize() wcheck += 2 self._gi._rectCheck.x = self._gi._rectAll.x + 2 self._gi._rectCheck.y = self._gi._rectAll.y + 2 self._gi._rectHighlight.x = self._gi._rectAll.x self._gi._rectHighlight.y = self._gi._rectAll.y self._gi._rectLabel.y = self._gi._rectAll.y + 2 if item.HasImage(): self._gi._rectIcon.x = self._gi._rectAll.x + wcheck + 2 self._gi._rectIcon.y = self._gi._rectAll.y + 2 self._gi._rectLabel.x = self._gi._rectAll.x + 6 + self._gi._rectIcon.width + wcheck else: self._gi._rectLabel.x = self._gi._rectAll.x + 2 + wcheck elif mode == ULC_REPORT: raise Exception("unexpected call to SetPosition") else: raise Exception("unknown mode") def InitItems(self, num): """ Initializes the list of items. :param `num`: the initial number of items to store. """ for i in xrange(num): self._items.append(UltimateListItemData(self._owner)) def SetItem(self, index, info): """ Sets information about the item. :param `index`: the index of the item; :param `info`: an instance of L{UltimateListItem}. """ item = self._items[index] item.SetItem(info) def GetItem(self, index, info): """ Returns information about the item. :param `index`: the index of the item; :param `info`: an instance of L{UltimateListItem}. """ item = self._items[index] return item.GetItem(info) def GetText(self, index): """ Returns the item text at the position `index`. :param `index`: the index of the item. """ item = self._items[index] return item.GetText() def SetText(self, index, s): """ Sets the item text at the position `index`. :param `index`: the index of the item; :param `s`: the new item text. """ item = self._items[index] item.SetText(s) def SetImage(self, index, image): """ Sets the zero-based indexes of the images associated with the item into the image list. :param `index`: the index of the item; :param `image`: a Python list with the zero-based indexes of the images associated with the item into the image list. """ item = self._items[index] item.SetImage(image) def GetImage(self, index=0): """ Returns a Python list with the zero-based indexes of the images associated with the item into the image list. :param `index`: the index of the item. """ item = self._items[index] return item.GetImage() def Check(self, index, checked=True): """ Checks/unchecks an item. :param `index`: the index of the item; :param `checked`: ``True`` to check an item, ``False`` to uncheck it. :note: This method is meaningful only for check and radio items. """ item = self._items[index] item.Check(checked) def SetKind(self, index, kind=0): """ Sets the item kind. :param `index`: the index of the item; :param `kind`: may be one of the following integers: =============== ========================== Item Kind Description =============== ========================== 0 A normal item 1 A checkbox-like item 2 A radiobutton-type item =============== ========================== """ item = self._items[index] item.SetKind(kind) def GetKind(self, index=0): """ Returns the item kind. :param `index`: the index of the item. :see: L{SetKind} for a list of valid item kinds. """ item = self._items[index] return item.GetKind() def IsChecked(self, index): """ Returns whether the item is checked or not. :param `index`: the index of the item. """ item = self._items[index] return item.IsChecked() def SetColour(self, index, c): """ Sets the text colour for the item. :param `index`: the index of the item; :param `c`: an instance of `wx.Colour`. """ item = self._items[index] item.SetColour(c) def GetAttr(self): """ Returns an instance of L{UltimateListItemAttr} associated with the first item in the line. """ item = self._items[0] return item.GetAttr() def SetAttr(self, attr): """ Sets an instance of L{UltimateListItemAttr} to the first item in the line. :param `attr`: an instance of L{UltimateListItemAttr}. """ item = self._items[0] item.SetAttr(attr) def SetAttributes(self, dc, attr, highlighted): """ Sets various attributes to the input device context. :param `dc`: an instance of `wx.DC`; :param `attr`: an instance of L{UltimateListItemAttr}; :param `highlighted`: ``True`` if the item is highlighted, ``False`` otherwise. """ listctrl = self._owner.GetParent() # fg colour # don't use foreground colour for drawing highlighted items - this might # make them completely invisible (and there is no way to do bit # arithmetics on wxColour, unfortunately) if not self._owner.HasAGWFlag(ULC_BORDER_SELECT) and not self._owner.HasAGWFlag(ULC_NO_FULL_ROW_SELECT): if highlighted: if wx.Platform == "__WXMAC__": if self._owner.HasFocus(): colText = wx.WHITE else: colText = wx.BLACK else: colText = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT) else: colText = listctrl.GetForegroundColour() elif attr and attr.HasTextColour(): colText = attr.GetTextColour() else: colText = listctrl.GetForegroundColour() dc.SetTextForeground(colText) # font if attr and attr.HasFont(): font = attr.GetFont() else: font = listctrl.GetFont() dc.SetFont(font) # bg colour hasBgCol = attr and attr.HasBackgroundColour() if highlighted or hasBgCol: if highlighted: dc.SetBrush(self._owner.GetHighlightBrush()) else: dc.SetBrush(wx.Brush(attr.GetBackgroundColour(), wx.SOLID)) dc.SetPen(wx.TRANSPARENT_PEN) return True return False def Draw(self, line, dc): """ Draws the line on the specified device context. :param `line`: an instance of L{UltimateListLineData}; :param `dc`: an instance of `wx.DC`. """ item = self._items[0] highlighted = self.IsHighlighted() attr = self.GetAttr() useGradient, gradientStyle = self._owner._usegradients, self._owner._gradientstyle useVista = self._owner._vistaselection hasFocus = self._owner._hasFocus borderOnly = self._owner.HasAGWFlag(ULC_BORDER_SELECT) drawn = False if self.SetAttributes(dc, attr, highlighted): drawn = True if not borderOnly: if useGradient: if gradientStyle == 0: # horizontal gradient self.DrawHorizontalGradient(dc, self._gi._rectAll, hasFocus) else: # vertical gradient self.DrawVerticalGradient(dc, self._gi._rectAll, hasFocus) elif useVista: # Vista selection style self.DrawVistaRectangle(dc, self._gi._rectAll, hasFocus) else: if wx.Platform not in ["__WXMAC__", "__WXGTK__"]: dc.DrawRectangleRect(self._gi._rectHighlight) else: if highlighted: flags = wx.CONTROL_SELECTED if self._owner.HasFocus() and wx.Platform == "__WXMAC__": flags |= wx.CONTROL_FOCUSED wx.RendererNative.Get().DrawItemSelectionRect(self._owner, dc, self._gi._rectHighlight, flags) else: dc.DrawRectangleRect(self._gi._rectHighlight) else: if borderOnly: dc.SetBrush(wx.WHITE_BRUSH) dc.SetPen(wx.TRANSPARENT_PEN) dc.DrawRectangleRect(self._gi._rectAll) if item.GetKind() in [1, 2]: rectCheck = self._gi._rectCheck self._owner.DrawCheckbox(dc, rectCheck.x, rectCheck.y, item.GetKind(), item.IsChecked(), item.IsEnabled()) if item.HasImage(): # centre the image inside our rectangle, this looks nicer when items # ae aligned in a row rectIcon = self._gi._rectIcon self._owner.DrawImage(item.GetImage()[0], dc, rectIcon.x, rectIcon.y, True) if item.HasText(): rectLabel = self._gi._rectLabel dc.SetClippingRect(rectLabel) dc.DrawText(item.GetText(), rectLabel.x, rectLabel.y) dc.DestroyClippingRegion() if self._owner.HasAGWFlag(ULC_HOT_TRACKING): if line == self._owner._newHotCurrent and not drawn: r = wx.Rect(*self._gi._rectAll) dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.SetPen(wx.Pen(wx.NamedColour("orange"))) dc.DrawRoundedRectangleRect(r, 3) if borderOnly and drawn: dc.SetPen(wx.Pen(wx.Colour(0, 191, 255), 2)) dc.SetBrush(wx.TRANSPARENT_BRUSH) r = wx.Rect(*self._gi._rectAll) r.x += 1 r.y += 1 r.width -= 1 r.height -= 1 dc.DrawRoundedRectangleRect(r, 4) def HideItemWindow(self, item): """ If the input item has a window associated with it, hide it. :param `item`: an instance of L{UltimateListItem}. """ wnd = item.GetWindow() if wnd and wnd.IsShown(): wnd.Hide() def DrawInReportMode(self, dc, line, rect, rectHL, highlighted, current, enabled, oldPN, oldBR): """ Draws the line on the specified device context when the parent L{UltimateListCtrl} is in report mode. :param `dc`: an instance of `wx.DC`; :param `line`: an instance of L{UltimateListLineData}; :param `rect`: the item client rectangle; :param `rectHL`: the item client rectangle when the item is highlighted; :param `highlighted`: ``True`` if the item is highlighted, ``False`` otherwise; :param `current`: ``True`` if the item is the current item; :param `enabled`: ``True`` if the item is enabled, ``False`` otherwise; :param `oldPN`: an instance of `wx.Pen`, to save and restore at the end of the drawing; :param `oldBR`: an instance of `wx.Brush`, to save and restore at the end of the drawing. """ attr = self.GetAttr() useGradient, gradientStyle = self._owner._usegradients, self._owner._gradientstyle useVista = self._owner._vistaselection hasFocus = self._owner._hasFocus borderOnly = self._owner.HasAGWFlag(ULC_BORDER_SELECT) nofullRow = self._owner.HasAGWFlag(ULC_NO_FULL_ROW_SELECT) drawn = False dc.SetBrush(wx.TRANSPARENT_BRUSH) if nofullRow: x = rect.x + HEADER_OFFSET_X y = rect.y height = rect.height for col, item in enumerate(self._items): width = self._owner.GetColumnWidth(col) if self._owner.IsColumnShown(col): paintRect = wx.Rect(x, y, self._owner.GetColumnWidth(col)-2*HEADER_OFFSET_X, rect.height) break xOld = x x += width else: paintRect = wx.Rect(*rectHL) if self.SetAttributes(dc, attr, highlighted) and enabled: drawn = True if not borderOnly: if useGradient: if gradientStyle == 0: # horizontal gradient self.DrawHorizontalGradient(dc, paintRect, hasFocus) else: # vertical gradient self.DrawVerticalGradient(dc, paintRect, hasFocus) elif useVista: # Vista selection style self.DrawVistaRectangle(dc, paintRect, hasFocus) else: # Normal selection style if wx.Platform not in ["__WXGTK__", "__WXMAC__"]: dc.DrawRectangleRect(paintRect) else: if highlighted: flags = wx.CONTROL_SELECTED if hasFocus: flags |= wx.CONTROL_FOCUSED if current: flags |= wx.CONTROL_CURRENT wx.RendererNative.Get().DrawItemSelectionRect(self._owner, dc, paintRect, flags) else: dc.DrawRectangleRect(paintRect) else: if borderOnly: dc.SetBrush(wx.WHITE_BRUSH) dc.SetPen(wx.TRANSPARENT_PEN) dc.DrawRectangleRect(paintRect) x = rect.x + HEADER_OFFSET_X y = rect.y height = rect.height boldFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) boldFont.SetWeight(wx.BOLD) for col, item in enumerate(self._items): if not self._owner.IsColumnShown(col): self.HideItemWindow(item) continue width = self._owner.GetColumnWidth(col) xOld = x x += width if item.GetCustomRenderer(): customRect = wx.Rect(xOld-HEADER_OFFSET_X, rect.y, width, rect.height) item.GetCustomRenderer().DrawSubItem(dc, customRect, line, highlighted, enabled) continue overflow = item.GetOverFlow() and item.HasText() if item.GetKind() in [1, 2]: # We got a checkbox-type item ix, iy = self._owner.GetCheckboxImageSize() checked = item.IsChecked() self._owner.DrawCheckbox(dc, xOld, y + (height-iy+1)/2, item.GetKind(), checked, enabled) xOld += ix width -= ix if item.HasImage(): images = item.GetImage() for img in images: ix, iy = self._owner.GetImageSize([img]) self._owner.DrawImage(img, dc, xOld, y + (height-iy)/2, enabled) xOld += ix width -= ix ## if images: ## width -= IMAGE_MARGIN_IN_REPORT_MODE - MARGIN_BETWEEN_TEXT_AND_ICON wnd = item.GetWindow() xSize = 0 if wnd: xSize, ySize = item.GetWindowSize() wndx = xOld - HEADER_OFFSET_X + width - xSize - 3 xa, ya = self._owner.CalcScrolledPosition((0, rect.y)) wndx += xa if rect.height > ySize: ya += (rect.height - ySize)/2 itemRect = wx.Rect(xOld-2*HEADER_OFFSET_X, rect.y, width-xSize-HEADER_OFFSET_X, rect.height) if overflow: itemRect = wx.Rect(xOld-2*HEADER_OFFSET_X, rect.y, rectHL.width-xSize-HEADER_OFFSET_X, rect.height) dc.SetClippingRect(itemRect) if item.HasBackgroundColour(): dc.SetBrush(wx.Brush(item.GetBackgroundColour())) dc.SetPen(wx.Pen(item.GetBackgroundColour())) dc.DrawRectangleRect(itemRect) dc.SetBrush(oldBR) dc.SetPen(oldPN) if item.HasText(): coloured = item.HasColour() oldDC = dc.GetTextForeground() oldFT = dc.GetFont() font = item.HasFont() if not enabled: dc.SetTextForeground(self._owner.GetDisabledTextColour()) else: if coloured: dc.SetTextForeground(item.GetColour()) elif useVista and drawn: dc.SetTextForeground(wx.BLACK) dc.SetFont(boldFont) if item.IsHyperText(): dc.SetFont(self._owner.GetHyperTextFont()) if item.GetVisited(): dc.SetTextForeground(self._owner.GetHyperTextVisitedColour()) else: dc.SetTextForeground(self._owner.GetHyperTextNewColour()) else: if font: dc.SetFont(item.GetFont()) itemRect = wx.Rect(itemRect.x+MARGIN_BETWEEN_TEXT_AND_ICON, itemRect.y, itemRect.width-8, itemRect.height) self.DrawTextFormatted(dc, item.GetText(), line, col, itemRect, overflow) if coloured: dc.SetTextForeground(oldDC) if font: dc.SetFont(oldFT) dc.DestroyClippingRegion() if wnd: if not wnd.IsShown(): wnd.Show() if item._expandWin: if wnd.GetRect() != itemRect: wRect = wx.Rect(*itemRect) wRect.x += 2 wRect.width = width - 8 wRect.y += 2 wRect.height -= 4 wnd.SetRect(wRect) else: if wnd.GetPosition() != (wndx, ya): wnd.SetPosition((wndx, ya)) if self._owner.HasAGWFlag(ULC_HOT_TRACKING): if line == self._owner._newHotCurrent and not drawn: r = wx.Rect(*paintRect) r.y += 1 r.height -= 1 dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.SetPen(wx.Pen(wx.NamedColour("orange"))) dc.DrawRoundedRectangleRect(r, 3) dc.SetPen(oldPN) if borderOnly and drawn: dc.SetPen(wx.Pen(wx.Colour(0, 191, 255), 2)) dc.SetBrush(wx.TRANSPARENT_BRUSH) rect = wx.Rect(*paintRect) rect.y += 1 rect.height -= 1 dc.DrawRoundedRectangleRect(rect, 3) dc.SetPen(oldPN) def DrawTextFormatted(self, dc, text, row, col, itemRect, overflow): """ Draws the item text, correctly formatted. :param `dc`: an instance of `wx.DC`; :param `text`: the item text; :param `row`: the line number to which this item belongs to; :param `col`: the column number to which this item belongs to; :param `itemRect`: the item client rectangle; :param `overflow`: ``True`` if the item should overflow into neighboring columns, ``False`` otherwise. """ # determine if the string can fit inside the current width w, h, dummy = dc.GetMultiLineTextExtent(text) width = itemRect.width shortItems = self._owner._shortItems tuples = (row, col) # it can, draw it using the items alignment item = self._owner.GetColumn(col) align = item.GetAlign() if align == ULC_FORMAT_RIGHT: textAlign = wx.ALIGN_RIGHT elif align == ULC_FORMAT_CENTER: textAlign = wx.ALIGN_CENTER else: textAlign = wx.ALIGN_LEFT if w <= width: if tuples in shortItems: shortItems.remove(tuples) dc.DrawLabel(text, itemRect, textAlign|wx.ALIGN_CENTER_VERTICAL) else: # otherwise, truncate and add an ellipsis if possible if tuples not in shortItems: shortItems.append(tuples) # determine the base width ellipsis = "..." base_w, h = dc.GetTextExtent(ellipsis) # continue until we have enough space or only one character left newText = text.split("\n") theText = "" for text in newText: lenText = len(text) drawntext = text w, dummy = dc.GetTextExtent(text) while lenText > 1: if w + base_w <= width: break w_c, h_c = dc.GetTextExtent(drawntext[-1]) drawntext = drawntext[0:-1] lenText -= 1 w -= w_c # if still not enough space, remove ellipsis characters while len(ellipsis) > 0 and w + base_w > width: ellipsis = ellipsis[0:-1] base_w, h = dc.GetTextExtent(ellipsis) theText += drawntext + ellipsis + "\n" theText = theText.rstrip() # now draw the text dc.DrawLabel(theText, itemRect, textAlign|wx.ALIGN_CENTER_VERTICAL) def DrawVerticalGradient(self, dc, rect, hasfocus): """ Gradient fill from colour 1 to colour 2 from top to bottom. :param `dc`: an instance of `wx.DC`; :param `rect`: the rectangle to be filled with the gradient shading; :param `hasfocus`: ``True`` if the main L{UltimateListCtrl} has focus, ``False`` otherwise. """ oldpen = dc.GetPen() oldbrush = dc.GetBrush() dc.SetPen(wx.TRANSPARENT_PEN) # calculate gradient coefficients if hasfocus: col2 = self._owner._secondcolour col1 = self._owner._firstcolour else: col2 = self._owner._highlightUnfocusedBrush.GetColour() col1 = self._owner._highlightUnfocusedBrush2.GetColour() r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue()) r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue()) flrect = float(rect.height) rstep = float((r2 - r1)) / flrect gstep = float((g2 - g1)) / flrect bstep = float((b2 - b1)) / flrect rf, gf, bf = 0, 0, 0 for y in xrange(rect.y, rect.y + rect.height): currCol = (r1 + rf, g1 + gf, b1 + bf) dc.SetBrush(wx.Brush(currCol, wx.SOLID)) dc.DrawRectangle(rect.x, y, rect.width, 1) rf = rf + rstep gf = gf + gstep bf = bf + bstep dc.SetPen(oldpen) dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.DrawRectangleRect(rect) dc.SetBrush(oldbrush) def DrawHorizontalGradient(self, dc, rect, hasfocus): """ Gradient fill from colour 1 to colour 2 from left to right. :param `dc`: an instance of `wx.DC`; :param `rect`: the rectangle to be filled with the gradient shading; :param `hasfocus`: ``True`` if the main L{UltimateListCtrl} has focus, ``False`` otherwise. """ oldpen = dc.GetPen() oldbrush = dc.GetBrush() dc.SetPen(wx.TRANSPARENT_PEN) # calculate gradient coefficients if hasfocus: col2 = self._owner._secondcolour col1 = self._owner._firstcolour else: col2 = self._owner._highlightUnfocusedBrush.GetColour() col1 = self._owner._highlightUnfocusedBrush2.GetColour() r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue()) r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue()) flrect = float(rect.width) rstep = float((r2 - r1)) / flrect gstep = float((g2 - g1)) / flrect bstep = float((b2 - b1)) / flrect rf, gf, bf = 0, 0, 0 for x in xrange(rect.x, rect.x + rect.width): currCol = (int(r1 + rf), int(g1 + gf), int(b1 + bf)) dc.SetBrush(wx.Brush(currCol, wx.SOLID)) dc.DrawRectangle(x, rect.y, 1, rect.height) rf = rf + rstep gf = gf + gstep bf = bf + bstep dc.SetPen(oldpen) dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.DrawRectangleRect(rect) dc.SetBrush(oldbrush) def DrawVistaRectangle(self, dc, rect, hasfocus): """ Draws the selected item(s) with the Windows Vista style. :param `dc`: an instance of `wx.DC`; :param `rect`: the rectangle to be filled with the gradient shading; :param `hasfocus`: ``True`` if the main L{UltimateListCtrl} has focus, ``False`` otherwise. """ if hasfocus: outer = _rgbSelectOuter inner = _rgbSelectInner top = _rgbSelectTop bottom = _rgbSelectBottom else: outer = _rgbNoFocusOuter inner = _rgbNoFocusInner top = _rgbNoFocusTop bottom = _rgbNoFocusBottom oldpen = dc.GetPen() oldbrush = dc.GetBrush() bdrRect = wx.Rect(*rect.Get()) filRect = wx.Rect(*rect.Get()) filRect.Deflate(1,1) r1, g1, b1 = int(top.Red()), int(top.Green()), int(top.Blue()) r2, g2, b2 = int(bottom.Red()), int(bottom.Green()), int(bottom.Blue()) flrect = float(filRect.height) if flrect < 1: flrect = self._owner._lineHeight rstep = float((r2 - r1)) / flrect gstep = float((g2 - g1)) / flrect bstep = float((b2 - b1)) / flrect rf, gf, bf = 0, 0, 0 dc.SetPen(wx.TRANSPARENT_PEN) for y in xrange(filRect.y, filRect.y + filRect.height): currCol = (r1 + rf, g1 + gf, b1 + bf) dc.SetBrush(wx.Brush(currCol, wx.SOLID)) dc.DrawRectangle(filRect.x, y, filRect.width, 1) rf = rf + rstep gf = gf + gstep bf = bf + bstep dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.SetPen(wx.Pen(outer)) dc.DrawRoundedRectangleRect(bdrRect, 3) bdrRect.Deflate(1, 1) dc.SetPen(wx.Pen(inner)) dc.DrawRoundedRectangleRect(bdrRect, 2) dc.SetPen(oldpen) dc.SetBrush(oldbrush) def Highlight(self, on): """ Sets the current line as highlighted or not highlighted. :param `on`: ``True`` to set the current line as highlighted, ``False`` otherwise. """ if on == self._highlighted: return False self._highlighted = on return True def ReverseHighlight(self): """ Reverses the line highlighting, switching it off if it was on and vice-versa. """ self.Highlight(not self.IsHighlighted()) #----------------------------------------------------------------------------- # UltimateListHeaderWindow (internal) #----------------------------------------------------------------------------- class UltimateListHeaderWindow(wx.PyControl): """ This class holds the header window for L{UltimateListCtrl}. """ def __init__(self, win, id, owner, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name="UltimateListCtrlcolumntitles", isFooter=False): """ Default class constructor. :param `parent`: parent window. Must not be ``None``; :param `id`: window identifier. A value of -1 indicates a default value; :param `owner`: an instance of L{UltimateListCtrl}; :param `pos`: the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform; :param `size`: the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform; :param `style`: the window style; :param `validator`: the window validator; :param `name`: the window name; :param `isFooter`: ``True`` if the L{UltimateListHeaderWindow} is in a footer position, ``False`` otherwise. """ wx.PyControl.__init__(self, win, id, pos, size, style|wx.NO_BORDER, validator, name) self._isFooter = isFooter self._owner = owner self._currentCursor = wx.NullCursor self._resizeCursor = wx.StockCursor(wx.CURSOR_SIZEWE) self._isDragging = False # Custom renderer for every column self._headerCustomRenderer = None # column being resized or -1 self._column = -1 # divider line position in logical (unscrolled) coords self._currentX = 0 # minimal position beyond which the divider line can't be dragged in # logical coords self._minX = 0 # needs refresh self._dirty = False self._hasFont = False self._sendSetColumnWidth = False self._colToSend = -1 self._widthToSend = 0 self._leftDown = False self._enter = False self._currentColumn = -1 self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None) self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse) self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow) self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow) if _USE_VISATTR: attr = wx.Panel.GetClassDefaultAttributes() self.SetOwnForegroundColour(attr.colFg) self.SetOwnBackgroundColour(attr.colBg) if not self._hasFont: self.SetOwnFont(attr.font) else: self.SetOwnForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)) self.SetOwnBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE)) if not self._hasFont: self.SetOwnFont(wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)) def SetCustomRenderer(self, renderer=None): """ Associate a custom renderer with the header - all columns will use it :param `renderer`: a class able to correctly render header buttons :note: the renderer class **must** implement the methods `DrawHeaderButton`, and `GetForegroundColor`. """ if not self._owner.HasAGWFlag(ULC_REPORT): raise Exception("Custom renderers can be used on with style = ULC_REPORT") self._headerCustomRenderer = renderer def DoGetBestSize(self): """ Gets the size which best suits the window: for a control, it would be the minimal size which doesn't truncate the control, for a panel - the same size as it would have after a call to `Fit()`. """ w, h, d, dummy = self.GetFullTextExtent("Hg") maxH = self.GetTextHeight() nativeH = wx.RendererNative.Get().GetHeaderButtonHeight(self.GetParent()) if not self._isFooter: maxH = max(max(h, maxH), nativeH) maxH += d self.GetParent()._headerHeight = maxH else: maxH = max(h, nativeH) maxH += d self.GetParent()._footerHeight = maxH return wx.Size(200, maxH) def IsColumnShown(self, column): """ Returns ``True`` if the input column is shown, ``False`` if it is hidden. :param `column`: an integer specifying the column index. """ if column < 0 or column >= self._owner.GetColumnCount(): raise Exception("Invalid column") return self._owner.IsColumnShown(column) # shift the DC origin to match the position of the main window horz # scrollbar: this allows us to always use logical coords def AdjustDC(self, dc): """ Shifts the `wx.DC` origin to match the position of the main window horizontal scrollbar: this allows us to always use logical coordinates. :param `dc`: an instance of `wx.DC`. """ xpix, dummy = self._owner.GetScrollPixelsPerUnit() x, dummy = self._owner.GetViewStart() # account for the horz scrollbar offset dc.SetDeviceOrigin(-x*xpix, 0) def GetTextHeight(self): """ Returns the column text height, in pixels. """ maxH = 0 numColumns = self._owner.GetColumnCount() dc = wx.ClientDC(self) for i in xrange(numColumns): if not self.IsColumnShown(i): continue item = self._owner.GetColumn(i) if item.GetFont().IsOk(): dc.SetFont(item.GetFont()) else: dc.SetFont(self.GetFont()) wLabel, hLabel, dummy = dc.GetMultiLineTextExtent(item.GetText()) maxH = max(maxH, hLabel) return maxH def OnPaint(self, event): """ Handles the ``wx.EVT_PAINT`` event for L{UltimateListHeaderWindow}. :param `event`: a `wx.PaintEvent` event to be processed. """ dc = wx.BufferedPaintDC(self) # width and height of the entire header window w, h = self.GetClientSize() w, dummy = self._owner.CalcUnscrolledPosition(w, 0) dc.SetBrush(wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE))) dc.SetPen(wx.TRANSPARENT_PEN) dc.DrawRectangle(0, -1, w, h+2) self.PrepareDC(dc) self.AdjustDC(dc) dc.SetBackgroundMode(wx.TRANSPARENT) dc.SetTextForeground(self.GetForegroundColour()) x = HEADER_OFFSET_X numColumns = self._owner.GetColumnCount() item = UltimateListItem() renderer = wx.RendererNative.Get() enabled = self.GetParent().IsEnabled() virtual = self._owner.IsVirtual() isFooter = self._isFooter for i in xrange(numColumns): # Reset anything in the dc that a custom renderer might have changed dc.SetTextForeground(self.GetForegroundColour()) if x >= w: break if not self.IsColumnShown(i): continue # do next column if not shown item = self._owner.GetColumn(i) wCol = item._width cw = wCol ch = h flags = 0 if not enabled: flags |= wx.CONTROL_DISABLED # NB: The code below is not really Mac-specific, but since we are close # to 2.8 release and I don't have time to test on other platforms, I # defined this only for wxMac. If this behavior is desired on # other platforms, please go ahead and revise or remove the #ifdef. if "__WXMAC__" in wx.PlatformInfo: if not virtual and item._mask & ULC_MASK_STATE and item._state & ULC_STATE_SELECTED: flags |= wx.CONTROL_SELECTED if i == 0: flags |= wx.CONTROL_SPECIAL # mark as first column if i == self._currentColumn: if self._leftDown: flags |= wx.CONTROL_PRESSED else: if self._enter: flags |= wx.CONTROL_CURRENT # the width of the rect to draw: make it smaller to fit entirely # inside the column rect header_rect = wx.Rect(x-1, HEADER_OFFSET_Y-1, cw-1, ch) if self._headerCustomRenderer != None: self._headerCustomRenderer.DrawHeaderButton(dc, header_rect, flags) # The custom renderer will specify the color to draw the header text and buttons dc.SetTextForeground(self._headerCustomRenderer.GetForegroundColour()) elif item._mask & ULC_MASK_RENDERER: item.GetCustomRenderer().DrawHeaderButton(dc, header_rect, flags) # The custom renderer will specify the color to draw the header text and buttons dc.SetTextForeground(item.GetCustomRenderer().GetForegroundColour()) else: renderer.DrawHeaderButton(self, dc, header_rect, flags) # see if we have enough space for the column label if isFooter: if item.GetFooterFont().IsOk(): dc.SetFont(item.GetFooterFont()) else: dc.SetFont(self.GetFont()) else: if item.GetFont().IsOk(): dc.SetFont(item.GetFont()) else: dc.SetFont(self.GetFont()) wcheck = hcheck = 0 kind = (isFooter and [item.GetFooterKind()] or [item.GetKind()])[0] checked = (isFooter and [item.IsFooterChecked()] or [item.IsChecked()])[0] if kind in [1, 2]: # We got a checkbox-type item ix, iy = self._owner.GetCheckboxImageSize() # We draw it on the left, always self._owner.DrawCheckbox(dc, x + HEADER_OFFSET_X, HEADER_OFFSET_Y + (h - 4 - iy)/2, kind, checked, enabled) wcheck += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE cw -= ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE # for this we need the width of the text text = (isFooter and [item.GetFooterText()] or [item.GetText()])[0] wLabel, hLabel, dummy = dc.GetMultiLineTextExtent(text) wLabel += 2*EXTRA_WIDTH # and the width of the icon, if any image = (isFooter and [item._footerImage] or [item._image])[0] if image: imageList = self._owner._small_image_list if imageList: for img in image: ix, iy = imageList.GetSize(img) wLabel += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE else: imageList = None # ignore alignment if there is not enough space anyhow align = (isFooter and [item.GetFooterAlign()] or [item.GetAlign()])[0] align = (wLabel < cw and [align] or [ULC_FORMAT_LEFT])[0] if align == ULC_FORMAT_LEFT: xAligned = x + wcheck elif align == ULC_FORMAT_RIGHT: xAligned = x + cw - wLabel - HEADER_OFFSET_X elif align == ULC_FORMAT_CENTER: xAligned = x + wcheck + (cw - wLabel)/2 # if we have an image, draw it on the right of the label if imageList: for indx, img in enumerate(image): imageList.Draw(img, dc, xAligned + wLabel - (ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE)*(indx+1), HEADER_OFFSET_Y + (h - 4 - iy)/2, wx.IMAGELIST_DRAW_TRANSPARENT) cw -= ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE # draw the text clipping it so that it doesn't overwrite the column # boundary dc.SetClippingRegion(x, HEADER_OFFSET_Y, cw, h - 4) self.DrawTextFormatted(dc, text, wx.Rect(xAligned+EXTRA_WIDTH, HEADER_OFFSET_Y, cw-EXTRA_WIDTH, h-4)) x += wCol dc.DestroyClippingRegion() # Fill in what's missing to the right of the columns, otherwise we will # leave an unpainted area when columns are removed (and it looks better) if x < w: header_rect = wx.Rect(x, HEADER_OFFSET_Y, w - x, h) if self._headerCustomRenderer != None: # Why does the custom renderer need this adjustment?? header_rect.x = header_rect.x - 1 header_rect.y = header_rect.y - 1 self._headerCustomRenderer.DrawHeaderButton(dc, header_rect, wx.CONTROL_DIRTY) else: renderer.DrawHeaderButton(self, dc, header_rect, wx.CONTROL_DIRTY) # mark as last column def DrawTextFormatted(self, dc, text, rect): """ Draws the item text, correctly formatted. :param `dc`: an instance of `wx.DC`; :param `text`: the item text; :param `rect`: the item client rectangle. """ # determine if the string can fit inside the current width w, h, dummy = dc.GetMultiLineTextExtent(text) width = rect.width if w <= width: dc.DrawLabel(text, rect, wx.ALIGN_CENTER_VERTICAL) else: # determine the base width ellipsis = "..." base_w, h = dc.GetTextExtent(ellipsis) # continue until we have enough space or only one character left newText = text.split("\n") theText = "" for text in newText: lenText = len(text) drawntext = text w, dummy = dc.GetTextExtent(text) while lenText > 1: if w + base_w <= width: break w_c, h_c = dc.GetTextExtent(drawntext[-1]) drawntext = drawntext[0:-1] lenText -= 1 w -= w_c # if still not enough space, remove ellipsis characters while len(ellipsis) > 0 and w + base_w > width: ellipsis = ellipsis[0:-1] base_w, h = dc.GetTextExtent(ellipsis) theText += drawntext + ellipsis + "\n" theText = theText.rstrip() dc.DrawLabel(theText, rect, wx.ALIGN_CENTER_VERTICAL) def OnInternalIdle(self): """ This method is normally only used internally, but sometimes an application may need it to implement functionality that should not be disabled by an application defining an `OnIdle` handler in a derived class. This method may be used to do delayed painting, for example, and most implementations call `wx.Window.UpdateWindowUI` in order to send update events to the window in idle time. """ wx.PyControl.OnInternalIdle(self) if self._isFooter: return if self._sendSetColumnWidth: self._owner.SetColumnWidth(self._colToSend, self._widthToSend) self._sendSetColumnWidth = False def DrawCurrent(self): """ Force the redrawing of the column window. """ self._sendSetColumnWidth = True self._colToSend = self._column self._widthToSend = self._currentX - self._minX def OnMouse(self, event): """ Handles the ``wx.EVT_MOUSE_EVENTS`` event for L{UltimateListHeaderWindow}. :param `event`: a `wx.MouseEvent` event to be processed. """ # we want to work with logical coords x, dummy = self._owner.CalcUnscrolledPosition(event.GetX(), 0) y = event.GetY() columnX, columnY = x, y if self._isDragging: self.SendListEvent(wxEVT_COMMAND_LIST_COL_DRAGGING, event.GetPosition()) # we don't draw the line beyond our window, but we allow dragging it # there w, dummy = self.GetClientSize() w, dummy = self._owner.CalcUnscrolledPosition(w, 0) w -= 6 # erase the line if it was drawn if self._currentX < w: self.DrawCurrent() if event.ButtonUp(): self.ReleaseMouse() self._isDragging = False self._dirty = True self._owner.SetColumnWidth(self._column, self._currentX - self._minX) self.SendListEvent(wxEVT_COMMAND_LIST_COL_END_DRAG, event.GetPosition()) else: if x > self._minX + 7: self._currentX = x else: self._currentX = self._minX + 7 # draw in the new location if self._currentX < w: self.DrawCurrent() else: # not dragging self._minX = 0 hit_border = False # end of the current column xpos = 0 # find the column where this event occurred countCol = self._owner.GetColumnCount() broken = False for col in xrange(countCol): if not self.IsColumnShown(col): continue xpos += self._owner.GetColumnWidth(col) self._column = col if abs(x-xpos) < 3 and y < 22: # near the column border hit_border = True broken = True break if x < xpos: # inside the column broken = True break self._minX = xpos if not broken: self._column = -1 if event.LeftUp(): self._leftDown = False self.Refresh() if event.LeftDown() or event.RightUp(): if hit_border and event.LeftDown(): if not self._isFooter: if self.SendListEvent(wxEVT_COMMAND_LIST_COL_BEGIN_DRAG, event.GetPosition()): self._isDragging = True self._currentX = x self.CaptureMouse() self.DrawCurrent() #else: column resizing was vetoed by the user code else: # click on a column # record the selected state of the columns if event.LeftDown(): for i in xrange(self._owner.GetColumnCount()): if not self.IsColumnShown(col): continue colItem = self._owner.GetColumn(i) state = colItem.GetState() if i == self._column: colItem.SetState(state | ULC_STATE_SELECTED) theX = x else: colItem.SetState(state & ~ULC_STATE_SELECTED) self._leftDown = True self._owner.SetColumn(i, colItem) x += self._owner.GetColumnWidth(i) if self.HandleColumnCheck(self._column, event.GetPosition()): return if not self._isFooter: self.SendListEvent((event.LeftDown() and [wxEVT_COMMAND_LIST_COL_CLICK] or \ [wxEVT_COMMAND_LIST_COL_RIGHT_CLICK])[0], event.GetPosition()) else: self.SendListEvent((event.LeftDown() and [wxEVT_COMMAND_LIST_FOOTER_CLICK] or \ [wxEVT_COMMAND_LIST_FOOTER_RIGHT_CLICK])[0], event.GetPosition()) self._leftDown = True self._currentColumn = self._column elif event.Moving(): setCursor = False if not self._isFooter: if hit_border: setCursor = self._currentCursor == wx.STANDARD_CURSOR self._currentCursor = self._resizeCursor else: setCursor = self._currentCursor != wx.STANDARD_CURSOR self._currentCursor = wx.STANDARD_CURSOR if setCursor: self.SetCursor(self._currentCursor) else: column = self.HitTestColumn(columnX, columnY) self._enter = True self._currentColumn = column self._leftDown = wx.GetMouseState().LeftDown() self.Refresh() elif event.ButtonDClick(): self.HandleColumnCheck(self._column, event.GetPosition()) def HandleColumnCheck(self, column, pos): """ Handles the case in which a column contains a checkbox-like item. :param `column`: the column index; :param `pos`: the mouse position. """ if column < 0 or column >= self._owner.GetColumnCount(): return False colItem = self._owner.GetColumn(column) # Let's see if it is a checkbox-type item kind = (self._isFooter and [colItem.GetFooterKind()] or [colItem.GetKind()])[0] if kind not in [1, 2]: return False x = HEADER_OFFSET_X for i in xrange(self._owner.GetColumnCount()): if not self.IsColumnShown(i): continue if i == self._column: theX = x break x += self._owner.GetColumnWidth(i) parent = self.GetParent() w, h = self.GetClientSize() ix, iy = self._owner.GetCheckboxImageSize() rect = wx.Rect(theX + HEADER_OFFSET_X, HEADER_OFFSET_Y + (h - 4 - iy)/2, ix, iy) if rect.Contains(pos): # User clicked on the checkbox evt = (self._isFooter and [wxEVT_COMMAND_LIST_FOOTER_CHECKING] or [wxEVT_COMMAND_LIST_COL_CHECKING])[0] if self.SendListEvent(evt, pos): # No veto for the item checking if self._isFooter: isChecked = colItem.IsFooterChecked() colItem.CheckFooter(not isChecked) else: isChecked = colItem.IsChecked() colItem.Check(not isChecked) self._owner.SetColumn(column, colItem) evt = (self._isFooter and [wxEVT_COMMAND_LIST_FOOTER_CHECKED] or [wxEVT_COMMAND_LIST_COL_CHECKED])[0] self.SendListEvent(evt, pos) self.RefreshRect(rect) if self._isFooter: return True if parent.HasAGWFlag(ULC_AUTO_CHECK_CHILD): self._owner.AutoCheckChild(isChecked, self._column) elif parent.HasAGWFlag(ULC_AUTO_TOGGLE_CHILD): self._owner.AutoToggleChild(self._column) return True return False def OnEnterWindow(self, event): """ Handles the ``wx.EVT_ENTER_WINDOW`` event for L{UltimateListHeaderWindow}. :param `event`: a `wx.MouseEvent` event to be processed. """ x, y = self._owner.CalcUnscrolledPosition(*self.ScreenToClient(wx.GetMousePosition())) column = self.HitTestColumn(x, y) self._leftDown = wx.GetMouseState().LeftDown() self._enter = column >= 0 and column < self._owner.GetColumnCount() self._currentColumn = column self.Refresh() def OnLeaveWindow(self, event): """ Handles the ``wx.EVT_LEAVE_WINDOW`` event for L{UltimateListHeaderWindow}. :param `event`: a `wx.MouseEvent` event to be processed. """ self._enter = False self._leftDown = False self._currentColumn = -1 self.Refresh() def HitTestColumn(self, x, y): """ HitTest method for column headers. :param `x`: the mouse x position; :param `y`: the mouse y position. :return: The column index if any column client rectangle contains the mouse position, ``wx.NOT_FOUND`` otherwise. """ xOld = 0 for i in xrange(self._owner.GetColumnCount()): if not self.IsColumnShown(i): continue xOld += self._owner.GetColumnWidth(i) if x <= xOld: return i return -1 def OnSetFocus(self, event): """ Handles the ``wx.EVT_SET_FOCUS`` event for L{UltimateListHeaderWindow}. :param `event`: a `wx.FocusEvent` event to be processed. """ self._owner.SetFocusIgnoringChildren() self._owner.Update() def SendListEvent(self, eventType, pos): """ Sends a L{UltimateListEvent} for the parent window. :param `eventType`: the event type; :param `pos`: an instance of `wx.Point`. """ parent = self.GetParent() le = UltimateListEvent(eventType, parent.GetId()) le.SetEventObject(parent) le.m_pointDrag = pos # the position should be relative to the parent window, not # this one for compatibility with MSW and common sense: the # user code doesn't know anything at all about this header # window, so why should it get positions relative to it? le.m_pointDrag.y -= self.GetSize().y le.m_col = self._column return (not parent.GetEventHandler().ProcessEvent(le) or le.IsAllowed()) def GetOwner(self): """ Returns the header window owner, an instance of L{UltimateListCtrl}. """ return self._owner #----------------------------------------------------------------------------- # UltimateListRenameTimer (internal) #----------------------------------------------------------------------------- class UltimateListRenameTimer(wx.Timer): """ Timer used for enabling in-place edit. """ def __init__(self, owner): """ Default class constructor. For internal use: do not call it in your code! :param `owner`: an instance of L{UltimateListCtrl}. """ wx.Timer.__init__(self) self._owner = owner def Notify(self): """ The timer has expired. """ self._owner.OnRenameTimer() #----------------------------------------------------------------------------- # UltimateListTextCtrl (internal) #----------------------------------------------------------------------------- class UltimateListTextCtrl(ExpandoTextCtrl): """ Control used for in-place edit. This is a subclass of `ExpandoTextCtrl` as L{UltimateListCtrl} supports multiline text items. :note: To add a newline character in a multiline item, press ``Shift`` + ``Enter`` as the ``Enter`` key alone is consumed by L{UltimateListCtrl} to finish the editing and ``Ctrl`` + ``Enter`` is consumed by the platform for tab navigation. """ def __init__(self, owner, itemEdit): """ Default class constructor. For internal use: do not call it in your code! :param `owner`: the control parent (an instance of L{UltimateListCtrl} ); :param `itemEdit`: an instance of L{UltimateListItem}. """ self._startValue = owner.GetItemText(itemEdit) self._currentValue = self._startValue self._itemEdited = itemEdit self._owner = owner self._finished = False self._aboutToFinish = False rectLabel = owner.GetLineLabelRect(itemEdit) rectLabel.x, rectLabel.y = self._owner.CalcScrolledPosition(rectLabel.x, rectLabel.y) xSize, ySize = rectLabel.width + 10, rectLabel.height expandoStyle = wx.WANTS_CHARS if wx.Platform in ["__WXGTK__", "__WXMAC__"]: expandoStyle |= wx.SIMPLE_BORDER else: expandoStyle |= wx.SUNKEN_BORDER ExpandoTextCtrl.__init__(self, owner, -1, self._startValue, wx.Point(rectLabel.x, rectLabel.y), wx.Size(xSize, ySize), expandoStyle) self.Bind(wx.EVT_CHAR, self.OnChar) self.Bind(wx.EVT_KEY_UP, self.OnKeyUp) self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus) def AcceptChanges(self): """ Accepts/refuses the changes made by the user. """ value = self.GetValue() if value == self._startValue: # nothing changed, always accept # when an item remains unchanged, the owner # needs to be notified that the user decided # not to change the tree item label, and that # the edit has been cancelled self._owner.OnRenameCancelled(self._itemEdited) return True if not self._owner.OnRenameAccept(self._itemEdited, value): # vetoed by the user return False # accepted, do rename the item self._owner.SetItemText(self._itemEdited, value) if value.count("\n") != self._startValue.count("\n"): self._owner.ResetLineDimensions() self._owner.Refresh() return True def Finish(self): """ Finish editing. """ try: if not self._finished: self._finished = True self._owner.SetFocusIgnoringChildren() self._owner.ResetTextControl() except wx.PyDeadObjectError: return def OnChar(self, event): """ Handles the ``wx.EVT_CHAR`` event for L{UltimateListTextCtrl}. :param `event`: a `wx.KeyEvent` event to be processed. """ keycode = event.GetKeyCode() shiftDown = event.ShiftDown() if keycode in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]: if shiftDown: event.Skip() else: self._aboutToFinish = True self.SetValue(self._currentValue) # Notify the owner about the changes self.AcceptChanges() # Even if vetoed, close the control (consistent with MSW) wx.CallAfter(self.Finish) elif keycode == wx.WXK_ESCAPE: self.StopEditing() else: event.Skip() def OnKeyUp(self, event): """ Handles the ``wx.EVT_KEY_UP`` event for L{UltimateListTextCtrl}. :param `event`: a `wx.KeyEvent` event to be processed. """ if not self._finished: # auto-grow the textctrl: parentSize = self._owner.GetSize() myPos = self.GetPosition() mySize = self.GetSize() dc = wx.ClientDC(self) sx, sy, dummy = dc.GetMultiLineTextExtent(self.GetValue() + "M") if myPos.x + sx > parentSize.x: sx = parentSize.x - myPos.x if mySize.x > sx: sx = mySize.x self.SetSize((sx, -1)) self._currentValue = self.GetValue() event.Skip() def OnKillFocus(self, event): """ Handles the ``wx.EVT_KILL_FOCUS`` event for L{UltimateListTextCtrl}. :param `event`: a `wx.FocusEvent` event to be processed. """ if not self._finished and not self._aboutToFinish: # We must finish regardless of success, otherwise we'll get # focus problems: if not self.AcceptChanges(): self._owner.OnRenameCancelled(self._itemEdited) # We must let the native text control handle focus, too, otherwise # it could have problems with the cursor (e.g., in wxGTK). event.Skip() wx.CallAfter(self.Finish) def StopEditing(self): """ Suddenly stops the editing. """ self._owner.OnRenameCancelled(self._itemEdited) self.Finish() #----------------------------------------------------------------------------- # UltimateListMainWindow (internal) #----------------------------------------------------------------------------- class UltimateListMainWindow(wx.PyScrolledWindow): """ This is the main widget implementation of L{UltimateListCtrl}. """ def __init__(self, parent, id, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=0, name="listctrlmainwindow"): """ Default class constructor. :param `parent`: parent window. Must not be ``None``; :param `id`: window identifier. A value of -1 indicates a default value; :param `pos`: the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform; :param `size`: the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform; :param `style`: the underlying `wx.PyScrolledWindow` window style; :param `agwStyle`: the AGW-specific window style; can be almost any combination of the following bits: =============================== =========== ==================================================================================================== Window Styles Hex Value Description =============================== =========== ==================================================================================================== ``ULC_VRULES`` 0x1 Draws light vertical rules between rows in report mode. ``ULC_HRULES`` 0x2 Draws light horizontal rules between rows in report mode. ``ULC_ICON`` 0x4 Large icon view, with optional labels. ``ULC_SMALL_ICON`` 0x8 Small icon view, with optional labels. ``ULC_LIST`` 0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a `wx.ListBox`. ``ULC_REPORT`` 0x20 Single or multicolumn report view, with optional header. ``ULC_ALIGN_TOP`` 0x40 Icons align to the top. Win32 default, Win32 only. ``ULC_ALIGN_LEFT`` 0x80 Icons align to the left. ``ULC_AUTOARRANGE`` 0x100 Icons arrange themselves. Win32 only. ``ULC_VIRTUAL`` 0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``. ``ULC_EDIT_LABELS`` 0x400 Labels are editable: the application will be notified when editing starts. ``ULC_NO_HEADER`` 0x800 No header in report mode. ``ULC_NO_SORT_HEADER`` 0x1000 No Docs. ``ULC_SINGLE_SEL`` 0x2000 Single selection (default is multiple). ``ULC_SORT_ASCENDING`` 0x4000 Sort in ascending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.) ``ULC_SORT_DESCENDING`` 0x8000 Sort in descending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.) ``ULC_TILE`` 0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented). ``ULC_NO_HIGHLIGHT`` 0x20000 No highlight when an item is selected. ``ULC_STICKY_HIGHLIGHT`` 0x40000 Items are selected by simply hovering on them, with no need to click on them. ``ULC_STICKY_NOSELEVENT`` 0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style. ``ULC_SEND_LEFTCLICK`` 0x100000 Send a left click event when an item is selected. ``ULC_HAS_VARIABLE_ROW_HEIGHT`` 0x200000 The list has variable row heights. ``ULC_AUTO_CHECK_CHILD`` 0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column. ``ULC_AUTO_TOGGLE_CHILD`` 0x800000 When a column header has a checkbox associated, toggle all the subitems in that column. ``ULC_AUTO_CHECK_PARENT`` 0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well. ``ULC_SHOW_TOOLTIPS`` 0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text. ``ULC_HOT_TRACKING`` 0x4000000 Enable hot tracking of items on mouse motion. ``ULC_BORDER_SELECT`` 0x8000000 Changes border colour whan an item is selected, instead of highlighting the item. ``ULC_TRACK_SELECT`` 0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`. ``ULC_HEADER_IN_ALL_VIEWS`` 0x20000000 Show column headers in all view modes. ``ULC_NO_FULL_ROW_SELECT`` 0x40000000 When an item is selected, the only the item in the first column is highlighted. ``ULC_FOOTER`` 0x80000000 Show a footer too (only when header is present). =============================== =========== ==================================================================================================== :param `name`: the window name. """ wx.PyScrolledWindow.__init__(self, parent, id, pos, size, style|wx.HSCROLL|wx.VSCROLL, name) # the list of column objects self._columns = [] # the array of all line objects for a non virtual list control (for the # virtual list control we only ever use self._lines[0]) self._lines = [] # currently focused item or -1 self._current = -1 # the number of lines per page self._linesPerPage = 0 # Automatically resized column - this column expands to fill the width of the window self._resizeColumn = -1 self._resizeColMinWidth = None # this flag is set when something which should result in the window # redrawing happens (i.e. an item was added or deleted, or its appearance # changed) and OnPaint() doesn't redraw the window while it is set which # allows to minimize the number of repaintings when a lot of items are # being added. The real repainting occurs only after the next OnIdle() # call self._dirty = False self._parent = parent self.Init() self._highlightBrush = wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT), wx.SOLID) btnshadow = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW) self._highlightUnfocusedBrush = wx.Brush(btnshadow, wx.SOLID) r, g, b = btnshadow.Red(), btnshadow.Green(), btnshadow.Blue() backcolour = (max((r >> 1) - 20, 0), max((g >> 1) - 20, 0), max((b >> 1) - 20, 0)) backcolour = wx.Colour(backcolour[0], backcolour[1], backcolour[2]) self._highlightUnfocusedBrush2 = wx.Brush(backcolour) self.SetScrollbars(0, 0, 0, 0, 0, 0) attr = wx.ListCtrl.GetClassDefaultAttributes() self.SetOwnForegroundColour(attr.colFg) self.SetOwnBackgroundColour(attr.colBg) self.SetOwnFont(attr.font) self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse) self.Bind(wx.EVT_CHILD_FOCUS, self.OnChildFocus) self.Bind(wx.EVT_CHAR, self.OnChar) self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) self.Bind(wx.EVT_KEY_UP, self.OnKeyUp) self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus) self.Bind(wx.EVT_SCROLLWIN, self.OnScroll) self.Bind(wx.EVT_TIMER, self.OnHoverTimer, self._hoverTimer) def Init(self): """ Initializes the L{UltimateListMainWindow} widget. """ self._dirty = True self._countVirt = 0 self._lineFrom = None self._lineTo = - 1 self._linesPerPage = 0 self._headerWidth = 0 self._lineHeight = 0 self._small_image_list = None self._normal_image_list = None self._small_spacing = 30 self._normal_spacing = 40 self._hasFocus = False self._dragCount = 0 self._isCreated = False self._lastOnSame = False self._renameTimer = UltimateListRenameTimer(self) self._textctrl = None self._current = -1 self._lineLastClicked = -1 self._lineSelectSingleOnUp = -1 self._lineBeforeLastClicked = -1 self._dragStart = wx.Point(-1, -1) self._aColWidths = [] self._selStore = SelectionStore() self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM) # Background image settings self._backgroundImage = None self._imageStretchStyle = _StyleTile # Disabled items colour self._disabledColour = wx.Colour(180, 180, 180) # Gradient selection colours self._firstcolour = colour= wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT) self._secondcolour = wx.WHITE self._usegradients = False self._gradientstyle = 1 # Vertical Gradient # Vista Selection Styles self._vistaselection = False self.SetImageListCheck(16, 16) # Disabled items colour self._disabledColour = wx.Colour(180, 180, 180) # Hyperlinks things normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) self._hypertextfont = wx.Font(normalFont.GetPointSize(), normalFont.GetFamily(), normalFont.GetStyle(), wx.NORMAL, True, normalFont.GetFaceName(), normalFont.GetEncoding()) self._hypertextnewcolour = wx.BLUE self._hypertextvisitedcolour = wx.Colour(200, 47, 200) self._isonhyperlink = False self._itemWithWindow = [] self._hasWindows = False self._shortItems = [] self._isDragging = False self._cursor = wx.STANDARD_CURSOR image = GetdragcursorImage() # since this image didn't come from a .cur file, tell it where the hotspot is image.SetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_X, 1) image.SetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_Y, 1) # make the image into a cursor self._dragCursor = wx.CursorFromImage(image) self._dragItem = None self._dropTarget = None self._oldHotCurrent = None self._newHotCurrent = None self._waterMark = None self._hoverTimer = wx.Timer(self, wx.ID_ANY) self._hoverItem = -1 def GetMainWindowOfCompositeControl(self): """ Returns the L{UltimateListMainWindow} parent. """ return self.GetParent() def DoGetBestSize(self): """ Gets the size which best suits the window: for a control, it would be the minimal size which doesn't truncate the control, for a panel - the same size as it would have after a call to `Fit()`. """ return wx.Size(100, 80) def HasAGWFlag(self, flag): """ Returns ``True`` if the window has the given `flag` bit set. :param `flag`: the bit to check. :see: L{UltimateListCtrl.SetSingleStyle} for a list of valid flags. """ return self._parent.HasAGWFlag(flag) def IsColumnShown(self, column): """ Returns ``True`` if the input column is shown, ``False`` if it is hidden. :param `column`: an integer specifying the column index. """ return self.GetColumn(column).IsShown() # return True if this is a virtual list control def IsVirtual(self): """ Returns ``True`` if the window has the ``ULC_VIRTUAL`` style set. """ return self.HasAGWFlag(ULC_VIRTUAL) # return True if the control is in report mode def InReportView(self): """ Returns ``True`` if the window is in report mode. """ return self.HasAGWFlag(ULC_REPORT) def InTileView(self): """ Returns ``True`` if the window is in tile mode (partially implemented). :todo: Fully implement tile view for L{UltimateListCtrl}. """ return self.HasAGWFlag(ULC_TILE) # return True if we are in single selection mode, False if multi sel def IsSingleSel(self): """ Returns ``True`` if we are in single selection mode, ``False`` if multi selection. """ return self.HasAGWFlag(ULC_SINGLE_SEL) def HasFocus(self): """ Returns ``True`` if the window has focus. """ return self._hasFocus # do we have a header window? def HasHeader(self): """ Returns ``True`` if the header window is shown. """ if (self.InReportView() or self.InTileView()) and not self.HasAGWFlag(ULC_NO_HEADER): return True if self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS): return True return False # do we have a footer window? def HasFooter(self): """ Returns ``True`` if the footer window is shown. """ if self.HasHeader() and self.HasAGWFlag(ULC_FOOTER): return True return False # toggle the line state and refresh it def ReverseHighlight(self, line): """ Toggles the line state and refreshes it. :param `line`: an instance of L{UltimateListLineData}. """ self.HighlightLine(line, not self.IsHighlighted(line)) self.RefreshLine(line) # get the size of the total line rect def GetLineSize(self, line): """ Returns the size of the total line client rectangle. :param `line`: an instance of L{UltimateListLineData}. """ return self.GetLineRect(line).GetSize() # bring the current item into view def MoveToFocus(self): """ Brings tyhe current item into view. """ self.MoveToItem(self._current) def GetColumnCount(self): """ Returns the total number of columns in the L{UltimateListCtrl}. """ return len(self._columns) def GetItemText(self, item): """ Returns the item text. :param `item`: an instance of L{UltimateListItem}. """ info = UltimateListItem() info._mask = ULC_MASK_TEXT info._itemId = item info = self.GetItem(info) return info._text def SetItemText(self, item, value): """ Sets the item text. :param `item`: an instance of L{UltimateListItem}; :param `value`: the new item text. """ info = UltimateListItem() info._mask = ULC_MASK_TEXT info._itemId = item info._text = value self.SetItem(info) def IsEmpty(self): """ Returns ``True`` if the window has no items in it. """ return self.GetItemCount() == 0 def ResetCurrent(self): """ Resets the current item to ``None``. """ self.ChangeCurrent(-1) def HasCurrent(self): """ Returns ``True`` if the current item has been set, either programmatically or by user intervention. """ return self._current != -1 # override base class virtual to reset self._lineHeight when the font changes def SetFont(self, font): """ Overridden base class virtual to reset the line height when the font changes. :param `font`: a valid `wx.Font` object. :note: Overridden from `wx.PyScrolledWindow`. """ if not wx.PyScrolledWindow.SetFont(self, font): return False self._lineHeight = 0 self.ResetLineDimensions() return True def ResetLineDimensions(self, force=False): """ Resets the line dimensions, so that client rectangles and positions are recalculated. :param `force`: ``True`` to reset all line dimensions. """ if (self.HasAGWFlag(ULC_REPORT) and self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT) and not self.IsVirtual()) or force: for l in xrange(self.GetItemCount()): line = self.GetLine(l) line.ResetDimensions() # these are for UltimateListLineData usage only # get the backpointer to the list ctrl def GetListCtrl(self): """ Returns the parent widget, an instance of L{UltimateListCtrl}. """ return self.GetParent() # get the brush to use for the item highlighting def GetHighlightBrush(self): """ Returns the brush to use for the item highlighting. """ return (self._hasFocus and [self._highlightBrush] or [self._highlightUnfocusedBrush])[0] # get the line data for the given index def GetLine(self, n): """ Returns the line data for the given index. :param `n`: the line index. """ if self.IsVirtual(): self.CacheLineData(n) n = 0 return self._lines[n] # force us to recalculate the range of visible lines def ResetVisibleLinesRange(self, reset=False): """ Forces us to recalculate the range of visible lines. :param `reset`: ``True`` to reset all line dimensions, which will then be recalculated. """ self._lineFrom = -1 if self.IsShownOnScreen() and reset: self.ResetLineDimensions() # Called on EVT_SIZE to resize the _resizeColumn to fill the width of the window def ResizeColumns(self): """ If ``ULC_AUTOSIZE_FILL`` was passed to L{UltimateListCtrl.SetColumnWidth} then that column's width will be expanded to fill the window on a resize event. Called by L{UltimateListCtrl.OnSize} when the window is resized. """ if self._resizeColumn == -1: return numCols = self.GetColumnCount() if numCols == 0: return # Nothing to resize. resizeCol = self._resizeColumn if self._resizeColMinWidth == None: self._resizeColMinWidth = self.GetColumnWidth(resizeCol) # We're showing the vertical scrollbar -> allow for scrollbar width # NOTE: on GTK, the scrollbar is included in the client size, but on # Windows it is not included listWidth = self.GetClientSize().width if wx.Platform != '__WXMSW__': if self.GetItemCount() > self.GetCountPerPage(): scrollWidth = wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X) listWidth = listWidth - scrollWidth totColWidth = 0 # Width of all columns except last one. for col in range(numCols): if col != (resizeCol): totColWidth = totColWidth + self.GetColumnWidth(col) resizeColWidth = self.GetColumnWidth(resizeCol) if totColWidth + self._resizeColMinWidth > listWidth: # We haven't got the width to show the last column at its minimum # width -> set it to its minimum width and allow the horizontal # scrollbar to show. self.SetColumnWidth(resizeCol, self._resizeColMinWidth) return # Resize the last column to take up the remaining available space. self.SetColumnWidth(resizeCol, listWidth - totColWidth) # get the colour to be used for drawing the rules def GetRuleColour(self): """ Returns the colour to be used for drawing the horizontal and vertical rules. """ return wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT) def SetReportView(self, inReportView): """ Sets whether L{UltimateListCtrl} is in report view or not. :param `inReportView`: ``True`` to set L{UltimateListCtrl} in report view, ``False`` otherwise. """ for line in self._lines: line.SetReportView(inReportView) def CacheLineData(self, line): """ Saves the current line attributes. :param `line`: an instance of L{UltimateListLineData}. :note: This method is used only if the L{UltimateListCtrl} has the ``ULC_VIRTUAL`` style set. """ listctrl = self.GetListCtrl() ld = self.GetDummyLine() countCol = self.GetColumnCount() for col in xrange(countCol): ld.SetText(col, listctrl.OnGetItemText(line, col)) ld.SetImage(col, listctrl.OnGetItemColumnImage(line, col)) kind = listctrl.OnGetItemColumnKind(line, col) ld.SetKind(col, kind) if kind > 0: ld.Check(col, listctrl.OnGetItemColumnCheck(line, col)) ld.SetAttr(listctrl.OnGetItemAttr(line)) def GetDummyLine(self): """ Returns a dummy line. :note: This method is used only if the L{UltimateListCtrl} has the ``ULC_VIRTUAL`` style set. """ if self.IsEmpty(): raise Exception("invalid line index") if not self.IsVirtual(): raise Exception("GetDummyLine() shouldn't be called") # we need to recreate the dummy line if the number of columns in the # control changed as it would have the incorrect number of fields # otherwise if len(self._lines) > 0 and len(self._lines[0]._items) != self.GetColumnCount(): self._lines = [] if not self._lines: line = UltimateListLineData(self) self._lines.append(line) return self._lines[0] # ---------------------------------------------------------------------------- # line geometry (report mode only) # ---------------------------------------------------------------------------- def GetLineHeight(self, item=None): """ Returns the line height for a specific item. :param `item`: if not ``None``, an instance of L{UltimateListItem}. """ # we cache the line height as calling GetTextExtent() is slow if item is None or not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): if not self._lineHeight: dc = wx.ClientDC(self) dc.SetFont(self.GetFont()) dummy, y = dc.GetTextExtent("H") if self._small_image_list and self._small_image_list.GetImageCount(): iw, ih = self._small_image_list.GetSize(0) y = max(y, ih) y += EXTRA_HEIGHT self._lineHeight = y + LINE_SPACING return self._lineHeight else: line = self.GetLine(item) LH = line.GetHeight() if LH != -1: return LH dc = wx.ClientDC(self) allTextY = 0 for col, items in enumerate(line._items): if items.GetCustomRenderer(): allTextY = max(allTextY, items.GetCustomRenderer().GetLineHeight()) continue if items.HasFont(): dc.SetFont(items.GetFont()) else: dc.SetFont(self.GetFont()) text_x, text_y, dummy = dc.GetMultiLineTextExtent(items.GetText()) allTextY = max(text_y, allTextY) if items.GetWindow(): xSize, ySize = items.GetWindowSize() allTextY = max(allTextY, ySize) if self._small_image_list and self._small_image_list.GetImageCount(): for img in items._image: iw, ih = self._small_image_list.GetSize(img) allTextY = max(allTextY, ih) allTextY += EXTRA_HEIGHT line.SetHeight(allTextY) return allTextY def GetLineY(self, line): """ Returns the line y position. :param `line`: an instance of L{UltimateListLineData}. """ if self.IsVirtual(): return LINE_SPACING + line*self.GetLineHeight() lineItem = self.GetLine(line) lineY = lineItem.GetY() if lineY != -1: return lineY lineY = 0 for l in xrange(line): lineY += self.GetLineHeight(l) lineItem.SetY(LINE_SPACING + lineY) return LINE_SPACING + lineY def GetLineRect(self, line): """ Returns the line client rectangle. :param `line`: an instance of L{UltimateListLineData}. """ if not self.InReportView(): return self.GetLine(line)._gi._rectAll rect = wx.Rect(HEADER_OFFSET_X, self.GetLineY(line), self.GetHeaderWidth(), self.GetLineHeight(line)) return rect def GetLineLabelRect(self, line): """ Returns the line client rectangle for the item text only. :param `line`: an instance of L{UltimateListLineData}. """ if not self.InReportView(): return self.GetLine(line)._gi._rectLabel image_x = 0 item = self.GetLine(line) if item.HasImage(): ix, iy = self.GetImageSize(item.GetImage()) image_x = ix if item.GetKind() in [1, 2]: image_x += self.GetCheckboxImageSize()[0] rect = wx.Rect(image_x + HEADER_OFFSET_X, self.GetLineY(line), self.GetColumnWidth(0) - image_x, self.GetLineHeight(line)) return rect def GetLineIconRect(self, line): """ Returns the line client rectangle for the item image only. :param `line`: an instance of L{UltimateListLineData}. """ if not self.InReportView(): return self.GetLine(line)._gi._rectIcon ld = self.GetLine(line) image_x = HEADER_OFFSET_X if ld.GetKind() in [1, 2]: image_x += self.GetCheckboxImageSize()[0] rect = wx.Rect(image_x, self.GetLineY(line), *self.GetImageSize(ld.GetImage())) return rect def GetLineCheckboxRect(self, line): """ Returns the line client rectangle for the item checkbox image only. :param `line`: an instance of L{UltimateListLineData}. """ if not self.InReportView(): return self.GetLine(line)._gi._rectCheck ld = self.GetLine(line) LH = self.GetLineHeight(line) wcheck, hcheck = self.GetCheckboxImageSize() rect = wx.Rect(HEADER_OFFSET_X, self.GetLineY(line) + LH/2 - hcheck/2, wcheck, hcheck) return rect def GetLineHighlightRect(self, line): """ Returns the line client rectangle when the line is highlighted. :param `line`: an instance of L{UltimateListLineData}. """ return (self.InReportView() and [self.GetLineRect(line)] or [self.GetLine(line)._gi._rectHighlight])[0] def HitTestLine(self, line, x, y): """ HitTest method for a L{UltimateListCtrl} line. :param `line`: an instance of L{UltimateListLineData}; :param `x`: the mouse x position; :param `y`: the mouse y position. :return: a tuple of values, representing the item hit and a hit flag. The hit flag can be one of the following bits: =============================== ========= ================================ HitTest Flag Hex Value Description =============================== ========= ================================ ``ULC_HITTEST_ABOVE`` 0x1 Above the client area ``ULC_HITTEST_BELOW`` 0x2 Below the client area ``ULC_HITTEST_NOWHERE`` 0x4 In the client area but below the last item ``ULC_HITTEST_ONITEM`` 0x2a0 Anywhere on the item (text, icon, checkbox image) ``ULC_HITTEST_ONITEMICON`` 0x20 On the bitmap associated with an item ``ULC_HITTEST_ONITEMLABEL`` 0x80 On the label (string) associated with an item ``ULC_HITTEST_ONITEMRIGHT`` 0x100 In the area to the right of an item ``ULC_HITTEST_ONITEMSTATEICON`` 0x200 On the state icon for a list view item that is in a user-defined state ``ULC_HITTEST_TOLEFT`` 0x400 To the left of the client area ``ULC_HITTEST_TORIGHT`` 0x800 To the right of the client area ``ULC_HITTEST_ONITEMCHECK`` 0x1000 On the item checkbox (if any) =============================== ========= ================================ """ ld = self.GetLine(line) if self.InReportView() and not self.IsVirtual(): lineY = self.GetLineY(line) xstart = HEADER_OFFSET_X for col, item in enumerate(ld._items): width = self.GetColumnWidth(col) xOld = xstart xstart += width ix = 0 if (line, col) in self._shortItems: rect = wx.Rect(xOld, lineY, width, self.GetLineHeight(line)) if rect.Contains((x, y)): newItem = self.GetParent().GetItem(line, col) return newItem, ULC_HITTEST_ONITEM if item.GetKind() in [1, 2]: # We got a checkbox-type item ix, iy = self.GetCheckboxImageSize() LH = self.GetLineHeight(line) rect = wx.Rect(xOld, lineY + LH/2 - iy/2, ix, iy) if rect.Contains((x, y)): newItem = self.GetParent().GetItem(line, col) return newItem, ULC_HITTEST_ONITEMCHECK if item.IsHyperText(): start, end = self.GetItemTextSize(item) rect = wx.Rect(xOld+start, lineY, end, self.GetLineHeight(line)) if rect.Contains((x, y)): newItem = self.GetParent().GetItem(line, col) return newItem, ULC_HITTEST_ONITEMLABEL xOld += ix if ld.HasImage() and self.GetLineIconRect(line).Contains((x, y)): return self.GetParent().GetItem(line), ULC_HITTEST_ONITEMICON # VS: Testing for "ld.HasText() || InReportView()" instead of # "ld.HasText()" is needed to make empty lines in report view # possible if ld.HasText() or self.InReportView(): if self.InReportView(): rect = self.GetLineRect(line) else: checkRect = self.GetLineCheckboxRect(line) if checkRect.Contains((x, y)): return self.GetParent().GetItem(line), ULC_HITTEST_ONITEMCHECK rect = self.GetLineLabelRect(line) if rect.Contains((x, y)): return self.GetParent().GetItem(line), ULC_HITTEST_ONITEMLABEL rect = self.GetLineRect(line) if rect.Contains((x, y)): return self.GetParent().GetItem(line), ULC_HITTEST_ONITEM return None, 0 # ---------------------------------------------------------------------------- # highlight (selection) handling # ---------------------------------------------------------------------------- def IsHighlighted(self, line): """ Returns ``True`` if the input line is highlighted. :param `line`: an instance of L{UltimateListLineData}. """ if self.IsVirtual(): return self._selStore.IsSelected(line) else: # !virtual ld = self.GetLine(line) return ld.IsHighlighted() def HighlightLines(self, lineFrom, lineTo, highlight=True): """ Highlights a range of lines in L{UltimateListCtrl}. :param `lineFrom`: an integer representing the first line to highlight; :param `lineTo`: an integer representing the last line to highlight; :param `highlight`: ``True`` to highlight the lines, ``False`` otherwise. """ if self.IsVirtual(): linesChanged = self._selStore.SelectRange(lineFrom, lineTo, highlight) if not linesChanged: # many items changed state, refresh everything self.RefreshLines(lineFrom, lineTo) else: # only a few items changed state, refresh only them for n in xrange(len(linesChanged)): self.RefreshLine(linesChanged[n]) else: # iterate over all items in non report view for line in xrange(lineFrom, lineTo+1): if self.HighlightLine(line, highlight): self.RefreshLine(line) def HighlightLine(self, line, highlight=True): """ Highlights a line in L{UltimateListCtrl}. :param `line`: an instance of L{UltimateListLineData}; :param `highlight`: ``True`` to highlight the line, ``False`` otherwise. """ changed = False if self.IsVirtual(): changed = self._selStore.SelectItem(line, highlight) else: # !virtual ld = self.GetLine(line) changed = ld.Highlight(highlight) dontNotify = self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and self.HasAGWFlag(ULC_STICKY_NOSELEVENT) if changed and not dontNotify: self.SendNotify(line, (highlight and [wxEVT_COMMAND_LIST_ITEM_SELECTED] or [wxEVT_COMMAND_LIST_ITEM_DESELECTED])[0]) return changed def RefreshLine(self, line): """ Redraws the input line. :param `line`: an instance of L{UltimateListLineData}. """ if self.InReportView(): visibleFrom, visibleTo = self.GetVisibleLinesRange() if line < visibleFrom or line > visibleTo: return rect = self.GetLineRect(line) rect.x, rect.y = self.CalcScrolledPosition(rect.x, rect.y) self.RefreshRect(rect) def RefreshLines(self, lineFrom, lineTo): """ Redraws a range of lines in L{UltimateListCtrl}. :param `lineFrom`: an integer representing the first line to refresh; :param `lineTo`: an integer representing the last line to refresh. """ if self.InReportView(): visibleFrom, visibleTo = self.GetVisibleLinesRange() if lineFrom < visibleFrom: lineFrom = visibleFrom if lineTo > visibleTo: lineTo = visibleTo rect = wx.Rect() rect.x = 0 rect.y = self.GetLineY(lineFrom) rect.width = self.GetClientSize().x rect.height = self.GetLineY(lineTo) - rect.y + self.GetLineHeight(lineTo) rect.x, rect.y = self.CalcScrolledPosition(rect.x, rect.y) self.RefreshRect(rect) else: # !report # TODO: this should be optimized... for line in xrange(lineFrom, lineTo+1): self.RefreshLine(line) def RefreshAfter(self, lineFrom): """ Redraws all the lines after the input one. :param `lineFrom`: an integer representing the first line to refresh. """ if self.InReportView(): visibleFrom, visibleTo = self.GetVisibleLinesRange() if lineFrom < visibleFrom: lineFrom = visibleFrom elif lineFrom > visibleTo: return rect = wx.Rect() rect.x = 0 rect.y = self.GetLineY(lineFrom) rect.x, rect.y = self.CalcScrolledPosition(rect.x, rect.y) size = self.GetClientSize() rect.width = size.x # refresh till the bottom of the window rect.height = size.y - rect.y self.RefreshRect(rect) else: # !report # TODO: how to do it more efficiently? self._dirty = True def RefreshSelected(self): """ Redraws the selected lines. """ if self.IsEmpty(): return if self.InReportView(): fromm, to = self.GetVisibleLinesRange() else: # !virtual fromm = 0 to = self.GetItemCount() - 1 if self.HasCurrent() and self._current >= fromm and self._current <= to: self.RefreshLine(self._current) for line in xrange(fromm, to+1): # NB: the test works as expected even if self._current == -1 if line != self._current and self.IsHighlighted(line): self.RefreshLine(line) def HideWindows(self): """ Hides the windows associated to the items. Used internally. """ for child in self._itemWithWindow: wnd = child.GetWindow() if wnd: wnd.Hide() def OnPaint(self, event): """ Handles the ``wx.EVT_PAINT`` event for L{UltimateListMainWindow}. :param `event`: a `wx.PaintEvent` event to be processed. """ # Note: a wxPaintDC must be constructed even if no drawing is # done (a Windows requirement). dc = wx.BufferedPaintDC(self) dc.SetBackgroundMode(wx.TRANSPARENT) self.PrepareDC(dc) dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.SetPen(wx.TRANSPARENT_PEN) dc.Clear() self.TileBackground(dc) self.PaintWaterMark(dc) if self.IsEmpty(): # nothing to draw or not the moment to draw it return if self._dirty: # delay the repainting until we calculate all the items positions self.RecalculatePositions(False) useVista, useGradient = self._vistaselection, self._usegradients dev_x, dev_y = self.CalcScrolledPosition(0, 0) dc.SetFont(self.GetFont()) if self.InReportView(): visibleFrom, visibleTo = self.GetVisibleLinesRange() # mrcs: draw additional items if visibleFrom > 0: visibleFrom -= 1 if visibleTo < self.GetItemCount() - 1: visibleTo += 1 xOrig = dc.LogicalToDeviceX(0) yOrig = dc.LogicalToDeviceY(0) # tell the caller cache to cache the data if self.IsVirtual(): evCache = UltimateListEvent(wxEVT_COMMAND_LIST_CACHE_HINT, self.GetParent().GetId()) evCache.SetEventObject(self.GetParent()) evCache.m_oldItemIndex = visibleFrom evCache.m_itemIndex = visibleTo self.GetParent().GetEventHandler().ProcessEvent(evCache) no_highlight = self.HasAGWFlag(ULC_NO_HIGHLIGHT) for line in xrange(visibleFrom, visibleTo+1): rectLine = self.GetLineRect(line) if not self.IsExposed(rectLine.x + xOrig, rectLine.y + yOrig, rectLine.width, rectLine.height): # don't redraw unaffected lines to avoid flicker continue theLine = self.GetLine(line) enabled = theLine.GetItem(0, CreateListItem(line, 0)).IsEnabled() oldPN, oldBR = dc.GetPen(), dc.GetBrush() theLine.DrawInReportMode(dc, line, rectLine, self.GetLineHighlightRect(line), self.IsHighlighted(line) and not no_highlight, line==self._current, enabled, oldPN, oldBR) if self.HasAGWFlag(ULC_HRULES): pen = wx.Pen(self.GetRuleColour(), 1, wx.SOLID) clientSize = self.GetClientSize() # Don't draw the first one start = (visibleFrom > 0 and [visibleFrom] or [1])[0] dc.SetPen(pen) dc.SetBrush(wx.TRANSPARENT_BRUSH) for i in xrange(start, visibleTo+1): lineY = self.GetLineY(i) dc.DrawLine(0 - dev_x, lineY, clientSize.x - dev_x, lineY) # Draw last horizontal rule if visibleTo == self.GetItemCount() - 1: lineY = self.GetLineY(visibleTo) + self.GetLineHeight(visibleTo) dc.SetPen(pen) dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.DrawLine(0 - dev_x, lineY, clientSize.x - dev_x , lineY) # Draw vertical rules if required if self.HasAGWFlag(ULC_VRULES) and not self.IsEmpty(): pen = wx.Pen(self.GetRuleColour(), 1, wx.SOLID) firstItemRect = self.GetItemRect(visibleFrom) lastItemRect = self.GetItemRect(visibleTo) x = firstItemRect.GetX() dc.SetPen(pen) dc.SetBrush(wx.TRANSPARENT_BRUSH) for col in xrange(self.GetColumnCount()): if not self.IsColumnShown(col): continue colWidth = self.GetColumnWidth(col) x += colWidth x_pos = x - dev_x if col < self.GetColumnCount()-1: x_pos -= 2 dc.DrawLine(x_pos, firstItemRect.GetY() - 1 - dev_y, x_pos, lastItemRect.GetBottom() + 1 - dev_y) else: # !report for i in xrange(self.GetItemCount()): self.GetLine(i).Draw(i, dc) if wx.Platform not in ["__WXMAC__", "__WXGTK__"]: # Don't draw rect outline under Mac at all. # Draw it elsewhere on GTK if self.HasCurrent(): if self._hasFocus and not self.HasAGWFlag(ULC_NO_HIGHLIGHT) and not useVista and not useGradient \ and not self.HasAGWFlag(ULC_BORDER_SELECT) and not self.HasAGWFlag(ULC_NO_FULL_ROW_SELECT): dc.SetPen(wx.BLACK_PEN) dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.DrawRectangleRect(self.GetLineHighlightRect(self._current)) def OnEraseBackground(self, event): """ Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{UltimateListMainWindow}. :param `event`: a `wx.EraseEvent` event to be processed. :note: This method is intentionally empty to reduce flicker. """ pass def TileBackground(self, dc): """ Tiles the background image to fill all the available area. :param `dc`: an instance of `wx.DC`. :todo: Support background images also in stretch and centered modes. """ if not self._backgroundImage: return if self._imageStretchStyle != _StyleTile: # Can we actually do something here (or in OnPaint()) To Handle # background images that are stretchable or always centered? # I tried but I get enormous flickering... return sz = self.GetClientSize() w = self._backgroundImage.GetWidth() h = self._backgroundImage.GetHeight() x = 0 while x < sz.width: y = 0 while y < sz.height: dc.DrawBitmap(self._backgroundImage, x, y, True) y = y + h x = x + w def PaintWaterMark(self, dc): """ Draws a watermark at the bottom right of L{UltimateListCtrl}. :param `dc`: an instance of `wx.DC`. :todo: Better support for this is needed. """ if not self._waterMark: return width, height = self.CalcUnscrolledPosition(*self.GetClientSize()) bitmapW = self._waterMark.GetWidth() bitmapH = self._waterMark.GetHeight() x = width - bitmapW - 5 y = height - bitmapH - 5 dc.DrawBitmap(self._waterMark, x, y, True) def HighlightAll(self, on=True): """ Highlights/unhighlights all the lines in L{UltimateListCtrl}. :param `on`: ``True`` to highlight all the lines, ``False`` to unhighlight them. """ if self.IsSingleSel(): if on: raise Exception("can't do this in a single sel control") # we just have one item to turn off if self.HasCurrent() and self.IsHighlighted(self._current): self.HighlightLine(self._current, False) self.RefreshLine(self._current) else: # multi sel if not self.IsEmpty(): self.HighlightLines(0, self.GetItemCount() - 1, on) def OnChildFocus(self, event): """ Handles the ``wx.EVT_CHILD_FOCUS`` event for L{UltimateListMainWindow}. :param `event`: a `wx.ChildFocusEvent` event to be processed. :note: This method is intentionally empty to prevent the default handler in `wx.PyScrolledWindow` from needlessly scrolling the window when the edit control is dismissed. """ # Do nothing here. This prevents the default handler in wx.PyScrolledWindow # from needlessly scrolling the window when the edit control is # dismissed. See ticket #9563. pass def SendNotify(self, line, command, point=wx.DefaultPosition): """ Actually sends a L{UltimateListEvent}. :param `line`: an instance of L{UltimateListLineData}; :param `command`: the event type to send; :param `point`: an instance of `wx.Point`. """ bRet = True le = UltimateListEvent(command, self.GetParent().GetId()) le.SetEventObject(self.GetParent()) le.m_itemIndex = line # set only for events which have position if point != wx.DefaultPosition: le.m_pointDrag = point # don't try to get the line info for virtual list controls: the main # program has it anyhow and if we did it would result in accessing all # the lines, even those which are not visible now and this is precisely # what we're trying to avoid if not self.IsVirtual(): if line != -1: self.GetLine(line).GetItem(0, le.m_item) #else: this happens for wxEVT_COMMAND_LIST_ITEM_FOCUSED event #else: there may be no more such item self.GetParent().GetEventHandler().ProcessEvent(le) bRet = le.IsAllowed() return bRet def ChangeCurrent(self, current): """ Changes the current line to the specified one. :param `current`: an integer specifying the index of the current line. """ self._current = current # as the current item changed, we shouldn't start editing it when the # "slow click" timer expires as the click happened on another item if self._renameTimer.IsRunning(): self._renameTimer.Stop() self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_FOCUSED) def EditLabel(self, item): """ Starts editing an item label. :param `item`: an instance of L{UltimateListItem}. """ if item < 0 or item >= self.GetItemCount(): raise Exception("wrong index in UltimateListCtrl.EditLabel()") le = UltimateListEvent(wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT, self.GetParent().GetId()) le.SetEventObject(self.GetParent()) le.m_itemIndex = item data = self.GetLine(item) le.m_item = data.GetItem(0, le.m_item) self._textctrl = UltimateListTextCtrl(self, item) if self.GetParent().GetEventHandler().ProcessEvent(le) and not le.IsAllowed(): # vetoed by user code return # We have to call this here because the label in question might just have # been added and no screen update taken place. if self._dirty: wx.SafeYield() # Pending events dispatched by wx.SafeYield might have changed the item # count if item >= self.GetItemCount(): return None # modified self._textctrl.SetFocus() return self._textctrl def OnRenameTimer(self): """ The timer for renaming has expired. Start editing. """ if not self.HasCurrent(): raise Exception("unexpected rename timer") self.EditLabel(self._current) def OnRenameAccept(self, itemEdit, value): """ Called by L{UltimateListTextCtrl}, to accept the changes and to send the ``EVT_LIST_END_LABEL_EDIT`` event. :param `itemEdit`: an instance of L{UltimateListItem}; :param `value`: the new value of the item label. """ le = UltimateListEvent(wxEVT_COMMAND_LIST_END_LABEL_EDIT, self.GetParent().GetId()) le.SetEventObject(self.GetParent()) le.m_itemIndex = itemEdit data = self.GetLine(itemEdit) le.m_item = data.GetItem(0, le.m_item) le.m_item._text = value return not self.GetParent().GetEventHandler().ProcessEvent(le) or le.IsAllowed() def OnRenameCancelled(self, itemEdit): """ Called by L{UltimateListTextCtrl}, to cancel the changes and to send the ``EVT_LIST_END_LABEL_EDIT`` event. :param `item`: an instance of L{UltimateListItem}. """ # let owner know that the edit was cancelled le = UltimateListEvent(wxEVT_COMMAND_LIST_END_LABEL_EDIT, self.GetParent().GetId()) le.SetEditCanceled(True) le.SetEventObject(self.GetParent()) le.m_itemIndex = itemEdit data = self.GetLine(itemEdit) le.m_item = data.GetItem(0, le.m_item) self.GetEventHandler().ProcessEvent(le) def OnMouse(self, event): """ Handles the ``wx.EVT_MOUSE_EVENTS`` event for L{UltimateListMainWindow}. :param `event`: a `wx.MouseEvent` event to be processed. """ if wx.Platform == "__WXMAC__": # On wxMac we can't depend on the EVT_KILL_FOCUS event to properly # shutdown the edit control when the mouse is clicked elsewhere on the # listctrl because the order of events is different (or something like # that,) so explicitly end the edit if it is active. if event.LeftDown() and self._textctrl: self._textctrl.AcceptChanges() self._textctrl.Finish() if event.LeftDown(): self.SetFocusIgnoringChildren() event.SetEventObject(self.GetParent()) if self.GetParent().GetEventHandler().ProcessEvent(event) : return if event.GetEventType() == wx.wxEVT_MOUSEWHEEL: # let the base handle mouse wheel events. self.Refresh() event.Skip() return if not self.HasCurrent() or self.IsEmpty(): if event.RightDown(): self.SendNotify(-1, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, event.GetPosition()) evtCtx = wx.ContextMenuEvent(wx.EVT_CONTEXT_MENU, self.GetParent().GetId(), self.ClientToScreen(event.GetPosition())) evtCtx.SetEventObject(self.GetParent()) self.GetParent().GetEventHandler().ProcessEvent(evtCtx) return if self._dirty: return if not (event.Dragging() or event.ButtonDown() or event.LeftUp() or \ event.ButtonDClick() or event.Moving() or event.RightUp()): return x = event.GetX() y = event.GetY() x, y = self.CalcUnscrolledPosition(x, y) # where did we hit it (if we did)? hitResult = 0 newItem = None count = self.GetItemCount() if self.InReportView(): if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): current = y/self.GetLineHeight() if current < count: newItem, hitResult = self.HitTestLine(current, x, y) else: return else: for current in xrange(count): newItem, hitResult = self.HitTestLine(current, x, y) if hitResult: break else: # TODO: optimize it too! this is less simple than for report view but # enumerating all items is still not a way to do it!! for current in xrange(count): newItem, hitResult = self.HitTestLine(current, x, y) if hitResult: break theItem = None if not self.IsVirtual(): theItem = CreateListItem(current, 0) theItem = self.GetItem(theItem) if event.GetEventType() == wx.wxEVT_MOTION and not event.Dragging(): if current >= 0 and current < count and self.HasAGWFlag(ULC_TRACK_SELECT) and not self._hoverTimer.IsRunning(): self._hoverItem = current self._hoverTimer.Start(HOVER_TIME, wx.TIMER_ONE_SHOT) if newItem and newItem.IsHyperText() and (hitResult & ULC_HITTEST_ONITEMLABEL) and theItem and theItem.IsEnabled(): self.SetCursor(wx.StockCursor(wx.CURSOR_HAND)) self._isonhyperlink = True else: if self._isonhyperlink: self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) self._isonhyperlink = False if self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and hitResult: if not self.IsHighlighted(current): self.HighlightAll(False) self.ChangeCurrent(current) self.ReverseHighlight(self._current) if self.HasAGWFlag(ULC_SHOW_TOOLTIPS): if newItem and hitResult & ULC_HITTEST_ONITEM: if (newItem._itemId, newItem._col) in self._shortItems: text = newItem.GetText() if self.GetToolTip() and self.GetToolTip().GetTip() != text: self.SetToolTipString(text) else: self.SetToolTipString("") else: self.SetToolTipString("") if self.HasAGWFlag(ULC_HOT_TRACKING): if hitResult: if self._oldHotCurrent != current: if self._oldHotCurrent is not None: self.RefreshLine(self._oldHotCurrent) self._newHotCurrent = current self.RefreshLine(self._newHotCurrent) self._oldHotCurrent = current event.Skip() return if event.Dragging(): if not self._isDragging: if self._lineLastClicked == -1 or not hitResult or not theItem or not theItem.IsEnabled(): return if self._dragCount == 0: # we have to report the raw, physical coords as we want to be # able to call HitTest(event.m_pointDrag) from the user code to # get the item being dragged self._dragStart = event.GetPosition() self._dragCount += 1 if self._dragCount != 3: return command = (event.RightIsDown() and [wxEVT_COMMAND_LIST_BEGIN_RDRAG] or [wxEVT_COMMAND_LIST_BEGIN_DRAG])[0] le = UltimateListEvent(command, self.GetParent().GetId()) le.SetEventObject(self.GetParent()) le.m_itemIndex = self._lineLastClicked le.m_pointDrag = self._dragStart self.GetParent().GetEventHandler().ProcessEvent(le) # we're going to drag this item self._isDragging = True self._dragItem = current # remember the old cursor because we will change it while # dragging self._oldCursor = self._cursor self.SetCursor(self._dragCursor) else: if current != self._dropTarget: self.SetCursor(self._dragCursor) # unhighlight the previous drop target if self._dropTarget is not None: self.RefreshLine(self._dropTarget) move = current if self._dropTarget: move = (current > self._dropTarget and [current+1] or [current-1])[0] self._dropTarget = current self.MoveToItem(move) else: if self._dragItem == current: self.SetCursor(wx.StockCursor(wx.CURSOR_NO_ENTRY)) if self.HasAGWFlag(ULC_REPORT) and self._dragItem != current: self.DrawDnDArrow() return else: self._dragCount = 0 if theItem and not theItem.IsEnabled(): self.DragFinish(event) event.Skip() return if not hitResult: # outside of any item if event.RightDown(): self.SendNotify(-1, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, event.GetPosition()) evtCtx = wx.ContextMenuEvent(wx.EVT_CONTEXT_MENU, self.GetParent().GetId(), self.ClientToScreen(event.GetPosition())) evtCtx.SetEventObject(self.GetParent()) self.GetParent().GetEventHandler().ProcessEvent(evtCtx) else: self.HighlightAll(False) self.DragFinish(event) return forceClick = False if event.ButtonDClick(): if self._renameTimer.IsRunning(): self._renameTimer.Stop() self._lastOnSame = False if current == self._lineLastClicked: self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_ACTIVATED) if newItem and newItem.GetKind() in [1, 2] and (hitResult & ULC_HITTEST_ONITEMCHECK): self.CheckItem(newItem, not self.IsItemChecked(newItem)) return else: # The first click was on another item, so don't interpret this as # a double click, but as a simple click instead forceClick = True if event.LeftUp(): if self.DragFinish(event): return if self._lineSelectSingleOnUp != - 1: # select single line self.HighlightAll(False) self.ReverseHighlight(self._lineSelectSingleOnUp) if self._lastOnSame: if (current == self._current) and (hitResult == ULC_HITTEST_ONITEMLABEL) and self.HasAGWFlag(ULC_EDIT_LABELS): if not self.InReportView() or self.GetLineLabelRect(current).Contains((x, y)): # This wx.SYS_DCLICK_MSEC is not yet wrapped in wxPython... # dclick = wx.SystemSettings.GetMetric(wx.SYS_DCLICK_MSEC) # m_renameTimer->Start(dclick > 0 ? dclick : 250, True) self._renameTimer.Start(250, True) self._lastOnSame = False self._lineSelectSingleOnUp = -1 elif event.RightUp(): if self.DragFinish(event): return else: # This is necessary, because after a DnD operation in # from and to ourself, the up event is swallowed by the # DnD code. So on next non-up event (which means here and # now) self._lineSelectSingleOnUp should be reset. self._lineSelectSingleOnUp = -1 if event.RightDown(): if self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, event.GetPosition()): self._lineBeforeLastClicked = self._lineLastClicked self._lineLastClicked = current # If the item is already selected, do not update the selection. # Multi-selections should not be cleared if a selected item is clicked. if not self.IsHighlighted(current): self.HighlightAll(False) self.ChangeCurrent(current) self.ReverseHighlight(self._current) # Allow generation of context menu event event.Skip() elif event.MiddleDown(): self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK) elif event.LeftDown() or forceClick: self._lineBeforeLastClicked = self._lineLastClicked self._lineLastClicked = current oldCurrent = self._current oldWasSelected = self.IsHighlighted(self._current) cmdModifierDown = event.CmdDown() if self.IsSingleSel() or not (cmdModifierDown or event.ShiftDown()): if self.IsSingleSel() or not self.IsHighlighted(current): self.HighlightAll(False) self.ChangeCurrent(current) self.ReverseHighlight(self._current) else: # multi sel & current is highlighted & no mod keys self._lineSelectSingleOnUp = current self.ChangeCurrent(current) # change focus else: # multi sel & either ctrl or shift is down if cmdModifierDown: self.ChangeCurrent(current) self.ReverseHighlight(self._current) elif event.ShiftDown(): self.ChangeCurrent(current) lineFrom, lineTo = oldCurrent, current if lineTo < lineFrom: lineTo = lineFrom lineFrom = self._current self.HighlightLines(lineFrom, lineTo) else: # !ctrl, !shift # test in the enclosing if should make it impossible raise Exception("how did we get here?") if newItem: if event.LeftDown(): if newItem.GetKind() in [1, 2] and (hitResult & ULC_HITTEST_ONITEMCHECK): self.CheckItem(newItem, not self.IsItemChecked(newItem)) if newItem.IsHyperText(): self.SetItemVisited(newItem, True) self.HandleHyperLink(newItem) if self._current != oldCurrent: self.RefreshLine(oldCurrent) # forceClick is only set if the previous click was on another item self._lastOnSame = not forceClick and (self._current == oldCurrent) and oldWasSelected if self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and self.HasAGWFlag(ULC_STICKY_NOSELEVENT) and self.HasAGWFlag(ULC_SEND_LEFTCLICK): self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_LEFT_CLICK, event.GetPosition()) def DrawDnDArrow(self): """ Draws a drag and drop visual representation of an arrow. """ dc = wx.ClientDC(self) lineY = self.GetLineY(self._dropTarget) width = self.GetTotalWidth() dc.SetPen(wx.Pen(wx.BLACK, 2)) x, y = self.CalcScrolledPosition(HEADER_OFFSET_X, lineY+2*HEADER_OFFSET_Y) tri1 = [wx.Point(x+1, y-2), wx.Point(x+1, y+4), wx.Point(x+4, y+1)] tri2 = [wx.Point(x+width-1, y-2), wx.Point(x+width-1, y+4), wx.Point(x+width-4, y+1)] dc.DrawPolygon(tri1) dc.DrawPolygon(tri2) dc.DrawLine(x, y+1, width, y+1) def DragFinish(self, event): """ A drag and drop operation has just finished. :param `event`: a `wx.MouseEvent` event to be processed. """ if not self._isDragging: return False self._isDragging = False self._dragCount = 0 self._dragItem = None self.SetCursor(self._oldCursor) self.Refresh() le = UltimateListEvent(wxEVT_COMMAND_LIST_END_DRAG, self.GetParent().GetId()) le.SetEventObject(self.GetParent()) le.m_itemIndex = self._dropTarget le.m_pointDrag = event.GetPosition() self.GetParent().GetEventHandler().ProcessEvent(le) return True def HandleHyperLink(self, item): """ Handles the hyperlink items, sending the ``EVT_LIST_ITEM_HYPERLINK`` event. :param `item`: an instance of L{UltimateListItem}. """ if self.IsItemHyperText(item): self.SendNotify(item._itemId, wxEVT_COMMAND_LIST_ITEM_HYPERLINK) def OnHoverTimer(self, event): """ Handles the ``wx.EVT_TIMER`` event for L{UltimateListMainWindow}. :param `event`: a `wx.TimerEvent` event to be processed. """ x, y = self.ScreenToClient(wx.GetMousePosition()) x, y = self.CalcUnscrolledPosition(x, y) item, hitResult = self.HitTestLine(self._hoverItem, x, y) if item and item._itemId == self._hoverItem: if not self.IsHighlighted(self._hoverItem): dontNotify = self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and self.HasAGWFlag(ULC_STICKY_NOSELEVENT) if not dontNotify: self.SendNotify(self._hoverItem, wxEVT_COMMAND_LIST_ITEM_SELECTED) self.HighlightAll(False) self.ChangeCurrent(self._hoverItem) self.ReverseHighlight(self._current) def MoveToItem(self, item): """ Scrolls the input item into view. :param `item`: an instance of L{UltimateListItem}. """ if item == -1: return if item >= self.GetItemCount(): item = self.GetItemCount() - 1 rect = self.GetLineRect(item) client_w, client_h = self.GetClientSize() hLine = self.GetLineHeight(item) view_x = SCROLL_UNIT_X*self.GetScrollPos(wx.HORIZONTAL) view_y = hLine*self.GetScrollPos(wx.VERTICAL) if self.InReportView(): # the next we need the range of lines shown it might be different, so # recalculate it self.ResetVisibleLinesRange() if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): if rect.y < view_y: self.Scroll(-1, rect.y/hLine) if rect.y+rect.height+5 > view_y+client_h: self.Scroll(-1, (rect.y+rect.height-client_h+hLine)/hLine) if wx.Platform == "__WXMAC__": # At least on Mac the visible lines value will get reset inside of # Scroll *before* it actually scrolls the window because of the # Update() that happens there, so it will still have the wrong value. # So let's reset it again and wait for it to be recalculated in the # next paint event. I would expect this problem to show up in wxGTK # too but couldn't duplicate it there. Perhaps the order of events # is different... --Robin self.ResetVisibleLinesRange() else: view_y = SCROLL_UNIT_Y*self.GetScrollPos(wx.VERTICAL) start_y, height = rect.y, rect.height if start_y < view_y: while start_y > view_y: start_y -= SCROLL_UNIT_Y self.Scroll(-1, start_y/SCROLL_UNIT_Y) if start_y + height > view_y + client_h: while start_y + height < view_y + client_h: start_y += SCROLL_UNIT_Y self.Scroll(-1, (start_y+height-client_h+SCROLL_UNIT_Y)/SCROLL_UNIT_Y) else: # !report sx = sy = -1 if rect.x-view_x < 5: sx = (rect.x - 5)/SCROLL_UNIT_X if rect.x+rect.width-5 > view_x+client_w: sx = (rect.x + rect.width - client_w + SCROLL_UNIT_X)/SCROLL_UNIT_X if rect.y-view_y < 5: sy = (rect.y - 5)/hLine if rect.y + rect.height - 5 > view_y + client_h: sy = (rect.y + rect.height - client_h + hLine)/hLine self.Scroll(sx, sy) # ---------------------------------------------------------------------------- # keyboard handling # ---------------------------------------------------------------------------- def GetNextActiveItem(self, item, down=True): """ Returns the next active item. Used Internally at present. :param `item`: an instance of L{UltimateListItem}; :param `down`: ``True`` to search downwards for an active item, ``False`` to search upwards. """ count = self.GetItemCount() initialItem = item while 1: if item >= count or item < 0: return initialItem listItem = CreateListItem(item, 0) listItem = self.GetItem(listItem, 0) if listItem.IsEnabled(): return item item = (down and [item+1] or [item-1])[0] def OnArrowChar(self, newCurrent, event): """ Handles the keyboard arrows key events. :param `newCurrent`: an integer specifying the new current item; :param `event`: a `wx.KeyEvent` event to be processed. """ oldCurrent = self._current newCurrent = self.GetNextActiveItem(newCurrent, newCurrent > oldCurrent) # in single selection we just ignore Shift as we can't select several # items anyhow if event.ShiftDown() and not self.IsSingleSel(): self.ChangeCurrent(newCurrent) # refresh the old focus to remove it self.RefreshLine(oldCurrent) # select all the items between the old and the new one if oldCurrent > newCurrent: newCurrent = oldCurrent oldCurrent = self._current self.HighlightLines(oldCurrent, newCurrent) else: # !shift # all previously selected items are unselected unless ctrl is held # in a multi-selection control if not event.ControlDown() or self.IsSingleSel(): self.HighlightAll(False) self.ChangeCurrent(newCurrent) # refresh the old focus to remove it self.RefreshLine(oldCurrent) if not event.ControlDown() or self.IsSingleSel(): self.HighlightLine(self._current, True) self.RefreshLine(self._current) self.MoveToFocus() def OnKeyDown(self, event): """ Handles the ``wx.EVT_KEY_DOWN`` event for L{UltimateListMainWindow}. :param `event`: a `wx.KeyEvent` event to be processed. """ parent = self.GetParent() # we propagate the key event upwards ke = wx.KeyEvent(event.GetEventType()) ke.SetEventObject(parent) if parent.GetEventHandler().ProcessEvent(ke): return event.Skip() def OnKeyUp(self, event): """ Handles the ``wx.EVT_KEY_UP`` event for L{UltimateListMainWindow}. :param `event`: a `wx.KeyEvent` event to be processed. """ parent = self.GetParent() # we propagate the key event upwards ke = wx.KeyEvent(event.GetEventType()) ke.SetEventObject(parent) if parent.GetEventHandler().ProcessEvent(ke): return event.Skip() def OnChar(self, event): """ Handles the ``wx.EVT_CHAR`` event for L{UltimateListMainWindow}. :param `event`: a `wx.KeyEvent` event to be processed. """ parent = self.GetParent() # we send a list_key event up if self.HasCurrent(): le = UltimateListEvent(wxEVT_COMMAND_LIST_KEY_DOWN, self.GetParent().GetId()) le.m_itemIndex = self._current le.m_item = self.GetLine(self._current).GetItem(0, le.m_item) le.m_code = event.GetKeyCode() le.SetEventObject(parent) parent.GetEventHandler().ProcessEvent(le) keyCode = event.GetKeyCode() if keyCode not in [wx.WXK_UP, wx.WXK_DOWN, wx.WXK_RIGHT, wx.WXK_LEFT, \ wx.WXK_PAGEUP, wx.WXK_PAGEDOWN, wx.WXK_END, wx.WXK_HOME]: # propagate the char event upwards ke = wx.KeyEvent(event.GetEventType()) ke.SetEventObject(parent) if parent.GetEventHandler().ProcessEvent(ke): return if event.GetKeyCode() == wx.WXK_TAB: nevent = wx.NavigationKeyEvent() nevent.SetWindowChange(event.ControlDown()) nevent.SetDirection(not event.ShiftDown()) nevent.SetEventObject(self.GetParent().GetParent()) nevent.SetCurrentFocus(self._parent) if self.GetParent().GetParent().GetEventHandler().ProcessEvent(nevent): return # no item . nothing to do if not self.HasCurrent(): event.Skip() return keyCode = event.GetKeyCode() if keyCode == wx.WXK_UP: if self._current > 0: self.OnArrowChar(self._current - 1, event) if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): self._dirty = True elif keyCode == wx.WXK_DOWN: if self._current < self.GetItemCount() - 1: self.OnArrowChar(self._current + 1, event) if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): self._dirty = True elif keyCode == wx.WXK_END: if not self.IsEmpty(): self.OnArrowChar(self.GetItemCount() - 1, event) self._dirty = True elif keyCode == wx.WXK_HOME: if not self.IsEmpty(): self.OnArrowChar(0, event) self._dirty = True elif keyCode == wx.WXK_PRIOR: steps = (self.InReportView() and [self._linesPerPage - 1] or [self._current % self._linesPerPage])[0] index = self._current - steps if index < 0: index = 0 self.OnArrowChar(index, event) self._dirty = True elif keyCode == wx.WXK_NEXT: steps = (self.InReportView() and [self._linesPerPage - 1] or [self._linesPerPage - (self._current % self._linesPerPage) - 1])[0] index = self._current + steps count = self.GetItemCount() if index >= count: index = count - 1 self.OnArrowChar(index, event) self._dirty = True elif keyCode == wx.WXK_LEFT: if not self.InReportView(): index = self._current - self._linesPerPage if index < 0: index = 0 self.OnArrowChar(index, event) elif keyCode == wx.WXK_RIGHT: if not self.InReportView(): index = self._current + self._linesPerPage count = self.GetItemCount() if index >= count: index = count - 1 self.OnArrowChar(index, event) elif keyCode == wx.WXK_SPACE: if self.IsSingleSel(): if event.ControlDown(): self.ReverseHighlight(self._current) else: # normal space press self.SendNotify(self._current, wxEVT_COMMAND_LIST_ITEM_ACTIVATED) else: # select it in ReverseHighlight() below if unselected self.ReverseHighlight(self._current) elif keyCode in [wx.WXK_RETURN, wx.WXK_EXECUTE, wx.WXK_NUMPAD_ENTER]: self.SendNotify(self._current, wxEVT_COMMAND_LIST_ITEM_ACTIVATED) else: event.Skip() # ---------------------------------------------------------------------------- # focus handling # ---------------------------------------------------------------------------- def OnSetFocus(self, event): """ Handles the ``wx.EVT_SET_FOCUS`` event for L{UltimateListMainWindow}. :param `event`: a `wx.FocusEvent` event to be processed. """ if self.GetParent(): event = wx.FocusEvent(wx.wxEVT_SET_FOCUS, self.GetParent().GetId()) event.SetEventObject(self.GetParent()) if self.GetParent().GetEventHandler().ProcessEvent(event): return # wxGTK sends us EVT_SET_FOCUS events even if we had never got # EVT_KILL_FOCUS before which means that we finish by redrawing the items # which are already drawn correctly resulting in horrible flicker - avoid # it if not self._hasFocus: self._hasFocus = True self.Refresh() def OnKillFocus(self, event): """ Handles the ``wx.EVT_KILL_FOCUS`` event for L{UltimateListMainWindow}. :param `event`: a `wx.FocusEvent` event to be processed. """ if self.GetParent(): event = wx.FocusEvent(wx.wxEVT_KILL_FOCUS, self.GetParent().GetId()) event.SetEventObject(self.GetParent()) if self.GetParent().GetEventHandler().ProcessEvent(event): return self._hasFocus = False self.Refresh() def DrawImage(self, index, dc, x, y, enabled): """ Draws one of the item images. :param `index`: the index of the image inside the image list; :param `dc`: an instance of `wx.DC`; :param `x`: the x position where to draw the image; :param `y`: the y position where to draw the image; :param `enabled`: ``True`` if the item is enabled, ``False`` if it is disabled. """ if self.HasAGWFlag(ULC_ICON) and self._normal_image_list: imgList = (enabled and [self._normal_image_list] or [self._normal_grayed_image_list])[0] imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT) elif self.HasAGWFlag(ULC_SMALL_ICON) and self._small_image_list: imgList = (enabled and [self._small_image_list] or [self._small_grayed_image_list])[0] imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT) elif self.HasAGWFlag(ULC_LIST) and self._small_image_list: imgList = (enabled and [self._small_image_list] or [self._small_grayed_image_list])[0] imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT) elif self.InReportView() and self._small_image_list: imgList = (enabled and [self._small_image_list] or [self._small_grayed_image_list])[0] imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT) def DrawCheckbox(self, dc, x, y, kind, checked, enabled): """ Draws the item checkbox/radiobutton image. :param `dc`: an instance of `wx.DC`; :param `x`: the x position where to draw the image; :param `y`: the y position where to draw the image; :param `kind`: may be one of the following integers: =============== ========================== Item Kind Description =============== ========================== 0 A normal item 1 A checkbox-like item 2 A radiobutton-type item =============== ========================== :param `checked`: ``True`` if the item is checked, ``False`` otherwise; :param `enabled`: ``True`` if the item is enabled, ``False`` if it is disabled. """ imgList = (enabled and [self._image_list_check] or [self._grayed_check_list])[0] if kind == 1: # checkbox index = (checked and [0] or [1])[0] else: # radiobutton index = (checked and [2] or [3])[0] imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT) def GetCheckboxImageSize(self): """ Returns the checkbox/radiobutton image size. """ bmp = self._image_list_check.GetBitmap(0) return bmp.GetWidth(), bmp.GetHeight() def GetImageSize(self, index): """ Returns the image size for the item. :param `index`: the image index. """ width = height = 0 if self.HasAGWFlag(ULC_ICON) and self._normal_image_list: for indx in index: w, h = self._normal_image_list.GetSize(indx) width += w + MARGIN_BETWEEN_TEXT_AND_ICON height = max(height, h) elif self.HasAGWFlag(ULC_SMALL_ICON) and self._small_image_list: for indx in index: w, h = self._small_image_list.GetSize(indx) width += w + MARGIN_BETWEEN_TEXT_AND_ICON height = max(height, h) elif self.HasAGWFlag(ULC_LIST) and self._small_image_list: for indx in index: w, h = self._small_image_list.GetSize(indx) width += w + MARGIN_BETWEEN_TEXT_AND_ICON height = max(height, h) elif self.InReportView() and self._small_image_list: for indx in index: w, h = self._small_image_list.GetSize(indx) width += w + MARGIN_BETWEEN_TEXT_AND_ICON height = max(height, h) return width, height def GetTextLength(self, s): """ Returns the text width for the input string. :param `s`: the string to measure. """ dc = wx.ClientDC(self) dc.SetFont(self.GetFont()) lw, lh, dummy = dc.GetMultiLineTextExtent(s) return lw + AUTOSIZE_COL_MARGIN def SetImageList(self, imageList, which): """ Sets the image list associated with the control. :param `imageList`: an instance of `wx.ImageList` or an instance of L{PyImageList}; :param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``, ``wx.IMAGE_LIST_STATE`` (the last is unimplemented). :note: Using L{PyImageList} enables you to have images of different size inside the image list. In your derived class, instead of doing this:: imageList = wx.ImageList(16, 16) imageList.Add(someBitmap) self.SetImageList(imageList, wx.IMAGE_LIST_SMALL) You should do this:: imageList = PyImageList(16, 16) imageList.Add(someBitmap) self.SetImageList(imageList, wx.IMAGE_LIST_SMALL) """ self._dirty = True if isinstance(imageList, PyImageList): # We have a custom PyImageList with variable image sizes cls = PyImageList else: cls = wx.ImageList # calc the spacing from the icon size width = height = 0 if imageList and imageList.GetImageCount(): width, height = imageList.GetSize(0) if which == wx.IMAGE_LIST_NORMAL: self._normal_image_list = imageList self._normal_grayed_image_list = cls(width, height, True, 0) for ii in xrange(imageList.GetImageCount()): bmp = imageList.GetBitmap(ii) newbmp = MakeDisabledBitmap(bmp) self._normal_grayed_image_list.Add(newbmp) self._normal_spacing = width + 8 if which == wx.IMAGE_LIST_SMALL: self._small_image_list = imageList self._small_spacing = width + 14 self._small_grayed_image_list = cls(width, height, True, 0) for ii in xrange(imageList.GetImageCount()): bmp = imageList.GetBitmap(ii) newbmp = MakeDisabledBitmap(bmp) self._small_grayed_image_list.Add(newbmp) self._lineHeight = 0 # ensure that the line height will be recalc'd self.ResetLineDimensions() def SetImageListCheck(self, sizex, sizey, imglist=None): """ Sets the checkbox/radiobutton image list. :param `sizex`: the width of the bitmaps in the `imglist`; :param `sizey`: the height of the bitmaps in the `imglist`; :param `imglist`: an instance of `wx.ImageList`. """ # Image list to hold disabled versions of each control self._grayed_check_list = wx.ImageList(sizex, sizey, True, 0) if imglist is None: self._image_list_check = wx.ImageList(sizex, sizey) # Get the Checkboxes self._image_list_check.Add(self.GetControlBmp(checkbox=True, checked=True, enabled=True, x=sizex, y=sizey)) self._grayed_check_list.Add(self.GetControlBmp(checkbox=True, checked=True, enabled=False, x=sizex, y=sizey)) self._image_list_check.Add(self.GetControlBmp(checkbox=True, checked=False, enabled=True, x=sizex, y=sizey)) self._grayed_check_list.Add(self.GetControlBmp(checkbox=True, checked=False, enabled=False, x=sizex, y=sizey)) # Get the Radio Buttons self._image_list_check.Add(self.GetControlBmp(checkbox=False, checked=True, enabled=True, x=sizex, y=sizey)) self._grayed_check_list.Add(self.GetControlBmp(checkbox=False, checked=True, enabled=False, x=sizex, y=sizey)) self._image_list_check.Add(self.GetControlBmp(checkbox=False, checked=False, enabled=True, x=sizex, y=sizey)) self._grayed_check_list.Add(self.GetControlBmp(checkbox=False, checked=False, enabled=False, x=sizex, y=sizey)) else: sizex, sizey = imglist.GetSize(0) self._image_list_check = imglist for ii in xrange(self._image_list_check.GetImageCount()): bmp = self._image_list_check.GetBitmap(ii) newbmp = MakeDisabledBitmap(bmp) self._grayed_check_list.Add(newbmp) self._dirty = True if imglist: self.RecalculatePositions() def GetControlBmp(self, checkbox=True, checked=False, enabled=True, x=16, y=16): """ Returns a native looking checkbox or radio button bitmap. :param `checkbox`: ``True`` to get a checkbox image, ``False`` for a radiobutton one; :param `checked`: ``True`` if the control is marked, ``False`` if it is not; :param `enabled`: ``True`` if the control is enabled, ``False`` if it is not; :param `x`: the width of the bitmap; :param `y`: the height of the bitmap. """ bmp = wx.EmptyBitmap(x, y) mdc = wx.MemoryDC(bmp) dc = wx.GCDC(mdc) render = wx.RendererNative.Get() if checked: flag = wx.CONTROL_CHECKED else: flag = 0 if not enabled: flag |= wx.CONTROL_DISABLED if checkbox: render.DrawCheckBox(self, mdc, (0, 0, x, y), flag) else: render.DrawRadioButton(self, mdc, (0, 0, x, y), flag) mdc.SelectObject(wx.NullBitmap) return bmp def SetItemSpacing(self, spacing, isSmall=False): """ Sets the spacing between item texts and icons. :param `spacing`: the spacing between item texts and icons, in pixels; :param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list, ``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list. """ self._dirty = True if isSmall: self._small_spacing = spacing else: self._normal_spacing = spacing def GetItemSpacing(self, isSmall=False): """ Returns the spacing between item texts and icons, in pixels. :param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list, ``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list. """ return (isSmall and [self._small_spacing] or [self._normal_spacing])[0] # ---------------------------------------------------------------------------- # columns # ---------------------------------------------------------------------------- def SetColumn(self, col, item): """ Sets information about this column. :param `col`: an integer specifying the column index; :param `item`: an instance of L{UltimateListItem}. """ column = self._columns[col] if item._width == ULC_AUTOSIZE_USEHEADER: item._width = self.GetTextLength(item._text) column.SetItem(item) headerWin = self.GetListCtrl()._headerWin if headerWin: headerWin._dirty = True self._dirty = True # invalidate it as it has to be recalculated self._headerWidth = 0 def SetColumnWidth(self, col, width): """ Sets the column width. :param `width`: can be a width in pixels or ``wx.LIST_AUTOSIZE`` (-1) or ``wx.LIST_AUTOSIZE_USEHEADER`` (-2) or ``ULC_AUTOSIZE_FILL`` (-3). ``wx.LIST_AUTOSIZE`` will resize the column to the length of its longest item. ``wx.LIST_AUTOSIZE_USEHEADER`` will resize the column to the length of the header (Win32) or 80 pixels (other platforms). ``ULC_AUTOSIZE_FILL`` will resize the column fill the remaining width of the window. :note: In small or normal icon view, col must be -1, and the column width is set for all columns. """ if col < 0: raise Exception("invalid column index") if not self.InReportView() and not self.InTileView() and not self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS): raise Exception("SetColumnWidth() can only be called in report/tile modes or with the ULC_HEADER_IN_ALL_VIEWS flag set.") self._dirty = True headerWin = self.GetListCtrl()._headerWin footerWin = self.GetListCtrl()._footerWin if headerWin: headerWin._dirty = True if footerWin: footerWin._dirty = True column = self._columns[col] count = self.GetItemCount() if width == ULC_AUTOSIZE_FILL: width = self.GetColumnWidth(col) if width == 0: width = WIDTH_COL_DEFAULT self._resizeColumn = col elif width == ULC_AUTOSIZE_USEHEADER: width = self.GetTextLength(column.GetText()) width += 2*EXTRA_WIDTH if column.GetKind() in [1, 2]: ix, iy = self._owner.GetCheckboxImageSize() width += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE # check for column header's image availability images = column.GetImage() for img in images: if self._small_image_list: ix, iy = self._small_image_list.GetSize(img) width += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE elif width == ULC_AUTOSIZE: if self.IsVirtual() or not self.InReportView(): # TODO: determine the max width somehow... width = WIDTH_COL_DEFAULT else: # !virtual maxW = AUTOSIZE_COL_MARGIN # if the cached column width isn't valid then recalculate it if self._aColWidths[col]._bNeedsUpdate: for i in xrange(count): line = self.GetLine(i) itemData = line._items[col] item = UltimateListItem() item = itemData.GetItem(item) itemWidth = self.GetItemWidthWithImage(item) if itemWidth > maxW and not item._overFlow: maxW = itemWidth self._aColWidths[col]._bNeedsUpdate = False self._aColWidths[col]._nMaxWidth = maxW maxW = self._aColWidths[col]._nMaxWidth width = maxW + AUTOSIZE_COL_MARGIN column.SetWidth(width) # invalidate it as it has to be recalculated self._headerWidth = 0 self._footerWidth = 0 if footerWin: footerWin.Refresh() def GetHeaderWidth(self): """ Returns the header window width, in pixels. """ if not self._headerWidth: count = self.GetColumnCount() for col in xrange(count): if not self.IsColumnShown(col): continue self._headerWidth += self.GetColumnWidth(col) if self.HasAGWFlag(ULC_FOOTER): self._footerWidth = self._headerWidth return self._headerWidth def GetColumn(self, col): """ Returns information about this column. :param `col`: an integer specifying the column index. """ item = UltimateListItem() column = self._columns[col] item = column.GetItem(item) return item def GetColumnWidth(self, col): """ Returns the column width for the input column. :param `col`: an integer specifying the column index. """ column = self._columns[col] return column.GetWidth() def GetTotalWidth(self): """ Returns the total width of the columns in L{UltimateListCtrl}. """ width = 0 for column in self._columns: width += column.GetWidth() return width # ---------------------------------------------------------------------------- # item state # ---------------------------------------------------------------------------- def SetItem(self, item): """ Sets information about the item. :param `item`: an instance of L{UltimateListItemData}. """ id = item._itemId if id < 0 or id >= self.GetItemCount(): raise Exception("invalid item index in SetItem") if not self.IsVirtual(): line = self.GetLine(id) line.SetItem(item._col, item) # Set item state if user wants if item._mask & ULC_MASK_STATE: self.SetItemState(item._itemId, item._state, item._state) if self.InReportView(): # update the Max Width Cache if needed width = self.GetItemWidthWithImage(item) if width > self._aColWidths[item._col]._nMaxWidth: self._aColWidths[item._col]._nMaxWidth = width self._aColWidths[item._col]._bNeedsUpdate = True if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): line.ResetDimensions() # update the item on screen if self.InReportView(): rectItem = self.GetItemRect(id) self.RefreshRect(rectItem) def SetItemStateAll(self, state, stateMask): """ Sets the item state flags for all the items. :param `state`: any combination of the following bits: ============================ ========= ============================== State Bits Hex Value Description ============================ ========= ============================== ``ULC_STATE_DONTCARE`` 0x0 Don't care what the state is ``ULC_STATE_DROPHILITED`` 0x1 The item is highlighted to receive a drop event ``ULC_STATE_FOCUSED`` 0x2 The item has the focus ``ULC_STATE_SELECTED`` 0x4 The item is selected ``ULC_STATE_CUT`` 0x8 The item is in the cut state ``ULC_STATE_DISABLED`` 0x10 The item is disabled ``ULC_STATE_FILTERED`` 0x20 The item has been filtered ``ULC_STATE_INUSE`` 0x40 The item is in use ``ULC_STATE_PICKED`` 0x80 The item has been picked ``ULC_STATE_SOURCE`` 0x100 The item is a drag and drop source ============================ ========= ============================== :param `stateMask`: the bitmask for the state flag. :note: The valid state flags are influenced by the value of the state mask. """ if self.IsEmpty(): return # first deal with selection if stateMask & ULC_STATE_SELECTED: # set/clear select state if self.IsVirtual(): # optimized version for virtual listctrl. self._selStore.SelectRange(0, self.GetItemCount() - 1, state==ULC_STATE_SELECTED) self.Refresh() elif state & ULC_STATE_SELECTED: count = self.GetItemCount() for i in xrange(count): self.SetItemState(i, ULC_STATE_SELECTED, ULC_STATE_SELECTED) else: # clear for non virtual (somewhat optimized by using GetNextItem()) i = -1 while 1: i += 1 if self.GetNextItem(i, ULC_NEXT_ALL, ULC_STATE_SELECTED) == -1: break self.SetItemState(i, 0, ULC_STATE_SELECTED) if self.HasCurrent() and state == 0 and stateMask & ULC_STATE_FOCUSED: # unfocus all: only one item can be focussed, so clearing focus for # all items is simply clearing focus of the focussed item. self.SetItemState(self._current, state, stateMask) #(setting focus to all items makes no sense, so it is not handled here.) def SetItemState(self, litem, state, stateMask): """ Sets the item state flags for the input item. :param `litem`: the index of the item; if defaulted to -1, the state flag will be set for all the items; :param `state`: the item state flag; :param `stateMask`: the bitmask for the state flag. :see: L{SetItemStateAll} for a list of valid state flags. """ if litem == -1: self.SetItemStateAll(state, stateMask) return if litem < 0 or litem >= self.GetItemCount(): raise Exception("invalid item index in SetItemState") oldCurrent = self._current item = litem # safe because of the check above # do we need to change the focus? if stateMask & ULC_STATE_FOCUSED: if state & ULC_STATE_FOCUSED: # don't do anything if this item is already focused if item != self._current: self.ChangeCurrent(item) if oldCurrent != - 1: if self.IsSingleSel(): self.HighlightLine(oldCurrent, False) self.RefreshLine(oldCurrent) self.RefreshLine(self._current) else: # unfocus # don't do anything if this item is not focused if item == self._current: self.ResetCurrent() if self.IsSingleSel(): # we must unselect the old current item as well or we # might end up with more than one selected item in a # single selection control self.HighlightLine(oldCurrent, False) self.RefreshLine(oldCurrent) # do we need to change the selection state? if stateMask & ULC_STATE_SELECTED: on = (state & ULC_STATE_SELECTED) != 0 if self.IsSingleSel(): if on: # selecting the item also makes it the focused one in the # single sel mode if self._current != item: self.ChangeCurrent(item) if oldCurrent != - 1: self.HighlightLine(oldCurrent, False) self.RefreshLine(oldCurrent) else: # off # only the current item may be selected anyhow if item != self._current: return if self.HighlightLine(item, on): self.RefreshLine(item) def GetItemState(self, item, stateMask): """ Returns the item state flags for the input item. :param `item`: the index of the item; :param `stateMask`: the bitmask for the state flag. :see: L{SetItemStateAll} for a list of valid state flags. """ if item < 0 or item >= self.GetItemCount(): raise Exception("invalid item index in GetItemState") ret = ULC_STATE_DONTCARE if stateMask & ULC_STATE_FOCUSED: if item == self._current: ret |= ULC_STATE_FOCUSED if stateMask & ULC_STATE_SELECTED: if self.IsHighlighted(item): ret |= ULC_STATE_SELECTED return ret def GetItem(self, item, col=0): """ Returns the information about the input item. :param `item`: an instance of L{UltimateListItem}; :param `col`: the column to which the item belongs to. """ if item._itemId < 0 or item._itemId >= self.GetItemCount(): raise Exception("invalid item index in GetItem") line = self.GetLine(item._itemId) item = line.GetItem(col, item) # Get item state if user wants it if item._mask & ULC_MASK_STATE: item._state = self.GetItemState(item._itemId, ULC_STATE_SELECTED | ULC_STATE_FOCUSED) return item def CheckItem(self, item, checked=True, sendEvent=True): """ Actually checks/uncheks an item, sending (eventually) the two events ``EVT_LIST_ITEM_CHECKING``/``EVT_LIST_ITEM_CHECKED``. :param `item`: an instance of L{UltimateListItem}; :param `checked`: ``True`` to check an item, ``False`` to uncheck it; :param `sendEvent`: ``True`` to send a {UltimateListEvent}, ``False`` otherwise. :note: This method is meaningful only for checkbox-like and radiobutton-like items. """ # Should we raise an error here?!? if item.GetKind() == 0 or not item.IsEnabled(): return if sendEvent: parent = self.GetParent() le = UltimateListEvent(wxEVT_COMMAND_LIST_ITEM_CHECKING, parent.GetId()) le.m_itemIndex = item._itemId le.m_item = item le.SetEventObject(parent) if parent.GetEventHandler().ProcessEvent(le): # Blocked by user return item.Check(checked) self.SetItem(item) self.RefreshLine(item._itemId) if not sendEvent: return le = UltimateListEvent(wxEVT_COMMAND_LIST_ITEM_CHECKED, parent.GetId()) le.m_itemIndex = item._itemId le.m_item = item le.SetEventObject(parent) parent.GetEventHandler().ProcessEvent(le) def AutoCheckChild(self, isChecked, column): """ Checks/unchecks all the items. :param `isChecked`: ``True`` to check the items, ``False`` to uncheck them; :param `column`: the column to which the items belongs to. :note: This method is meaningful only for checkbox-like and radiobutton-like items. """ for indx in xrange(self.GetItemCount()): item = CreateListItem(indx, column) newItem = self.GetItem(item, column) self.CheckItem(newItem, not isChecked, False) def AutoToggleChild(self, column): """ Toggles all the items. :param `column`: the column to which the items belongs to. :note: This method is meaningful only for checkbox-like and radiobutton-like items. """ for indx in xrange(self.GetItemCount()): item = CreateListItem(indx, column) newItem = self.GetItem(item, column) if newItem.GetKind() != 1: continue self.CheckItem(newItem, not item.IsChecked(), False) def IsItemChecked(self, item): """ Returns whether an item is checked or not. :param `item`: an instance of L{UltimateListItem}. """ item = self.GetItem(item, item._col) return item.IsChecked() def IsItemEnabled(self, item): """ Returns whether an item is enabled or not. :param `item`: an instance of L{UltimateListItem}. """ item = self.GetItem(item, item._col) return item.IsEnabled() def EnableItem(self, item, enable=True): """ Enables/disables an item. :param `item`: an instance of L{UltimateListItem}; :param `enable`: ``True`` to enable the item, ``False`` otherwise. """ item = self.GetItem(item, 0) if item.IsEnabled() == enable: return False item.Enable(enable) wnd = item.GetWindow() # Handles the eventual window associated to the item if wnd: wnd.Enable(enable) self.SetItem(item) return True def GetItemKind(self, item): """ Returns the item kind. :param `item`: an instance of L{UltimateListItem}. :see: L{SetItemKind} for a list of valid item kinds. """ item = self.GetItem(item, item._col) return item.GetKind() def SetItemKind(self, item, kind): """ Sets the item kind. :param `item`: an instance of L{UltimateListItem}; :param `kind`: may be one of the following integers: =============== ========================== Item Kind Description =============== ========================== 0 A normal item 1 A checkbox-like item 2 A radiobutton-type item =============== ========================== """ item = self.GetItem(item, item._col) item.SetKind(kind) self.SetItem(item) return True def IsItemHyperText(self, item): """ Returns whether an item is hypertext or not. :param `item`: an instance of L{UltimateListItem}. """ item = self.GetItem(item, item._col) return item.IsHyperText() def SetItemHyperText(self, item, hyper=True): """ Sets whether the item is hypertext or not. :param `item`: an instance of L{UltimateListItem}; :param `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise. """ item = self.GetItem(item, item._col) item.SetHyperText(hyper) self.SetItem(item) return True def GetHyperTextFont(self): """Returns the font used to render an hypertext item.""" return self._hypertextfont def SetHyperTextFont(self, font): """ Sets the font used to render hypertext items. :param `font`: a valid `wx.Font` instance. """ self._hypertextfont = font self._dirty = True def SetHyperTextNewColour(self, colour): """ Sets the colour used to render a non-visited hypertext item. :param `colour`: a valid `wx.Colour` instance. """ self._hypertextnewcolour = colour self._dirty = True def GetHyperTextNewColour(self): """ Returns the colour used to render a non-visited hypertext item. """ return self._hypertextnewcolour def SetHyperTextVisitedColour(self, colour): """ Sets the colour used to render a visited hypertext item. :param `colour`: a valid `wx.Colour` instance. """ self._hypertextvisitedcolour = colour self._dirty = True def GetHyperTextVisitedColour(self): """ Returns the colour used to render a visited hypertext item. """ return self._hypertextvisitedcolour def SetItemVisited(self, item, visited=True): """ Sets whether an hypertext item was visited. :param `item`: an instance of L{UltimateListItem}; :param `visited`: ``True`` to mark an hypertext item as visited, ``False`` otherwise. """ newItem = self.GetItem(item, item._col) newItem.SetVisited(visited) self.SetItem(newItem) self.RefreshLine(item) return True def GetItemVisited(self, item): """ Returns whether an hypertext item was visited. :param `item`: an instance of L{UltimateListItem}. """ item = self.GetItem(item, item._col) return item.GetVisited() def GetItemWindow(self, item): """ Returns the window associated to the item (if any). :param `item`: an instance of L{UltimateListItem}. """ item = self.GetItem(item, item._col) return item.GetWindow() def SetItemWindow(self, item, wnd, expand=False): """ Sets the window for the given item. :param `item`: an instance of L{UltimateListItem}; :param `wnd`: if not ``None``, a non-toplevel window to be displayed next to the item; :param `expand`: ``True`` to expand the column where the item/subitem lives, so that the window will be fully visible. """ if not self.InReportView() or not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): raise Exception("Widgets are only allowed in repotr mode and with the ULC_HAS_VARIABLE_ROW_HEIGHT style.") item = self.GetItem(item, item._col) if wnd is not None: self._hasWindows = True if item not in self._itemWithWindow: self._itemWithWindow.append(item) else: self.DeleteItemWindow(item) else: self.DeleteItemWindow(item) item.SetWindow(wnd, expand) self.SetItem(item) self.RecalculatePositions() self.Refresh() def DeleteItemWindow(self, item): """ Deletes the window associated to an item (if any). :param `item`: an instance of L{UltimateListItem}. """ if item.GetWindow() is None: return item.DeleteWindow() if item in self._itemWithWindow: self._itemWithWindow.remove(item) self.SetItem(item) self.RecalculatePositions() def GetItemWindowEnabled(self, item): """ Returns whether the window associated to the item is enabled. :param `item`: an instance of L{UltimateListItem}. """ item = self.GetItem(item, item._col) return item.GetWindowEnabled() def SetItemWindowEnabled(self, item, enable=True): """ Enables/disables the window associated to the item. :param `item`: an instance of L{UltimateListItem}; :param `enable`: ``True`` to enable the associated window, ``False`` to disable it. """ item = self.GetItem(item, item._col) item.SetWindowEnabled(enable) self.SetItem(item) self.Refresh() def SetColumnCustomRenderer(self, col=0, renderer=None): """ Associate a custom renderer to this column's header :param `col`: the column index. :param `renderer`: a class able to correctly render the input item. :note: the renderer class **must** implement the methods `DrawHeaderButton`, and `GetForegroundColor`. """ self._columns[col].SetCustomRenderer(renderer) def GetColumnCustomRenderer(self, col): """ Returns the custom renderer used to draw the column header :param `col`: the column index. """ return self._columns[col].GetCustomRenderer() def GetItemCustomRenderer(self, item): """ Returns the custom renderer used to draw the input item (if any). :param `item`: an instance of L{UltimateListItem}. """ item = self.GetItem(item, item._col) return item.GetCustomRenderer() def SetItemCustomRenderer(self, item, renderer=None): """ Associate a custom renderer to this item. :param `item`: an instance of L{UltimateListItem}; :param `renderer`: a class able to correctly render the item. :note: the renderer class **must** implement the methods `DrawSubItem`, `GetLineHeight` and `GetSubItemWidth`. """ item = self.GetItem(item, item._col) item.SetCustomRenderer(renderer) self.SetItem(item) self.ResetLineDimensions() self.Refresh() def GetItemOverFlow(self, item): """ Returns if the item is in the overflow state. An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it. :param `item`: an instance of L{UltimateListItem}. """ item = self.GetItem(item, item._col) return item.GetOverFlow() def SetItemOverFlow(self, item, over=True): """ Sets the item in the overflow/non overflow state. An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it. :param `item`: an instance of L{UltimateListItem}; :param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise. """ item = self.GetItem(item, item._col) item.SetOverFlow(over) self.SetItem(item) self.Refresh() # ---------------------------------------------------------------------------- # item count # ---------------------------------------------------------------------------- def GetItemCount(self): """ Returns the number of items in the L{UltimateListCtrl}. """ return (self.IsVirtual() and [self._countVirt] or [len(self._lines)])[0] def SetItemCount(self, count): """ This method can only be used with virtual L{UltimateListCtrl}. It is used to indicate to the control the number of items it contains. After calling it, the main program should be ready to handle calls to various item callbacks (such as L{UltimateListCtrl.OnGetItemText}) for all items in the range from 0 to `count`. :param `count`: the total number of items in L{UltimateListCtrl}. """ self._selStore.SetItemCount(count) self._countVirt = count self.ResetVisibleLinesRange() # scrollbars must be reset self._dirty = True def GetSelectedItemCount(self): """ Returns the number of selected items in L{UltimateListCtrl}. """ # deal with the quick case first if self.IsSingleSel(): return (self.HasCurrent() and [self.IsHighlighted(self._current)] or [False])[0] # virtual controls remmebers all its selections itself if self.IsVirtual(): return self._selStore.GetSelectedCount() # TODO: we probably should maintain the number of items selected even for # non virtual controls as enumerating all lines is really slow... countSel = 0 count = self.GetItemCount() for line in xrange(count): if self.GetLine(line).IsHighlighted(): countSel += 1 return countSel # ---------------------------------------------------------------------------- # item position/size # ---------------------------------------------------------------------------- def GetViewRect(self): """ Returns the rectangle taken by all items in the control. In other words, if the controls client size were equal to the size of this rectangle, no scrollbars would be needed and no free space would be left. :note: This function only works in the icon and small icon views, not in list or report views. """ if self.HasAGWFlag(ULC_LIST): raise Exception("UltimateListCtrl.GetViewRect() not implemented for list view") # we need to find the longest/tallest label xMax = yMax = 0 count = self.GetItemCount() if count: for i in xrange(count): # we need logical, not physical, coordinates here, so use # GetLineRect() instead of GetItemRect() r = self.GetLineRect(i) x, y = r.GetRight(), r.GetBottom() if x > xMax: xMax = x if y > yMax: yMax = y # some fudge needed to make it look prettier xMax += 2*EXTRA_BORDER_X yMax += 2*EXTRA_BORDER_Y # account for the scrollbars if necessary sizeAll = self.GetClientSize() if xMax > sizeAll.x: yMax += wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y) if yMax > sizeAll.y: xMax += wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X) return wx.Rect(0, 0, xMax, yMax) def GetSubItemRect(self, item, subItem): """ Returns the rectangle representing the size and position, in physical coordinates, of the given subitem, i.e. the part of the row `item` in the column `subItem`. :param `item`: the row in which the item lives; :param `subItem`: the column in which the item lives. If set equal to the special value ``ULC_GETSUBITEMRECT_WHOLEITEM`` the return value is the same as for L{GetItemRect}. :note: This method is only meaningful when the L{UltimateListCtrl} is in the report mode. """ if not self.InReportView() and subItem == ULC_GETSUBITEMRECT_WHOLEITEM: raise Exception("GetSubItemRect only meaningful in report view") if item < 0 or item >= self.GetItemCount(): raise Exception("invalid item in GetSubItemRect") # ensure that we're laid out, otherwise we could return nonsense if self._dirty: self.RecalculatePositions(True) rect = self.GetLineRect(item) # Adjust rect to specified column if subItem != ULC_GETSUBITEMRECT_WHOLEITEM: if subItem < 0 or subItem >= self.GetColumnCount(): raise Exception("invalid subItem in GetSubItemRect") for i in xrange(subItem): rect.x += self.GetColumnWidth(i) rect.width = self.GetColumnWidth(subItem) rect.x, rect.y = self.CalcScrolledPosition(rect.x, rect.y) return rect def GetItemRect(self, item): """ Returns the rectangle representing the item's size and position, in physical coordinates. :param `item`: the row in which the item lives. """ return self.GetSubItemRect(item, ULC_GETSUBITEMRECT_WHOLEITEM) def GetItemPosition(self, item): """ Returns the position of the item, in icon or small icon view. :param `item`: the row in which the item lives. """ rect = self.GetItemRect(item) return wx.Point(rect.x, rect.y) # ---------------------------------------------------------------------------- # geometry calculation # ---------------------------------------------------------------------------- def RecalculatePositions(self, noRefresh=False): """ Recalculates all the items positions, and sets the scrollbars positions too. :param `noRefresh`: ``True`` to avoid calling `Refresh`, ``False`` otherwise. """ count = self.GetItemCount() if self.HasAGWFlag(ULC_ICON) and self._normal_image_list: iconSpacing = self._normal_spacing elif self.HasAGWFlag(ULC_SMALL_ICON) and self._small_image_list: iconSpacing = self._small_spacing else: iconSpacing = 0 # Note that we do not call GetClientSize() here but # GetSize() and subtract the border size for sunken # borders manually. This is technically incorrect, # but we need to know the client area's size WITHOUT # scrollbars here. Since we don't know if there are # any scrollbars, we use GetSize() instead. Another # solution would be to call SetScrollbars() here to # remove the scrollbars and call GetClientSize() then, # but this might result in flicker and - worse - will # reset the scrollbars to 0 which is not good at all # if you resize a dialog/window, but don't want to # reset the window scrolling. RR. # Furthermore, we actually do NOT subtract the border # width as 2 pixels is just the extra space which we # need around the actual content in the window. Other- # wise the text would e.g. touch the upper border. RR. clientWidth, clientHeight = self.GetSize() if self.InReportView(): self.ResetVisibleLinesRange() if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): # all lines have the same height and we scroll one line per step lineHeight = self.GetLineHeight() entireHeight = count*lineHeight + LINE_SPACING decrement = 0 if entireHeight > self.GetClientSize()[1]: decrement = SCROLL_UNIT_X self._linesPerPage = clientHeight/lineHeight self.SetScrollbars(SCROLL_UNIT_X, lineHeight, (self.GetHeaderWidth()-decrement)/SCROLL_UNIT_X, (entireHeight + lineHeight - 1)/lineHeight, self.GetScrollPos(wx.HORIZONTAL), self.GetScrollPos(wx.VERTICAL), True) else: if count > 0: entireHeight = self.GetLineY(count-1) + self.GetLineHeight(count-1) + LINE_SPACING lineFrom, lineTo = self.GetVisibleLinesRange() self._linesPerPage = lineTo - lineFrom + 1 else: lineHeight = self.GetLineHeight() entireHeight = count*lineHeight + LINE_SPACING self._linesPerPage = clientHeight/lineHeight decrement = 0 if entireHeight > self.GetClientSize()[1]: decrement = SCROLL_UNIT_X self.SetScrollbars(SCROLL_UNIT_X, SCROLL_UNIT_Y, (self.GetHeaderWidth()-decrement)/SCROLL_UNIT_X, (entireHeight + SCROLL_UNIT_Y - 1)/SCROLL_UNIT_Y, self.GetScrollPos(wx.HORIZONTAL), self.GetScrollPos(wx.VERTICAL), True) else: # !report dc = wx.ClientDC(self) dc.SetFont(self.GetFont()) lineHeight = self.GetLineHeight() # we have 3 different layout strategies: either layout all items # horizontally/vertically (ULC_ALIGN_XXX styles explicitly given) or # to arrange them in top to bottom, left to right (don't ask me why # not the other way round...) order if self.HasAGWFlag(ULC_ALIGN_LEFT | ULC_ALIGN_TOP): x = EXTRA_BORDER_X y = EXTRA_BORDER_Y widthMax = 0 for i in xrange(count): line = self.GetLine(i) line.CalculateSize(dc, iconSpacing) line.SetPosition(x, y, iconSpacing) sizeLine = self.GetLineSize(i) if self.HasAGWFlag(ULC_ALIGN_TOP): if sizeLine.x > widthMax: widthMax = sizeLine.x y += sizeLine.y else: # ULC_ALIGN_LEFT x += sizeLine.x + MARGIN_BETWEEN_ROWS if self.HasAGWFlag(ULC_ALIGN_TOP): # traverse the items again and tweak their sizes so that they are # all the same in a row for i in xrange(count): line = self.GetLine(i) line._gi.ExtendWidth(widthMax) self.SetScrollbars(SCROLL_UNIT_X, lineHeight, (x + SCROLL_UNIT_X)/SCROLL_UNIT_X, (y + lineHeight)/lineHeight, self.GetScrollPos(wx.HORIZONTAL), self.GetScrollPos(wx.VERTICAL), True) else: # "flowed" arrangement, the most complicated case # at first we try without any scrollbars, if the items don't fit into # the window, we recalculate after subtracting the space taken by the # scrollbar entireWidth = 0 for tries in xrange(2): entireWidth = 2*EXTRA_BORDER_X if tries == 1: # Now we have decided that the items do not fit into the # client area, so we need a scrollbar entireWidth += SCROLL_UNIT_X x = EXTRA_BORDER_X y = EXTRA_BORDER_Y maxWidthInThisRow = 0 self._linesPerPage = 0 currentlyVisibleLines = 0 for i in xrange(count): currentlyVisibleLines += 1 line = self.GetLine(i) line.CalculateSize(dc, iconSpacing) line.SetPosition(x, y, iconSpacing) sizeLine = self.GetLineSize(i) if maxWidthInThisRow < sizeLine.x: maxWidthInThisRow = sizeLine.x y += sizeLine.y if currentlyVisibleLines > self._linesPerPage: self._linesPerPage = currentlyVisibleLines if y + sizeLine.y >= clientHeight: currentlyVisibleLines = 0 y = EXTRA_BORDER_Y maxWidthInThisRow += MARGIN_BETWEEN_ROWS x += maxWidthInThisRow entireWidth += maxWidthInThisRow maxWidthInThisRow = 0 # We have reached the last item. if i == count - 1: entireWidth += maxWidthInThisRow if tries == 0 and entireWidth + SCROLL_UNIT_X > clientWidth: clientHeight -= wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y) self._linesPerPage = 0 break if i == count - 1: break # Everything fits, no second try required. self.SetScrollbars(SCROLL_UNIT_X, lineHeight, (entireWidth + SCROLL_UNIT_X)/SCROLL_UNIT_X, 0, self.GetScrollPos(wx.HORIZONTAL), 0, True) self._dirty = False if not noRefresh: # FIXME: why should we call it from here? self.UpdateCurrent() self.RefreshAll() def RefreshAll(self): """ Refreshes the entire l{UltimateListCtrl}. """ self._dirty = False self.Refresh() headerWin = self.GetListCtrl()._headerWin if headerWin and headerWin._dirty: headerWin._dirty = False headerWin.Refresh() def UpdateCurrent(self): """ Updates the current line selection. """ if not self.HasCurrent() and not self.IsEmpty(): self.ChangeCurrent(0) def GetNextItem(self, item, geometry=ULC_NEXT_ALL, state=ULC_STATE_DONTCARE): """ Searches for an item with the given `geometry` or `state`, starting from `item` but excluding the `item` itself. :param `item`: the item at which starting the search. If set to -1, the first item that matches the specified flags will be returned. :param `geometry`: can be one of: =================== ========= ================================= Geometry Flag Hex Value Description =================== ========= ================================= ``ULC_NEXT_ABOVE`` 0x0 Searches for an item above the specified item ``ULC_NEXT_ALL`` 0x1 Searches for subsequent item by index ``ULC_NEXT_BELOW`` 0x2 Searches for an item below the specified item ``ULC_NEXT_LEFT`` 0x3 Searches for an item to the left of the specified item ``ULC_NEXT_RIGHT`` 0x4 Searches for an item to the right of the specified item =================== ========= ================================= :param `state`: any combination of the following bits: ============================ ========= ============================== State Bits Hex Value Description ============================ ========= ============================== ``ULC_STATE_DONTCARE`` 0x0 Don't care what the state is ``ULC_STATE_DROPHILITED`` 0x1 The item is highlighted to receive a drop event ``ULC_STATE_FOCUSED`` 0x2 The item has the focus ``ULC_STATE_SELECTED`` 0x4 The item is selected ``ULC_STATE_CUT`` 0x8 The item is in the cut state ``ULC_STATE_DISABLED`` 0x10 The item is disabled ``ULC_STATE_FILTERED`` 0x20 The item has been filtered ``ULC_STATE_INUSE`` 0x40 The item is in use ``ULC_STATE_PICKED`` 0x80 The item has been picked ``ULC_STATE_SOURCE`` 0x100 The item is a drag and drop source ============================ ========= ============================== :return: The first item with given state following item or -1 if no such item found. :note: This function may be used to find all selected items in the control like this:: item = -1 while 1: item = listctrl.GetNextItem(item, ULC_NEXT_ALL, ULC_STATE_SELECTED) if item == -1: break # This item is selected - do whatever is needed with it wx.LogMessage("Item %ld is selected."%item) """ ret = item maxI = self.GetItemCount() # notice that we start with the next item (or the first one if item == -1) # and this is intentional to allow writing a simple loop to iterate over # all selected items ret += 1 if ret == maxI: # this is not an error because the index was ok initially, just no # such item return -1 if not state: # any will do return ret for line in xrange(ret, maxI): if state & ULC_STATE_FOCUSED and line == self._current: return line if state & ULC_STATE_SELECTED and self.IsHighlighted(line): return line return -1 # ---------------------------------------------------------------------------- # deleting stuff # ---------------------------------------------------------------------------- def DeleteItem(self, lindex): """ Deletes the specified item. :param `lindex`: the index of the item to delete. :note: This function sends the ``EVT_LIST_DELETE_ITEM`` event for the item being deleted. """ count = self.GetItemCount() if lindex < 0 or lindex >= self.GetItemCount(): raise Exception("invalid item index in DeleteItem") # we don't need to adjust the index for the previous items if self.HasCurrent() and self._current >= lindex: # if the current item is being deleted, we want the next one to # become selected - unless there is no next one - so don't adjust # self._current in this case if self._current != lindex or self._current == count - 1: self._current -= 1 if self.InReportView(): # mark the Column Max Width cache as dirty if the items in the line # we're deleting contain the Max Column Width line = self.GetLine(lindex) item = UltimateListItem() for i in xrange(len(self._columns)): itemData = line._items[i] item = itemData.GetItem(item) itemWidth = self.GetItemWidthWithImage(item) if itemWidth >= self._aColWidths[i]._nMaxWidth: self._aColWidths[i]._bNeedsUpdate = True if item.GetWindow(): self.DeleteItemWindow(item) self.ResetVisibleLinesRange(True) self._current = -1 self.SendNotify(lindex, wxEVT_COMMAND_LIST_DELETE_ITEM) if self.IsVirtual(): self._countVirt -= 1 self._selStore.OnItemDelete(lindex) else: self._lines.pop(lindex) # we need to refresh the (vert) scrollbar as the number of items changed self._dirty = True self._lineHeight = 0 self.ResetLineDimensions(True) self.RecalculatePositions() self.RefreshAfter(lindex) def DeleteColumn(self, col): """ Deletes the specified column. :param `col`: the index of the column to delete. """ self._columns.pop(col) self._dirty = True if not self.IsVirtual(): # update all the items for i in xrange(len(self._lines)): line = self.GetLine(i) line._items.pop(col) if self.InReportView(): # we only cache max widths when in Report View self._aColWidths.pop(col) # invalidate it as it has to be recalculated self._headerWidth = 0 def DoDeleteAllItems(self): """ Actually performs the deletion of all the items. """ if self.IsEmpty(): # nothing to do - in particular, don't send the event return self.ResetCurrent() # to make the deletion of all items faster, we don't send the # notifications for each item deletion in this case but only one event # for all of them: this is compatible with wxMSW and documented in # DeleteAllItems() description event = UltimateListEvent(wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS, self.GetParent().GetId()) event.SetEventObject(self.GetParent()) self.GetParent().GetEventHandler().ProcessEvent(event) if self.IsVirtual(): self._countVirt = 0 self._selStore.Clear() if self.InReportView(): self.ResetVisibleLinesRange(True) for i in xrange(len(self._aColWidths)): self._aColWidths[i]._bNeedsUpdate = True for item in self._itemWithWindow: wnd = item.GetWindow() wnd.Destroy() self._lines = [] self._itemWithWindow = [] self._hasWindows = False def DeleteAllItems(self): """ Deletes all items in the L{UltimateListCtrl}. :note: This function does not send the ``EVT_LIST_DELETE_ITEM`` event because deleting many items from the control would be too slow then (unlike L{DeleteItem}). """ self.DoDeleteAllItems() self.RecalculatePositions() def DeleteEverything(self): """ Deletes all items in the L{UltimateListCtrl}, resetting column widths to zero. """ self._columns = [] self._aColWidths = [] self.DeleteAllItems() # ---------------------------------------------------------------------------- # scanning for an item # ---------------------------------------------------------------------------- def EnsureVisible(self, index): """ Ensures this item is visible. :param `index`: the index of the item to scroll into view. """ if index < 0 or index >= self.GetItemCount(): raise Exception("invalid item index in EnsureVisible") # We have to call this here because the label in question might just have # been added and its position is not known yet if self._dirty: self.RecalculatePositions(True) self.MoveToItem(index) def FindItem(self, start, string, partial=False): """ Find an item whose label matches this string. :param `start`: the starting point of the input `string` or the beginning if `start` is -1; :param `string`: the string to look for matches; :param `partial`: if ``True`` then this method will look for items which begin with `string`. :note: The string comparison is case insensitive. """ if start < 0: start = 0 str_upper = string.upper() count = self.GetItemCount() for i in xrange(start, count): line = self.GetLine(i) text = line.GetText(0) line_upper = text.upper() if not partial: if line_upper == str_upper: return i else: if line_upper.find(str_upper) == 0: return i return wx.NOT_FOUND def FindItemData(self, start, data): """ Find an item whose data matches this data. :param `start`: the starting point of the input `data` or the beginning if `start` is -1; :param `data`: the data to look for matches. """ if start < 0: start = 0 count = self.GetItemCount() for i in xrange(start, count): line = self.GetLine(i) item = UltimateListItem() item = line.GetItem(0, item) if item._data == data: return i return wx.NOT_FOUND def FindItemAtPos(self, pt): """ Find an item nearest this position. :param `pt`: an instance of `wx.Point`. """ topItem, dummy = self.GetVisibleLinesRange() p = self.GetItemPosition(self.GetItemCount()-1) if p.y == 0: return topItem id = int(math.floor(pt.y*float(self.GetItemCount()-topItem-1)/p.y+topItem)) if id >= 0 and id < self.GetItemCount(): return id return wx.NOT_FOUND def HitTest(self, x, y): """ HitTest method for a L{UltimateListCtrl}. :param `x`: the mouse x position; :param `y`: the mouse y position. :see: L{HitTestLine} for a list of return flags. """ x, y = self.CalcUnscrolledPosition(x, y) count = self.GetItemCount() if self.InReportView(): if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): current = y/self.GetLineHeight() if current < count: newItem, flags = self.HitTestLine(current, x, y) if flags: return current, flags else: for current in xrange(self._lineFrom, count): newItem, flags = self.HitTestLine(current, x, y) if flags: return current, flags else: # TODO: optimize it too! this is less simple than for report view but # enumerating all items is still not a way to do it!! for current in xrange(count): newItem, flags = self.HitTestLine(current, x, y) if flags: return current, flags return wx.NOT_FOUND, None # ---------------------------------------------------------------------------- # adding stuff # ---------------------------------------------------------------------------- def InsertItem(self, item): """ Inserts an item into L{UltimateListCtrl}. :param `item`: an instance of L{UltimateListItem}. """ if self.IsVirtual(): raise Exception("can't be used with virtual control") count = self.GetItemCount() if item._itemId < 0: raise Exception("invalid item index") CheckVariableRowHeight(self, item._text) if item._itemId > count: item._itemId = count id = item._itemId self._dirty = True if self.InReportView(): self.ResetVisibleLinesRange(True) # calculate the width of the item and adjust the max column width pWidthInfo = self._aColWidths[item.GetColumn()] width = self.GetItemWidthWithImage(item) item.SetWidth(width) if width > pWidthInfo._nMaxWidth: pWidthInfo._nMaxWidth = width line = UltimateListLineData(self) line.SetItem(item._col, item) self._lines.insert(id, line) self._dirty = True # If an item is selected at or below the point of insertion, we need to # increment the member variables because the current row's index has gone # up by one if self.HasCurrent() and self._current >= id: self._current += 1 self.SendNotify(id, wxEVT_COMMAND_LIST_INSERT_ITEM) self.RefreshLines(id, self.GetItemCount() - 1) def InsertColumn(self, col, item): """ Inserts a column into L{UltimateListCtrl}. :param `col`: the column index at which we wish to insert a new column; :param `item`: an instance of L{UltimateListItem}. :note: This method is meaningful only if L{UltimateListCtrl} has the ``ULC_REPORT`` or the ``ULC_TILE`` styles set. """ self._dirty = True if self.InReportView() or self.InTileView() or self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS): if item._width == ULC_AUTOSIZE_USEHEADER: item._width = self.GetTextLength(item._text) column = UltimateListHeaderData(item) colWidthInfo = ColWidthInfo() insert = (col >= 0) and (col < len(self._columns)) if insert: self._columns.insert(col, column) self._aColWidths.insert(col, colWidthInfo) else: self._columns.append(column) self._aColWidths.append(colWidthInfo) if not self.IsVirtual(): # update all the items for i in xrange(len(self._lines)): line = self.GetLine(i) data = UltimateListItemData(self) if insert: line._items.insert(col, data) else: line._items.append(data) # invalidate it as it has to be recalculated self._headerWidth = 0 def GetItemWidthWithImage(self, item): """ Returns the item width, in pixels, considering the item text and its images. :param `item`: an instance of L{UltimateListItem}. """ if item.GetCustomRenderer(): return item.GetCustomRenderer().GetSubItemWidth() width = 0 dc = wx.ClientDC(self) if item.GetFont().IsOk(): font = item.GetFont() else: font = self.GetFont() dc.SetFont(font) if item.GetKind() in [1, 2]: ix, iy = self.GetCheckboxImageSize() width += ix if item.GetImage(): ix, iy = self.GetImageSize(item.GetImage()) width += ix + IMAGE_MARGIN_IN_REPORT_MODE if item.GetText(): w, h, dummy = dc.GetMultiLineTextExtent(item.GetText()) width += w if item.GetWindow(): width += item._windowsize.x + 5 return width def GetItemTextSize(self, item): """ Returns the item width, in pixels, considering only the item text. :param `item`: an instance of L{UltimateListItem}. """ width = ix = iy = start = end = 0 dc = wx.ClientDC(self) if item.HasFont(): font = item.GetFont() else: font = self.GetFont() dc.SetFont(font) if item.GetKind() in [1, 2]: ix, iy = self.GetCheckboxImageSize() start += ix if item.GetImage(): ix, iy = self.GetImageSize(item.GetImage()) start += ix + IMAGE_MARGIN_IN_REPORT_MODE if item.GetText(): w, h, dummy = dc.GetMultiLineTextExtent(item.GetText()) end = w return start, end # ---------------------------------------------------------------------------- # sorting # ---------------------------------------------------------------------------- def OnCompareItems(self, line1, line2): """ Returns whether 2 lines have the same index. Override this function in the derived class to change the sort order of the items in the L{UltimateListCtrl}. The function should return a negative, zero or positive value if the first line is less than, equal to or greater than the second one. :param `line1`: an instance of L{UltimateListItem}; :param `line2`: another instance of L{UltimateListItem}. :note: The base class version compares lines by their index. """ item = UltimateListItem() item1 = line1.GetItem(0, item) item = UltimateListItem() item2 = line2.GetItem(0, item) data1 = item1._data data2 = item2._data if self.__func: return self.__func(data1, data2) else: return cmp(data1, data2) def SortItems(self, func): """ Call this function to sort the items in the L{UltimateListCtrl}. Sorting is done using the specified function `func`. This function must have the following prototype:: def OnCompareItems(self, line1, line2): DoSomething(line1, line2) # function code It is called each time when the two items must be compared and should return 0 if the items are equal, negative value if the first item is less than the second one and positive value if the first one is greater than the second one. :param `func`: the method to use to sort the items. The default is to use the L{OnCompareItems} method. """ self.HighlightAll(False) self.ResetCurrent() if self._hasWindows: self.HideWindows() if not func: self.__func = None self._lines.sort(self.OnCompareItems) else: self.__func = func self._lines.sort(self.OnCompareItems) if self.IsShownOnScreen(): self._dirty = True self._lineHeight = 0 self.ResetLineDimensions(True) self.RecalculatePositions(True) # ---------------------------------------------------------------------------- # scrolling # ---------------------------------------------------------------------------- def OnScroll(self, event): """ Handles the ``wx.EVT_SCROLLWIN`` event for L{UltimateListMainWindow}. :param `event`: a `wx.ScrollEvent` event to be processed. """ event.Skip() # update our idea of which lines are shown when we redraw the window the # next time self.ResetVisibleLinesRange() if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): wx.CallAfter(self.RecalculatePositions, True) if event.GetOrientation() == wx.HORIZONTAL: lc = self.GetListCtrl() if self.HasHeader(): lc._headerWin.Refresh() lc._headerWin.Update() if self.HasFooter(): lc._footerWin.Refresh() lc._footerWin.Update() def GetCountPerPage(self): """ Returns the number of items that can fit vertically in the visible area of the L{UltimateListCtrl} (list or report view) or the total number of items in the list control (icon or small icon view). """ if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): if not self._linesPerPage: self._linesPerPage = self.GetClientSize().y/self.GetLineHeight() return self._linesPerPage visibleFrom, visibleTo = self.GetVisibleLinesRange() self._linesPerPage = visibleTo - visibleFrom + 1 return self._linesPerPage def GetVisibleLinesRange(self): """ Returns the range of visible items on screen. :note: This method can be used only if L{UltimateListCtrl} has the ``ULC_REPORT`` style set. """ if not self.InReportView(): raise Exception("this is for report mode only") if self._lineFrom == -1: count = self.GetItemCount() if count: if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): view_x, view_y = self.GetViewStart() view_y *= SCROLL_UNIT_Y for i in xrange(0, count): rc = self.GetLineY(i) if rc > view_y: self._lineFrom = i - 1 break if self._lineFrom < 0: self._lineFrom = 0 self._lineTo = self._lineFrom clientWidth, clientHeight = self.GetClientSize() for i in xrange(self._lineFrom, count): rc = self.GetLineY(i) + self.GetLineHeight(i) if rc > view_y + clientHeight - 5: break self._lineTo += 1 else: # No variable row height self._lineFrom = self.GetScrollPos(wx.VERTICAL) # this may happen if SetScrollbars() hadn't been called yet if self._lineFrom >= count: self._lineFrom = count - 1 self._lineTo = self._lineFrom + self._linesPerPage # we redraw one extra line but this is needed to make the redrawing # logic work when there is a fractional number of lines on screen if self._lineTo >= count: self._lineTo = count - 1 else: # empty control self._lineFrom = -1 self._lineTo = -1 return self._lineFrom, self._lineTo def ResetTextControl(self): """ Called by L{UltimateListTextCtrl} when it marks itself for deletion.""" self._textctrl.Destroy() self._textctrl = None self.RecalculatePositions() self.Refresh() def SetFirstGradientColour(self, colour=None): """ Sets the first gradient colour for gradient-style selections. :param `colour`: if not ``None``, a valid `wx.Colour` instance. Otherwise, the colour is taken from the system value ``wx.SYS_COLOUR_HIGHLIGHT``. """ if colour is None: colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT) self._firstcolour = colour if self._usegradients: self.RefreshSelected() def SetSecondGradientColour(self, colour=None): """ Sets the second gradient colour for gradient-style selections. :param `colour`: if not ``None``, a valid `wx.Colour` instance. Otherwise, the colour generated is a slightly darker version of the L{UltimateListCtrl} background colour. """ if colour is None: # No colour given, generate a slightly darker from the # UltimateListCtrl background colour colour = self.GetBackgroundColour() r, g, b = int(colour.Red()), int(colour.Green()), int(colour.Blue()) colour = ((r >> 1) + 20, (g >> 1) + 20, (b >> 1) + 20) colour = wx.Colour(colour[0], colour[1], colour[2]) self._secondcolour = colour if self._usegradients: self.RefreshSelected() def GetFirstGradientColour(self): """ Returns the first gradient colour for gradient-style selections. """ return self._firstcolour def GetSecondGradientColour(self): """ Returns the second gradient colour for gradient-style selections. """ return self._secondcolour def EnableSelectionGradient(self, enable=True): """ Globally enables/disables drawing of gradient selections. :param `enable`: ``True`` to enable gradient-style selections, ``False`` to disable it. :note: Calling this method disables any Vista-style selection previously enabled. """ self._usegradients = enable self._vistaselection = False self.RefreshSelected() def SetGradientStyle(self, vertical=0): """ Sets the gradient style for gradient-style selections. :param `vertical`: 0 for horizontal gradient-style selections, 1 for vertical gradient-style selections. """ # 0 = Horizontal, 1 = Vertical self._gradientstyle = vertical if self._usegradients: self.RefreshSelected() def GetGradientStyle(self): """ Returns the gradient style for gradient-style selections. :return: 0 for horizontal gradient-style selections, 1 for vertical gradient-style selections. """ return self._gradientstyle def EnableSelectionVista(self, enable=True): """ Globally enables/disables drawing of Windows Vista selections. :param `enable`: ``True`` to enable Vista-style selections, ``False`` to disable it. :note: Calling this method disables any gradient-style selection previously enabled. """ self._usegradients = False self._vistaselection = enable self.RefreshSelected() def SetBackgroundImage(self, image): """ Sets the L{UltimateListCtrl} background image. :param `image`: if not ``None``, an instance of `wx.Bitmap`. :note: At present, the background image can only be used in "tile" mode. :todo: Support background images also in stretch and centered modes. """ self._backgroundImage = image self.Refresh() def GetBackgroundImage(self): """ Returns the L{UltimateListCtrl} background image (if any). :note: At present, the background image can only be used in "tile" mode. :todo: Support background images also in stretch and centered modes. """ return self._backgroundImage def SetWaterMark(self, watermark): """ Sets the L{UltimateListCtrl} watermark image to be displayed in the bottom right part of the window. :param `watermark`: if not ``None``, an instance of `wx.Bitmap`. :todo: Better support for this is needed. """ self._waterMark = watermark self.Refresh() def GetWaterMark(self): """ Returns the L{UltimateListCtrl} watermark image (if any), displayed in the bottom right part of the window. :todo: Better support for this is needed. """ return self._waterMark def SetDisabledTextColour(self, colour): """ Sets the items disabled colour. :param `colour`: an instance of `wx.Colour`. """ # Disabled items colour self._disabledColour = colour self.Refresh() def GetDisabledTextColour(self): """ Returns the items disabled colour. """ return self._disabledColour def ScrollList(self, dx, dy): """ Scrolls the L{UltimateListCtrl}. :param `dx`: if in icon, small icon or report view mode, specifies the number of pixels to scroll. If in list view mode, `dx` specifies the number of columns to scroll. :param `dy`: always specifies the number of pixels to scroll vertically. """ if not self.InReportView(): # TODO: this should work in all views but is not implemented now return False top, bottom = self.GetVisibleLinesRange() if bottom == -1: return 0 self.ResetVisibleLinesRange() if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): hLine = self.GetLineHeight() self.Scroll(-1, top + dy/hLine) else: self.Scroll(-1, top + dy/SCROLL_UNIT_Y) if wx.Platform == "__WXMAC__": # see comment in MoveToItem() for why we do this self.ResetVisibleLinesRange() return True # ------------------------------------------------------------------------------------- # UltimateListCtrl # ------------------------------------------------------------------------------------- class UltimateListCtrl(wx.PyControl): """ UltimateListCtrl is a class that mimics the behaviour of `wx.ListCtrl`, with almost the same base functionalities plus some more enhancements. This class does not rely on the native control, as it is a full owner-drawn list control. """ def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, agwStyle=0, validator=wx.DefaultValidator, name="UltimateListCtrl"): """ Default class constructor. :param `parent`: parent window. Must not be ``None``; :param `id`: window identifier. A value of -1 indicates a default value; :param `pos`: the control position. A value of (-1, -1) indicates a default position, chosen by either the windowing system or wxPython, depending on platform; :param `size`: the control size. A value of (-1, -1) indicates a default size, chosen by either the windowing system or wxPython, depending on platform; :param `style`: the underlying `wx.PyControl` window style; :param `agwStyle`: the AGW-specific window style; can be almost any combination of the following bits: =============================== =========== ==================================================================================================== Window Styles Hex Value Description =============================== =========== ==================================================================================================== ``ULC_VRULES`` 0x1 Draws light vertical rules between rows in report mode. ``ULC_HRULES`` 0x2 Draws light horizontal rules between rows in report mode. ``ULC_ICON`` 0x4 Large icon view, with optional labels. ``ULC_SMALL_ICON`` 0x8 Small icon view, with optional labels. ``ULC_LIST`` 0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a `wx.ListBox`. ``ULC_REPORT`` 0x20 Single or multicolumn report view, with optional header. ``ULC_ALIGN_TOP`` 0x40 Icons align to the top. Win32 default, Win32 only. ``ULC_ALIGN_LEFT`` 0x80 Icons align to the left. ``ULC_AUTOARRANGE`` 0x100 Icons arrange themselves. Win32 only. ``ULC_VIRTUAL`` 0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``. ``ULC_EDIT_LABELS`` 0x400 Labels are editable: the application will be notified when editing starts. ``ULC_NO_HEADER`` 0x800 No header in report mode. ``ULC_NO_SORT_HEADER`` 0x1000 No Docs. ``ULC_SINGLE_SEL`` 0x2000 Single selection (default is multiple). ``ULC_SORT_ASCENDING`` 0x4000 Sort in ascending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.) ``ULC_SORT_DESCENDING`` 0x8000 Sort in descending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.) ``ULC_TILE`` 0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented). ``ULC_NO_HIGHLIGHT`` 0x20000 No highlight when an item is selected. ``ULC_STICKY_HIGHLIGHT`` 0x40000 Items are selected by simply hovering on them, with no need to click on them. ``ULC_STICKY_NOSELEVENT`` 0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style. ``ULC_SEND_LEFTCLICK`` 0x100000 Send a left click event when an item is selected. ``ULC_HAS_VARIABLE_ROW_HEIGHT`` 0x200000 The list has variable row heights. ``ULC_AUTO_CHECK_CHILD`` 0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column. ``ULC_AUTO_TOGGLE_CHILD`` 0x800000 When a column header has a checkbox associated, toggle all the subitems in that column. ``ULC_AUTO_CHECK_PARENT`` 0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well. ``ULC_SHOW_TOOLTIPS`` 0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text. ``ULC_HOT_TRACKING`` 0x4000000 Enable hot tracking of items on mouse motion. ``ULC_BORDER_SELECT`` 0x8000000 Changes border colour whan an item is selected, instead of highlighting the item. ``ULC_TRACK_SELECT`` 0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`. ``ULC_HEADER_IN_ALL_VIEWS`` 0x20000000 Show column headers in all view modes. ``ULC_NO_FULL_ROW_SELECT`` 0x40000000 When an item is selected, the only the item in the first column is highlighted. ``ULC_FOOTER`` 0x80000000 Show a footer too (only when header is present). =============================== =========== ==================================================================================================== :param `validator`: the window validator; :param `name`: the window name. """ self._imageListNormal = None self._imageListSmall = None self._imageListState = None if not agwStyle & ULC_MASK_TYPE: raise Exception("UltimateListCtrl style should have exactly one mode bit set") if not (agwStyle & ULC_REPORT) and agwStyle & ULC_HAS_VARIABLE_ROW_HEIGHT: raise Exception("Style ULC_HAS_VARIABLE_ROW_HEIGHT can only be used in report, non-virtual mode") if agwStyle & ULC_STICKY_HIGHLIGHT and agwStyle & ULC_TRACK_SELECT: raise Exception("Styles ULC_STICKY_HIGHLIGHT and ULC_TRACK_SELECT can not be combined") if agwStyle & ULC_NO_HEADER and agwStyle & ULC_HEADER_IN_ALL_VIEWS: raise Exception("Styles ULC_NO_HEADER and ULC_HEADER_IN_ALL_VIEWS can not be combined") wx.PyControl.__init__(self, parent, id, pos, size, style|wx.CLIP_CHILDREN, validator, name) self._mainWin = None self._headerWin = None self._footerWin = None self._headerHeight = wx.RendererNative.Get().GetHeaderButtonHeight(self) self._footerHeight = self._headerHeight if wx.Platform == "__WXGTK__": style &= ~wx.BORDER_MASK style |= wx.BORDER_THEME else: if style & wx.BORDER_THEME: style -= wx.BORDER_THEME self._agwStyle = agwStyle if style & wx.SUNKEN_BORDER: style -= wx.SUNKEN_BORDER self._mainWin = UltimateListMainWindow(self, wx.ID_ANY, wx.Point(0, 0), size, style, agwStyle) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self._mainWin, 1, wx.GROW) self.SetSizer(sizer) self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self.CreateOrDestroyHeaderWindowAsNeeded() self.CreateOrDestroyFooterWindowAsNeeded() self.SetInitialSize(size) wx.CallAfter(self.Layout) def CreateOrDestroyHeaderWindowAsNeeded(self): """ Creates or destroys the header window depending on the window style flags. """ needs_header = self.HasHeader() has_header = self._headerWin is not None if needs_header == has_header: return if needs_header: self._headerWin = UltimateListHeaderWindow(self, wx.ID_ANY, self._mainWin, wx.Point(0, 0), wx.Size(self.GetClientSize().x, self._headerHeight), wx.TAB_TRAVERSAL, isFooter=False) # ---------------------------------------------------- # How do you translate all this blah-blah to wxPython? # ---------------------------------------------------- #if defined( __WXMAC__ ) && wxOSX_USE_COCOA_OR_CARBON # wxFont font #if wxOSX_USE_ATSU_TEXT # font.MacCreateFromThemeFont( kThemeSmallSystemFont ) #else # font.MacCreateFromUIFont( kCTFontSystemFontType ) #endif # m_headerWin->SetFont( font ) #endif self.GetSizer().Prepend(self._headerWin, 0, wx.GROW) else: self.GetSizer().Detach(self._headerWin) self._headerWin.Destroy() self._headerWin = None def CreateOrDestroyFooterWindowAsNeeded(self): """ Creates or destroys the footer window depending on the window style flags. """ needs_footer = self.HasFooter() has_footer = self._footerWin is not None if needs_footer == has_footer: return if needs_footer: self._footerWin = UltimateListHeaderWindow(self, wx.ID_ANY, self._mainWin, wx.Point(0, 0), wx.Size(self.GetClientSize().x, self._footerHeight), wx.TAB_TRAVERSAL, isFooter=True) # ---------------------------------------------------- # How do you translate all this blah-blah to wxPython? # ---------------------------------------------------- #if defined( __WXMAC__ ) && wxOSX_USE_COCOA_OR_CARBON # wxFont font #if wxOSX_USE_ATSU_TEXT # font.MacCreateFromThemeFont( kThemeSmallSystemFont ) #else # font.MacCreateFromUIFont( kCTFontSystemFontType ) #endif # m_headerWin->SetFont( font ) #endif self.GetSizer().Add(self._footerWin, 0, wx.GROW) else: self.GetSizer().Detach(self._footerWin) self._footerWin.Destroy() self._footerWin = None def HasHeader(self): """ Returns ``True`` if L{UltimateListCtrl} has a header window. """ return self._mainWin.HasHeader() def HasFooter(self): """ Returns ``True`` if L{UltimateListCtrl} has a footer window. """ return self._mainWin.HasFooter() def GetDefaultBorder(self): """ Returns the default window border. """ return wx.BORDER_THEME def SetSingleStyle(self, style, add=True): """ Adds or removes a single window style. :param `style`: can be one of the following bits: =============================== =========== ==================================================================================================== Window Styles Hex Value Description =============================== =========== ==================================================================================================== ``ULC_VRULES`` 0x1 Draws light vertical rules between rows in report mode. ``ULC_HRULES`` 0x2 Draws light horizontal rules between rows in report mode. ``ULC_ICON`` 0x4 Large icon view, with optional labels. ``ULC_SMALL_ICON`` 0x8 Small icon view, with optional labels. ``ULC_LIST`` 0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a `wx.ListBox`. ``ULC_REPORT`` 0x20 Single or multicolumn report view, with optional header. ``ULC_ALIGN_TOP`` 0x40 Icons align to the top. Win32 default, Win32 only. ``ULC_ALIGN_LEFT`` 0x80 Icons align to the left. ``ULC_AUTOARRANGE`` 0x100 Icons arrange themselves. Win32 only. ``ULC_VIRTUAL`` 0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``. ``ULC_EDIT_LABELS`` 0x400 Labels are editable: the application will be notified when editing starts. ``ULC_NO_HEADER`` 0x800 No header in report mode. ``ULC_NO_SORT_HEADER`` 0x1000 No Docs. ``ULC_SINGLE_SEL`` 0x2000 Single selection (default is multiple). ``ULC_SORT_ASCENDING`` 0x4000 Sort in ascending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.) ``ULC_SORT_DESCENDING`` 0x8000 Sort in descending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.) ``ULC_TILE`` 0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented). ``ULC_NO_HIGHLIGHT`` 0x20000 No highlight when an item is selected. ``ULC_STICKY_HIGHLIGHT`` 0x40000 Items are selected by simply hovering on them, with no need to click on them. ``ULC_STICKY_NOSELEVENT`` 0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style. ``ULC_SEND_LEFTCLICK`` 0x100000 Send a left click event when an item is selected. ``ULC_HAS_VARIABLE_ROW_HEIGHT`` 0x200000 The list has variable row heights. ``ULC_AUTO_CHECK_CHILD`` 0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column. ``ULC_AUTO_TOGGLE_CHILD`` 0x800000 When a column header has a checkbox associated, toggle all the subitems in that column. ``ULC_AUTO_CHECK_PARENT`` 0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well. ``ULC_SHOW_TOOLTIPS`` 0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text. ``ULC_HOT_TRACKING`` 0x4000000 Enable hot tracking of items on mouse motion. ``ULC_BORDER_SELECT`` 0x8000000 Changes border colour whan an item is selected, instead of highlighting the item. ``ULC_TRACK_SELECT`` 0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`. ``ULC_HEADER_IN_ALL_VIEWS`` 0x20000000 Show column headers in all view modes. ``ULC_NO_FULL_ROW_SELECT`` 0x40000000 When an item is selected, the only the item in the first column is highlighted. ``ULC_FOOTER`` 0x80000000 Show a footer too (only when header is present). =============================== =========== ==================================================================================================== :param `add`: ``True`` to add the window style, ``False`` to remove it. :note: The style ``ULC_VIRTUAL`` can not be set/unset after construction. """ if style & ULC_VIRTUAL: raise Exception("ULC_VIRTUAL can't be [un]set") flag = self.GetAGWWindowStyleFlag() if add: if style & ULC_MASK_TYPE: flag &= ~(ULC_MASK_TYPE | ULC_VIRTUAL) if style & ULC_MASK_ALIGN: flag &= ~ULC_MASK_ALIGN if style & ULC_MASK_SORT: flag &= ~ULC_MASK_SORT if add: flag |= style else: flag &= ~style # some styles can be set without recreating everything (as happens in # SetAGWWindowStyleFlag() which calls ListMainWindow.DeleteEverything()) if not style & ~(ULC_HRULES | ULC_VRULES): self.Refresh() self.SetAGWWindowStyleFlag(self, flag) else: self.SetAGWWindowStyleFlag(flag) def GetAGWWindowStyleFlag(self): """ Gets the L{UltimateListCtrl} AGW-specific style flag. See L{SetAGWWindowStyleFlag} for possible style flags. """ return self._agwStyle def SetAGWWindowStyleFlag(self, style): """ Sets the L{UltimateListCtrl} AGW-specific style flag. :param `style`: the AGW-specific window style; can be almost any combination of the following bits: =============================== =========== ==================================================================================================== Window Styles Hex Value Description =============================== =========== ==================================================================================================== ``ULC_VRULES`` 0x1 Draws light vertical rules between rows in report mode. ``ULC_HRULES`` 0x2 Draws light horizontal rules between rows in report mode. ``ULC_ICON`` 0x4 Large icon view, with optional labels. ``ULC_SMALL_ICON`` 0x8 Small icon view, with optional labels. ``ULC_LIST`` 0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a `wx.ListBox`. ``ULC_REPORT`` 0x20 Single or multicolumn report view, with optional header. ``ULC_ALIGN_TOP`` 0x40 Icons align to the top. Win32 default, Win32 only. ``ULC_ALIGN_LEFT`` 0x80 Icons align to the left. ``ULC_AUTOARRANGE`` 0x100 Icons arrange themselves. Win32 only. ``ULC_VIRTUAL`` 0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``. ``ULC_EDIT_LABELS`` 0x400 Labels are editable: the application will be notified when editing starts. ``ULC_NO_HEADER`` 0x800 No header in report mode. ``ULC_NO_SORT_HEADER`` 0x1000 No Docs. ``ULC_SINGLE_SEL`` 0x2000 Single selection (default is multiple). ``ULC_SORT_ASCENDING`` 0x4000 Sort in ascending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.) ``ULC_SORT_DESCENDING`` 0x8000 Sort in descending order. (You must still supply a comparison callback in `wx.ListCtrl.SortItems`.) ``ULC_TILE`` 0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented). ``ULC_NO_HIGHLIGHT`` 0x20000 No highlight when an item is selected. ``ULC_STICKY_HIGHLIGHT`` 0x40000 Items are selected by simply hovering on them, with no need to click on them. ``ULC_STICKY_NOSELEVENT`` 0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style. ``ULC_SEND_LEFTCLICK`` 0x100000 Send a left click event when an item is selected. ``ULC_HAS_VARIABLE_ROW_HEIGHT`` 0x200000 The list has variable row heights. ``ULC_AUTO_CHECK_CHILD`` 0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column. ``ULC_AUTO_TOGGLE_CHILD`` 0x800000 When a column header has a checkbox associated, toggle all the subitems in that column. ``ULC_AUTO_CHECK_PARENT`` 0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well. ``ULC_SHOW_TOOLTIPS`` 0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text. ``ULC_HOT_TRACKING`` 0x4000000 Enable hot tracking of items on mouse motion. ``ULC_BORDER_SELECT`` 0x8000000 Changes border colour whan an item is selected, instead of highlighting the item. ``ULC_TRACK_SELECT`` 0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`. ``ULC_HEADER_IN_ALL_VIEWS`` 0x20000000 Show column headers in all view modes. ``ULC_NO_FULL_ROW_SELECT`` 0x40000000 When an item is selected, the only the item in the first column is highlighted. ``ULC_FOOTER`` 0x80000000 Show a footer too (only when header is present). =============================== =========== ==================================================================================================== """ if style & ULC_HAS_VARIABLE_ROW_HEIGHT and not self.HasAGWFlag(ULC_REPORT): raise Exception("ULC_HAS_VARIABLE_ROW_HEIGHT style can be used only in report mode") wasInReportView = self.HasAGWFlag(ULC_REPORT) self._agwStyle = style if self._mainWin: inReportView = (style & ULC_REPORT) != 0 if inReportView != wasInReportView: # we need to notify the main window about this change as it must # update its data structures self._mainWin.SetReportView(inReportView) self.CreateOrDestroyHeaderWindowAsNeeded() self.CreateOrDestroyFooterWindowAsNeeded() self.GetSizer().Layout() if style & ULC_HAS_VARIABLE_ROW_HEIGHT: self._mainWin.ResetLineDimensions() self._mainWin.ResetVisibleLinesRange() self.Refresh() def HasAGWFlag(self, flag): """ Returns ``True`` if the window has the given flag bit set. :param `flag`: the window style to check. :see: L{SetAGWWindowStyleFlag} for a list of valid window styles. """ return self._agwStyle & flag def GetColumn(self, col): """ Returns information about this column. :param `col`: an integer specifying the column index. """ return self._mainWin.GetColumn(col) def SetColumn(self, col, item): """ Sets information about this column. :param `col`: an integer specifying the column index; :param `item`: an instance of L{UltimateListItem}. """ self._mainWin.SetColumn(col, item) return True def GetColumnWidth(self, col): """ Returns the column width for the input column. :param `col`: an integer specifying the column index. """ return self._mainWin.GetColumnWidth(col) def SetColumnWidth(self, col, width): """ Sets the column width. :param `width`: can be a width in pixels or ``wx.LIST_AUTOSIZE`` (-1) or ``wx.LIST_AUTOSIZE_USEHEADER`` (-2) or ``LIST_AUTOSIZE_FILL`` (-3). ``wx.LIST_AUTOSIZE`` will resize the column to the length of its longest item. ``wx.LIST_AUTOSIZE_USEHEADER`` will resize the column to the length of the header (Win32) or 80 pixels (other platforms). ``LIST_AUTOSIZE_FILL`` will resize the column fill the remaining width of the window. :note: In small or normal icon view, col must be -1, and the column width is set for all columns. """ self._mainWin.SetColumnWidth(col, width) return True def GetCountPerPage(self): """ Returns the number of items that can fit vertically in the visible area of the L{UltimateListCtrl} (list or report view) or the total number of items in the list control (icon or small icon view). """ return self._mainWin.GetCountPerPage() # different from Windows ? def GetItem(self, itemOrId, col=0): """ Returns the information about the input item. :param `itemOrId`: an instance of L{UltimateListItem} or an integer specifying the item index; :param `col`: the column to which the item belongs to. """ item = CreateListItem(itemOrId, col) return self._mainWin.GetItem(item, col) def SetItem(self, info): """ Sets the information about the input item. :param `info`: an instance of L{UltimateListItem}. """ self._mainWin.SetItem(info) return True def SetStringItem(self, index, col, label, imageIds=[], it_kind=0): """ Sets a string or image at the given location. :param `index`: the item index; :param `col`: the column to which the item belongs to; :param `label`: the item text; :param `imageIds`: a Python list containing the image indexes for the images associated to this item; :param `it_kind`: the item kind. May be one of the following integers: =============== ========================== Item Kind Description =============== ========================== 0 A normal item 1 A checkbox-like item 2 A radiobutton-type item =============== ========================== """ info = UltimateListItem() info._text = label info._mask = ULC_MASK_TEXT if it_kind: info._mask |= ULC_MASK_KIND info._kind = it_kind info._itemId = index info._col = col for ids in to_list(imageIds): if ids > -1: info._image.append(ids) if info._image: info._mask |= ULC_MASK_IMAGE self._mainWin.SetItem(info) return index def GetItemState(self, item, stateMask): """ Returns the item state flags for the input item. :param `item`: the index of the item; :param `stateMask`: the bitmask for the state flag. :see: L{SetItemState} for a list of valid state flags. """ return self._mainWin.GetItemState(item, stateMask) def SetItemState(self, item, state, stateMask): """ Sets the item state flags for the input item. :param `item`: the index of the item; if defaulted to -1, the state flag will be set for all the items; :param `state`: any combination of the following bits: ============================ ========= ============================== State Bits Hex Value Description ============================ ========= ============================== ``ULC_STATE_DONTCARE`` 0x0 Don't care what the state is ``ULC_STATE_DROPHILITED`` 0x1 The item is highlighted to receive a drop event ``ULC_STATE_FOCUSED`` 0x2 The item has the focus ``ULC_STATE_SELECTED`` 0x4 The item is selected ``ULC_STATE_CUT`` 0x8 The item is in the cut state ``ULC_STATE_DISABLED`` 0x10 The item is disabled ``ULC_STATE_FILTERED`` 0x20 The item has been filtered ``ULC_STATE_INUSE`` 0x40 The item is in use ``ULC_STATE_PICKED`` 0x80 The item has been picked ``ULC_STATE_SOURCE`` 0x100 The item is a drag and drop source ============================ ========= ============================== :param `stateMask`: the bitmask for the state flag. """ self._mainWin.SetItemState(item, state, stateMask) return True def SetItemImage(self, item, image, selImage=-1): """ Sets a Python list of image indexes associated with the item. :param `item`: an integer specifying the item index; :param `image`: a Python list of indexes into the image list associated with the L{UltimateListCtrl}. In report view, this only sets the images for the first column; :param `selImage`: not used at present. """ return self.SetItemColumnImage(item, 0, image) def SetItemColumnImage(self, item, column, image): """ Sets a Python list of image indexes associated with the item in the input column. :param `item`: an integer specifying the item index; :param `column`: the column to which the item belongs to; :param `image`: a Python list of indexes into the image list associated with the L{UltimateListCtrl}. """ info = UltimateListItem() info._image = to_list(image) info._mask = ULC_MASK_IMAGE info._itemId = item info._col = column self._mainWin.SetItem(info) return True def GetItemText(self, item): """ Returns the item text. :param `item`: an instance of L{UltimateListItem} or an integer specifying the item index. """ return self._mainWin.GetItemText(item) def SetItemText(self, item, text): """ Sets the item text. :param `item`: an instance of L{UltimateListItem} or an integer specifying the item index; :param `text`: the new item text. """ self._mainWin.SetItemText(item, text) def GetItemData(self, item): """ Gets the application-defined data associated with this item. :param `item`: an integer specifying the item index. """ info = UltimateListItem() info._mask = ULC_MASK_DATA info._itemId = item self._mainWin.GetItem(info) return info._data def SetItemData(self, item, data): """ Sets the application-defined data associated with this item. :param `item`: an integer specifying the item index; :param `data`: the data to be associated with the input item. :note: Tthis function cannot be used to associate pointers with the control items, use L{SetItemPyData} instead. """ info = UltimateListItem() info._mask = ULC_MASK_DATA info._itemId = item info._data = data self._mainWin.SetItem(info) return True def GetItemPyData(self, item): """ Returns the data for the item, which can be any Python object. :param `item`: an integer specifying the item index. :note: Please note that Python data is associated with the item and not with subitems. """ info = UltimateListItem() info._mask = ULC_MASK_PYDATA info._itemId = item self._mainWin.GetItem(info) return info._pyData def SetItemPyData(self, item, pyData): """ Sets the data for the item, which can be any Python object. :param `item`: an integer specifying the item index; :param `pyData`: any Python object. :note: Please note that Python data is associated with the item and not with subitems. """ info = UltimateListItem() info._mask = ULC_MASK_PYDATA info._itemId = item info._pyData = pyData self._mainWin.SetItem(info) return True SetPyData = SetItemPyData GetPyData = GetItemPyData def GetViewRect(self): """ Returns the rectangle taken by all items in the control. In other words, if the controls client size were equal to the size of this rectangle, no scrollbars would be needed and no free space would be left. :note: This function only works in the icon and small icon views, not in list or report views. """ return self._mainWin.GetViewRect() def GetItemRect(self, item, code=ULC_RECT_BOUNDS): """ Returns the rectangle representing the item's size and position, in physical coordinates. :param `item`: the row in which the item lives; :param `code`: one of ``ULC_RECT_BOUNDS``, ``ULC_RECT_ICON``, ``ULC_RECT_LABEL``. """ return self.GetSubItemRect(item, ULC_GETSUBITEMRECT_WHOLEITEM, code) def GetSubItemRect(self, item, subItem, code): """ Returns the rectangle representing the size and position, in physical coordinates, of the given subitem, i.e. the part of the row `item` in the column `subItem`. :param `item`: the row in which the item lives; :param `subItem`: the column in which the item lives. If set equal to the special value ``ULC_GETSUBITEMRECT_WHOLEITEM`` the return value is the same as for L{GetItemRect}; :param `code`: one of ``ULC_RECT_BOUNDS``, ``ULC_RECT_ICON``, ``ULC_RECT_LABEL``. :note: This method is only meaningful when the L{UltimateListCtrl} is in the report mode. """ rect = self._mainWin.GetSubItemRect(item, subItem) if self._mainWin.HasHeader(): rect.y += self._headerHeight + 1 return rect def GetItemPosition(self, item): """ Returns the position of the item, in icon or small icon view. :param `item`: the row in which the item lives. """ return self._mainWin.GetItemPosition(item) def SetItemPosition(self, item, pos): """ Sets the position of the item, in icon or small icon view. :param `item`: the row in which the item lives; :param `pos`: the item position. :note: This method is currently unimplemented and does nothing. """ return False def GetItemCount(self): """ Returns the number of items in the L{UltimateListCtrl}. """ return self._mainWin.GetItemCount() def GetColumnCount(self): """ Returns the total number of columns in the L{UltimateListCtrl}. """ return self._mainWin.GetColumnCount() def SetItemSpacing(self, spacing, isSmall=False): """ Sets the spacing between item texts and icons. :param `spacing`: the spacing between item texts and icons, in pixels; :param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list, ``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list. """ self._mainWin.SetItemSpacing(spacing, isSmall) def GetItemSpacing(self, isSmall=False): """ Returns the spacing between item texts and icons, in pixels. :param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list, ``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list. """ return self._mainWin.GetItemSpacing(isSmall) def SetItemTextColour(self, item, col): """ Sets the item text colour. :param `item`: the index of the item; :param `col`: a valid `wx.Colour` object. """ info = UltimateListItem() info._itemId = item info.SetTextColour(col) self._mainWin.SetItem(info) def GetItemTextColour(self, item): """ Returns the item text colour. :param `item`: the index of the item. """ info = UltimateListItem() info._itemId = item info = self._mainWin.GetItem(info) return info.GetTextColour() def SetItemBackgroundColour(self, item, col): """ Sets the item background colour. :param `item`: the index of the item; :param `col`: a valid `wx.Colour` object. """ info = UltimateListItem() info._itemId = item info.SetBackgroundColour(col) self._mainWin.SetItem(info) def GetItemBackgroundColour(self, item): """ Returns the item background colour. :param `item`: the index of the item. """ info = UltimateListItem() info._itemId = item info = self._mainWin.GetItem(info) return info.GetBackgroundColour() def SetItemFont(self, item, f): """ Sets the item font. :param `item`: the index of the item; :param `f`: a valid `wx.Font` object. """ info = UltimateListItem() info._itemId = item info.SetFont(f) self._mainWin.SetItem(info) def GetItemFont(self, item): """ Returns the item font. :param `item`: the index of the item. """ info = UltimateListItem() info._itemId = item info = self._mainWin.GetItem(info) return info.GetFont() def GetSelectedItemCount(self): """ Returns the number of selected items in L{UltimateListCtrl}. """ return self._mainWin.GetSelectedItemCount() def GetTextColour(self): """ Returns the L{UltimateListCtrl} foreground colour. """ return self.GetForegroundColour() def SetTextColour(self, col): """ Sets the L{UltimateListCtrl} foreground colour. :param `col`: a valid `wx.Colour` object. """ self.SetForegroundColour(col) def GetTopItem(self): """ Gets the index of the topmost visible item when in list or report view. """ top, dummy = self._mainWin.GetVisibleLinesRange() return top def GetNextItem(self, item, geometry=ULC_NEXT_ALL, state=ULC_STATE_DONTCARE): """ Searches for an item with the given `geometry` or `state`, starting from `item` but excluding the `item` itself. :param `item`: the item at which starting the search. If set to -1, the first item that matches the specified flags will be returned. :param `geometry`: can be one of: =================== ========= ================================= Geometry Flag Hex Value Description =================== ========= ================================= ``ULC_NEXT_ABOVE`` 0x0 Searches for an item above the specified item ``ULC_NEXT_ALL`` 0x1 Searches for subsequent item by index ``ULC_NEXT_BELOW`` 0x2 Searches for an item below the specified item ``ULC_NEXT_LEFT`` 0x3 Searches for an item to the left of the specified item ``ULC_NEXT_RIGHT`` 0x4 Searches for an item to the right of the specified item =================== ========= ================================= :param `state`: any combination of the following bits: ============================ ========= ============================== State Bits Hex Value Description ============================ ========= ============================== ``ULC_STATE_DONTCARE`` 0x0 Don't care what the state is ``ULC_STATE_DROPHILITED`` 0x1 The item is highlighted to receive a drop event ``ULC_STATE_FOCUSED`` 0x2 The item has the focus ``ULC_STATE_SELECTED`` 0x4 The item is selected ``ULC_STATE_CUT`` 0x8 The item is in the cut state ``ULC_STATE_DISABLED`` 0x10 The item is disabled ``ULC_STATE_FILTERED`` 0x20 The item has been filtered ``ULC_STATE_INUSE`` 0x40 The item is in use ``ULC_STATE_PICKED`` 0x80 The item has been picked ``ULC_STATE_SOURCE`` 0x100 The item is a drag and drop source ============================ ========= ============================== :return: The first item with given state following item or -1 if no such item found. :note: This function may be used to find all selected items in the control like this:: item = -1 while 1: item = listctrl.GetNextItem(item, ULC_NEXT_ALL, ULC_STATE_SELECTED) if item == -1: break # This item is selected - do whatever is needed with it wx.LogMessage("Item %ld is selected."%item) """ return self._mainWin.GetNextItem(item, geometry, state) def GetImageList(self, which): """ Returns the image list associated with the control. :param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``, ``wx.IMAGE_LIST_STATE`` (the last is unimplemented). """ if which == wx.IMAGE_LIST_NORMAL: return self._imageListNormal elif which == wx.IMAGE_LIST_SMALL: return self._imageListSmall elif which == wx.IMAGE_LIST_STATE: return self._imageListState return None def SetImageList(self, imageList, which): """ Sets the image list associated with the control. :param `imageList`: an instance of `wx.ImageList` or an instance of L{PyImageList}; :param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``, ``wx.IMAGE_LIST_STATE`` (the last is unimplemented). :note: Using L{PyImageList} enables you to have images of different size inside the image list. In your derived class, instead of doing this:: imageList = wx.ImageList(16, 16) imageList.Add(someBitmap) self.SetImageList(imageList, wx.IMAGE_LIST_SMALL) You should do this:: imageList = PyImageList(16, 16) imageList.Add(someBitmap) self.SetImageList(imageList, wx.IMAGE_LIST_SMALL) """ if which == wx.IMAGE_LIST_NORMAL: self._imageListNormal = imageList elif which == wx.IMAGE_LIST_SMALL: self._imageListSmall = imageList elif which == wx.IMAGE_LIST_STATE: self._imageListState = imageList self._mainWin.SetImageList(imageList, which) def AssignImageList(self, imageList, which): """ Assigns the image list associated with the control. :param `imageList`: an instance of `wx.ImageList` or an instance of L{PyImageList}; :param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``, ``wx.IMAGE_LIST_STATE`` (the last is unimplemented). :note: Using L{PyImageList} enables you to have images of different size inside the image list. In your derived class, instead of doing this:: imageList = wx.ImageList(16, 16) imageList.Add(someBitmap) self.SetImageList(imageList, wx.IMAGE_LIST_SMALL) You should do this:: imageList = PyImageList(16, 16) imageList.Add(someBitmap) self.SetImageList(imageList, wx.IMAGE_LIST_SMALL) """ self.SetImageList(imageList, which) def Arrange(self, flag): """ Arranges the items in icon or small icon view. :param `flag`: one of the following bits: ========================== ========= =============================== Alignment Flag Hex Value Description ========================== ========= =============================== ``ULC_ALIGN_DEFAULT`` 0x0 Default alignment ``ULC_ALIGN_SNAP_TO_GRID`` 0x3 Snap to grid ========================== ========= =============================== :note: This method is currently unimplemented and does nothing. """ return 0 def DeleteItem(self, item): """ Deletes the specified item. :param `item`: the index of the item to delete. :note: This function sends the ``EVT_LIST_DELETE_ITEM`` event for the item being deleted. """ self._mainWin.DeleteItem(item) return True def DeleteAllItems(self): """ Deletes all items in the L{UltimateListCtrl}. :note: This function does not send the ``EVT_LIST_DELETE_ITEM`` event because deleting many items from the control would be too slow then (unlike L{DeleteItem}). """ self._mainWin.DeleteAllItems() return True def DeleteAllColumns(self): """ Deletes all the column in L{UltimateListCtrl}. """ count = len(self._mainWin._columns) for n in xrange(count): self.DeleteColumn(0) return True def ClearAll(self): """ Deletes everything in L{UltimateListCtrl}. """ self._mainWin.DeleteEverything() def DeleteColumn(self, col): """ Deletes the specified column. :param `col`: the index of the column to delete. """ self._mainWin.DeleteColumn(col) return True def EditLabel(self, item): """ Starts editing an item label. :param `item`: the index of the item to edit. """ self._mainWin.EditLabel(item) def EnsureVisible(self, item): """ Ensures this item is visible. :param `index`: the index of the item to scroll into view. """ self._mainWin.EnsureVisible(item) return True def FindItem(self, start, str, partial=False): """ Find an item whose label matches this string. :param `start`: the starting point of the input `string` or the beginning if `start` is -1; :param `string`: the string to look for matches; :param `partial`: if ``True`` then this method will look for items which begin with `string`. :note: The string comparison is case insensitive. """ return self._mainWin.FindItem(start, str, partial) def FindItemData(self, start, data): """ Find an item whose data matches this data. :param `start`: the starting point of the input `data` or the beginning if `start` is -1; :param `data`: the data to look for matches. """ return self._mainWin.FindItemData(start, data) def FindItemAtPos(self, start, pt, direction): """ Find an item nearest this position. :param `pt`: an instance of `wx.Point`. """ return self._mainWin.FindItemAtPos(pt) def HitTest(self, pointOrTuple): """ HitTest method for a L{UltimateListCtrl}. :param `pointOrTuple`: an instance of `wx.Point` or a tuple representing the mouse x, y position. :see: L{UltimateListMainWindow.HitTestLine} for a list of return flags. """ if isinstance(pointOrTuple, wx.Point): x, y = pointOrTuple.x, pointOrTuple.y else: x, y = pointOrTuple return self._mainWin.HitTest(x, y) def InsertItem(self, info): """ Inserts an item into L{UltimateListCtrl}. :param `info`: an instance of L{UltimateListItem}. """ self._mainWin.InsertItem(info) return info._itemId def InsertStringItem(self, index, label, it_kind=0): """ Inserts a string item at the given location. :param `index`: the index at which we wish to insert the item; :param `label`: the item text; :param `it_kind`: the item kind. :see: L{SetStringItem} for a list of valid item kinds. """ info = UltimateListItem() info._text = label info._mask = ULC_MASK_TEXT if it_kind: info._mask |= ULC_MASK_KIND info._kind = it_kind info._itemId = index return self.InsertItem(info) def InsertImageItem(self, index, imageIds, it_kind=0): """ Inserts an image item at the given location. :param `index`: the index at which we wish to insert the item; :param `imageIds`: a Python list containing the image indexes for the images associated to this item; :param `it_kind`: the item kind. :see: L{SetStringItem} for a list of valid item kinds. """ info = UltimateListItem() info._mask = ULC_MASK_IMAGE if it_kind: info._mask |= ULC_MASK_KIND info._kind = it_kind info._image = to_list(imageIds) info._itemId = index return self.InsertItem(info) def InsertImageStringItem(self, index, label, imageIds, it_kind=0): """ Inserts an image+string item at the given location. :param `index`: the index at which we wish to insert the item; :param `label`: the item text; :param `imageIds`: a Python list containing the image indexes for the images associated to this item; :param `it_kind`: the item kind. :see: L{SetStringItem} for a list of valid item kinds. """ info = UltimateListItem() info._text = label info._image = to_list(imageIds) info._mask = ULC_MASK_TEXT | ULC_MASK_IMAGE if it_kind: info._mask |= ULC_MASK_KIND info._kind = it_kind info._itemId = index return self.InsertItem(info) def InsertColumnInfo(self, col, item): """ Inserts a column into L{UltimateListCtrl}. :param `col`: the column index at which we wish to insert a column; :param `item`: an instance of L{UltimateListItem}. """ if not self._mainWin.InReportView() and not self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS) and \ not self._mainWin.InTileView(): raise Exception("Can't add column in non report/tile modes or without the ULC_HEADER_IN_ALL_VIEWS style set") self._mainWin.InsertColumn(col, item) if self._headerWin: self._headerWin.Refresh() return 0 def InsertColumn(self, col, heading, format=ULC_FORMAT_LEFT, width=-1): """ Inserts a column into L{UltimateListCtrl}. :param `col`: the column index at which we wish to insert a column; :param `heading`: the header text; :param `format`: the column alignment flag. This can be one of the following bits: ============================ ========= ============================== Alignment Bits Hex Value Description ============================ ========= ============================== ``ULC_FORMAT_LEFT`` 0x0 The item is left-aligned ``ULC_FORMAT_RIGHT`` 0x1 The item is right-aligned ``ULC_FORMAT_CENTRE`` 0x2 The item is centre-aligned ``ULC_FORMAT_CENTER`` 0x2 The item is center-aligned ============================ ========= ============================== :param `width`: can be a width in pixels or ``wx.LIST_AUTOSIZE`` (-1) or ``wx.LIST_AUTOSIZE_USEHEADER`` (-2). ``wx.LIST_AUTOSIZE`` will resize the column to the length of its longest item. ``wx.LIST_AUTOSIZE_USEHEADER`` will resize the column to the length of the header (Win32) or 80 pixels (other platforms). """ item = UltimateListItem() item._mask = ULC_MASK_TEXT | ULC_MASK_FORMAT | ULC_MASK_FONT item._text = heading if width >= -2: item._mask |= ULC_MASK_WIDTH item._width = width item._format = format return self.InsertColumnInfo(col, item) def IsColumnShown(self, column): """ Returns ``True`` if the input column is shown, ``False`` if it is hidden. :param `column`: an integer specifying the column index. """ if self._headerWin: return self._mainWin.IsColumnShown(column) raise Exception("Showing/hiding columns works only with the header shown") def SetColumnShown(self, column, shown=True): """ Sets the specified column as shown or hidden. :param `column`: an integer specifying the column index; :param `shown`: ``True`` to show the column, ``False`` to hide it. """ col = self.GetColumn(column) col._mask |= ULC_MASK_SHOWN col.SetShown(shown) self._mainWin.SetColumn(column, col) self.Update() def ScrollList(self, dx, dy): """ Scrolls the L{UltimateListCtrl}. :param `dx`: if in icon, small icon or report view mode, specifies the number of pixels to scroll. If in list view mode, `dx` specifies the number of columns to scroll. :param `dy`: always specifies the number of pixels to scroll vertically. """ return self._mainWin.ScrollList(dx, dy) # Sort items. # The return value is a negative number if the first item should precede the second # item, a positive number of the second item should precede the first, # or zero if the two items are equivalent. def SortItems(self, func=None): """ Call this function to sort the items in the L{UltimateListCtrl}. Sorting is done using the specified function `func`. This function must have the following prototype:: def OnCompareItems(self, line1, line2): DoSomething(line1, line2) # function code It is called each time when the two items must be compared and should return 0 if the items are equal, negative value if the first item is less than the second one and positive value if the first one is greater than the second one. :param `func`: the method to use to sort the items. The default is to use the L{UltimateListMainWindow.OnCompareItems} method. """ self._mainWin.SortItems(func) wx.CallAfter(self.Update) return True # ---------------------------------------------------------------------------- # event handlers # ---------------------------------------------------------------------------- def OnSize(self, event): """ Handles the ``wx.EVT_SIZE`` event for L{UltimateListCtrl}. :param `event`: a `wx.SizeEvent` event to be processed. """ if not self.IsShownOnScreen(): # We don't have the proper column sizes until we are visible so # use CallAfter to resize the columns on the first display if self._mainWin: wx.CallAfter(self._mainWin.ResizeColumns) return if not self._mainWin: return # We need to override OnSize so that our scrolled # window a) does call Layout() to use sizers for # positioning the controls but b) does not query # the sizer for their size and use that for setting # the scrollable area as set that ourselves by # calling SetScrollbar() further down. self.Layout() self._mainWin.ResizeColumns() self._mainWin.ResetVisibleLinesRange(True) self._mainWin.RecalculatePositions() self._mainWin.AdjustScrollbars() if self._headerWin: self._headerWin.Refresh() if self._footerWin: self._footerWin.Refresh() def OnSetFocus(self, event): """ Handles the ``wx.EVT_SET_FOCUS`` event for L{UltimateListCtrl}. :param `event`: a `wx.FocusEvent` event to be processed. """ if self._mainWin: self._mainWin.SetFocusIgnoringChildren() self._mainWin.Update() def OnInternalIdle(self): """ This method is normally only used internally, but sometimes an application may need it to implement functionality that should not be disabled by an application defining an `OnIdle` handler in a derived class. This method may be used to do delayed painting, for example, and most implementations call `wx.Window.UpdateWindowUI` in order to send update events to the window in idle time. """ wx.PyControl.OnInternalIdle(self) # do it only if needed if self._mainWin._dirty: self._mainWin._shortItems = [] self._mainWin.RecalculatePositions() # ---------------------------------------------------------------------------- # font/colours # ---------------------------------------------------------------------------- def SetBackgroundColour(self, colour): """ Changes the background colour of L{UltimateListCtrl}. :param `colour`: the colour to be used as the background colour, pass `wx.NullColour` to reset to the default colour. :note: The background colour is usually painted by the default `wx.EraseEvent` event handler function under Windows and automatically under GTK. :note: Setting the background colour does not cause an immediate refresh, so you may wish to call `wx.Window.ClearBackground` or `wx.Window.Refresh` after calling this function. :note: Overridden from `wx.PyControl`. """ if self._mainWin: self._mainWin.SetBackgroundColour(colour) self._mainWin._dirty = True return True def SetForegroundColour(self, colour): """ Changes the foreground colour of L{UltimateListCtrl}. :param `colour`: the colour to be used as the foreground colour, pass `wx.NullColour` to reset to the default colour. :note: Overridden from `wx.PyControl`. """ if not wx.PyControl.SetForegroundColour(self, colour): return False if self._mainWin: self._mainWin.SetForegroundColour(colour) self._mainWin._dirty = True if self._headerWin: self._headerWin.SetForegroundColour(colour) return True def SetFont(self, font): """ Sets the L{UltimateListCtrl} font. :param `font`: a valid `wx.Font` instance. :note: Overridden from `wx.PyControl`. """ if not wx.PyControl.SetFont(self, font): return False if self._mainWin: self._mainWin.SetFont(font) self._mainWin._dirty = True if self._headerWin: self._headerWin.SetFont(font) self.Refresh() return True def GetClassDefaultAttributes(self, variant): """ Returns the default font and colours which are used by the control. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the users system, especially if it uses themes. This static method is "overridden'' in many derived classes and so calling, for example, `wx.Button.GetClassDefaultAttributes()` will typically return the values appropriate for a button which will be normally different from those returned by, say, `wx.ListCtrl.GetClassDefaultAttributes()`. :note: The `wx.VisualAttributes` structure has at least the fields `font`, `colFg` and `colBg`. All of them may be invalid if it was not possible to determine the default control appearance or, especially for the background colour, if the field doesn't make sense as is the case for `colBg` for the controls with themed background. :note: Overridden from `wx.PyControl`. """ attr = wx.VisualAttributes() attr.colFg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_LISTBOXTEXT) attr.colBg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_LISTBOX) attr.font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT) return attr def GetScrolledWin(self): """ Returns the header window owner. """ return self._headerWin.GetOwner() # ---------------------------------------------------------------------------- # methods forwarded to self._mainWin # ---------------------------------------------------------------------------- def SetDropTarget(self, dropTarget): """ Associates a drop target with this window. If the window already has a drop target, it is deleted. :param `dropTarget`: an instance of `wx.DropTarget`. :note: Overridden from `wx.PyControl`. """ self._mainWin.SetDropTarget(dropTarget) def GetDropTarget(self): """ Returns the associated drop target, which may be ``None``. :note: Overridden from `wx.PyControl`. """ return self._mainWin.GetDropTarget() def SetCursor(self, cursor): """ Sets the window's cursor. :param `cursor`: specifies the cursor that the window should normally display. The `cursor` may be `wx.NullCursor` in which case the window cursor will be reset back to default. :note: The window cursor also sets it for the children of the window implicitly. :note: Overridden from `wx.PyControl`. """ return (self._mainWin and [self._mainWin.SetCursor(cursor)] or [False])[0] def GetBackgroundColour(self): """ Returns the background colour of the window. :note: Overridden from `wx.PyControl`. """ return (self._mainWin and [self._mainWin.GetBackgroundColour()] or [wx.NullColour])[0] def GetForegroundColour(self): """ Returns the foreground colour of the window. :note: Overridden from `wx.PyControl`. """ return (self._mainWin and [self._mainWin.GetForegroundColour()] or [wx.NullColour])[0] def PopupMenu(self, menu, pos=wx.DefaultPosition): """ Pops up the given menu at the specified coordinates, relative to this window, and returns control when the user has dismissed the menu. If a menu item is selected, the corresponding menu event is generated and will be processed as usual. If the coordinates are not specified, the current mouse cursor position is used. :param `menu`: an instance of `wx.Menu` to pop up; :param `pos`: the position where the menu will appear. :note: Overridden from `wx.PyControl`. """ return self._mainWin.PopupMenu(menu, pos) def ClientToScreen(self, x, y): """ Converts to screen coordinates from coordinates relative to this window. :param `x`: an integer specifying the x client coordinate; :param `y`: an integer specifying the y client coordinate. :return: the coordinates relative to the screen. :note: Overridden from `wx.PyControl`. """ return self._mainWin.ClientToScreen(x, y) def ScreenToClient(self, x, y): """ Converts from screen to client window coordinates. :param `x`: an integer specifying the x screen coordinate; :param `y`: an integer specifying the y screen coordinate. :return: the coordinates relative to this window. :note: Overridden from `wx.PyControl`. """ return self._mainWin.ScreenToClient(x, y) def SetFocus(self): """ This sets the window to receive keyboard input. """ # The test in window.cpp fails as we are a composite # window, so it checks against "this", but not self._mainWin. if wx.Window.FindFocus() != self: self._mainWin.SetFocusIgnoringChildren() def DoGetBestSize(self): """ Gets the size which best suits the window: for a control, it would be the minimal size which doesn't truncate the control, for a panel - the same size as it would have after a call to `Fit()`. """ # Something is better than nothing... # 100x80 is what the MSW version will get from the default # wx.Control.DoGetBestSize return wx.Size(100, 80) # ---------------------------------------------------------------------------- # virtual list control support # ---------------------------------------------------------------------------- def OnGetItemText(self, item, col): """ This function **must** be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style. It should return the string containing the text of the given column for the specified item. :param `item`: an integer specifying the item index; :param `col`: the column index to which the item belongs to. """ # this is a pure virtual function, in fact - which is not really pure # because the controls which are not virtual don't need to implement it raise Exception("UltimateListCtrl.OnGetItemText not supposed to be called") def OnGetItemImage(self, item): """ This function **must** be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style having an image list (if the control doesn't have an image list, it is not necessary to overload it). It should return a Python list of indexes representing the images associated to the input item or an empty list for no images. :param `item`: an integer specifying the item index; :note: In a control with ``ULC_REPORT`` style, L{OnGetItemImage} only gets called for the first column of each line. :note: The base class version always returns an empty Python list. """ if self.GetImageList(wx.IMAGE_LIST_SMALL): raise Exception("List control has an image list, OnGetItemImage should be overridden.") return [] def OnGetItemColumnImage(self, item, column=0): """ This function **must** be overloaded in the derived class for a control with ``ULC_VIRTUAL`` and ``ULC_REPORT`` style. It should return a Python list of indexes representing the images associated to the input item or an empty list for no images. :param `item`: an integer specifying the item index. :note: The base class version always returns an empty Python list. """ if column == 0: return self.OnGetItemImage(item) return [] def OnGetItemAttr(self, item): """ This function may be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style. It should return the attribute for the specified item or ``None`` to use the default appearance parameters. :param `item`: an integer specifying the item index. :note: L{UltimateListCtrl} will not delete the pointer or keep a reference of it. You can return the same L{UltimateListItemAttr} pointer for every L{OnGetItemAttr} call. :note: The base class version always returns ``None``. """ if item < 0 or item > self.GetItemCount(): raise Exception("Invalid item index in OnGetItemAttr()") # no attributes by default return None def OnGetItemCheck(self, item): """ This function may be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style. It should return whether a checkbox-like item or a radiobutton-like item is checked or unchecked. :param `item`: an integer specifying the item index. :note: The base class version always returns an empty list. """ return [] def OnGetItemColumnCheck(self, item, column=0): """ This function **must** be overloaded in the derived class for a control with ``ULC_VIRTUAL`` and ``ULC_REPORT`` style. It should return whether a checkbox-like item or a radiobutton-like item in the column header is checked or unchecked. :param `item`: an integer specifying the item index. :note: The base class version always returns an empty Python list. """ if column == 0: return self.OnGetItemCheck(item) return [] def OnGetItemKind(self, item): """ This function **must** be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style. It should return the item kind for the input item. :param `item`: an integer specifying the item index. :note: The base class version always returns 0 (a standard item). :see: L{SetItemKind} for a list of valid item kinds. """ return 0 def OnGetItemColumnKind(self, item, column=0): """ This function **must** be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style. It should return the item kind for the input item in the header window. :param `item`: an integer specifying the item index; :param `column`: the column index. :note: The base class version always returns 0 (a standard item). :see: L{SetItemKind} for a list of valid item kinds. """ if column == 0: return self.OnGetItemKind(item) return 0 def SetItemCount(self, count): """ Sets the total number of items we handle. :param `count`: the total number of items we handle. """ if not self._mainWin.IsVirtual(): raise Exception("This is for virtual controls only") self._mainWin.SetItemCount(count) def RefreshItem(self, item): """ Redraws the given item. :param `item`: an integer specifying the item index; :note: This is only useful for the virtual list controls as without calling this function the displayed value of the item doesn't change even when the underlying data does change. """ self._mainWin.RefreshLine(item) def RefreshItems(self, itemFrom, itemTo): """ Redraws the items between `itemFrom` and `itemTo`. The starting item must be less than or equal to the ending one. Just as L{RefreshItem} this is only useful for virtual list controls :param `itemFrom`: the first index of the refresh range; :param `itemTo`: the last index of the refresh range. """ self._mainWin.RefreshLines(itemFrom, itemTo) # # Generic UltimateListCtrl is more or less a container for two other # windows which drawings are done upon. These are namely # 'self._headerWin' and 'self._mainWin'. # Here we override 'virtual wxWindow::Refresh()' to mimic the # behaviour UltimateListCtrl has under wxMSW. # def Refresh(self, eraseBackground=True, rect=None): """ Causes this window, and all of its children recursively (except under wxGTK1 where this is not implemented), to be repainted. :param `eraseBackground`: If ``True``, the background will be erased; :param `rect`: If not ``None``, only the given rectangle will be treated as damaged. :note: Note that repainting doesn't happen immediately but only during the next event loop iteration, if you need to update the window immediately you should use L{Update} instead. :note: Overridden from `wx.PyControl`. """ if not rect: # The easy case, no rectangle specified. if self._headerWin: self._headerWin.Refresh(eraseBackground) if self._mainWin: self._mainWin.Refresh(eraseBackground) else: # Refresh the header window if self._headerWin: rectHeader = self._headerWin.GetRect() rectHeader.Intersect(rect) if rectHeader.GetWidth() and rectHeader.GetHeight(): x, y = self._headerWin.GetPosition() rectHeader.OffsetXY(-x, -y) self._headerWin.Refresh(eraseBackground, rectHeader) # Refresh the main window if self._mainWin: rectMain = self._mainWin.GetRect() rectMain.Intersect(rect) if rectMain.GetWidth() and rectMain.GetHeight(): x, y = self._mainWin.GetPosition() rectMain.OffsetXY(-x, -y) self._mainWin.Refresh(eraseBackground, rectMain) def Update(self): """ Calling this method immediately repaints the invalidated area of the window and all of its children recursively while this would usually only happen when the flow of control returns to the event loop. :note: This function doesn't invalidate any area of the window so nothing happens if nothing has been invalidated (i.e. marked as requiring a redraw). Use L{Refresh} first if you want to immediately redraw the window unconditionally. :note: Overridden from `wx.PyControl`. """ self._mainWin.ResetVisibleLinesRange(True) wx.PyControl.Update(self) def GetEditControl(self): """ Returns a pointer to the edit L{UltimateListTextCtrl} if the item is being edited or ``None`` otherwise (it is assumed that no more than one item may be edited simultaneously). """ retval = None if self._mainWin: retval = self._mainWin.GetEditControl() return retval def Select(self, idx, on=True): """ Selects/deselects an item. :param `idx`: the index of the item to select; :param `on`: ``True`` to select the item, ``False`` to deselect it. """ item = CreateListItem(idx, 0) item = self._mainWin.GetItem(item, 0) if not item.IsEnabled(): return if on: state = ULC_STATE_SELECTED else: state = 0 self.SetItemState(idx, state, ULC_STATE_SELECTED) def Focus(self, idx): """ Focus and show the given item. :param `idx`: the index of the item to be focused. """ self.SetItemState(idx, ULC_STATE_FOCUSED, ULC_STATE_FOCUSED) self.EnsureVisible(idx) def GetFocusedItem(self): """ Returns the currently focused item or -1 if none is focused. """ return self.GetNextItem(-1, ULC_NEXT_ALL, ULC_STATE_FOCUSED) def GetFirstSelected(self, *args): """ Return first selected item, or -1 when none is selected. """ return self.GetNextSelected(-1) def GetNextSelected(self, item): """ Returns subsequent selected items, or -1 when no more are selected. :param `item`: the index of the item. """ return self.GetNextItem(item, ULC_NEXT_ALL, ULC_STATE_SELECTED) def IsSelected(self, idx): """ Returns ``True`` if the item is selected. :param `idx`: the index of the item to check for selection. """ return (self.GetItemState(idx, ULC_STATE_SELECTED) & ULC_STATE_SELECTED) != 0 def IsItemChecked(self, itemOrId, col=0): """ Returns whether an item is checked or not. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to. """ item = CreateListItem(itemOrId, col) return self._mainWin.IsItemChecked(item) def IsItemEnabled(self, itemOrId, col=0): """ Returns whether an item is enabled or not. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to. """ item = CreateListItem(itemOrId, col) return self._mainWin.IsItemEnabled(item) def GetItemKind(self, itemOrId, col=0): """ Returns the item kind. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to. :see: L{SetItemKind} for a list of valid item kinds. """ item = CreateListItem(itemOrId, col) return self._mainWin.GetItemKind(item) def SetItemKind(self, itemOrId, col=0, kind=0): """ Sets the item kind. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to; :param `kind`: may be one of the following integers: =============== ========================== Item Kind Description =============== ========================== 0 A normal item 1 A checkbox-like item 2 A radiobutton-type item =============== ========================== """ item = CreateListItem(itemOrId, col) return self._mainWin.SetItemKind(item, kind) def EnableItem(self, itemOrId, col=0, enable=True): """ Enables/disables an item. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to; :param `enable`: ``True`` to enable the item, ``False`` otherwise. """ item = CreateListItem(itemOrId, col) return self._mainWin.EnableItem(item, enable) def IsItemHyperText(self, itemOrId, col=0): """ Returns whether an item is hypertext or not. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to. """ item = CreateListItem(itemOrId, col) return self._mainWin.IsItemHyperText(item) def SetItemHyperText(self, itemOrId, col=0, hyper=True): """ Sets whether the item is hypertext or not. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to; :param `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise. """ item = CreateListItem(itemOrId, col) return self._mainWin.SetItemHyperText(item, hyper) def SetColumnImage(self, col, image): """ Sets one or more images to the specified column. :param `col`: the column index; :param `image`: a Python list containing the image indexes for the images associated to this column item. """ item = self.GetColumn(col) # preserve all other attributes too item.SetMask(ULC_MASK_STATE | ULC_MASK_TEXT | ULC_MASK_IMAGE | ULC_MASK_DATA | ULC_SET_ITEM | ULC_MASK_WIDTH | ULC_MASK_FORMAT | ULC_MASK_FONTCOLOUR | ULC_MASK_FONT | ULC_MASK_BACKCOLOUR | ULC_MASK_KIND | ULC_MASK_CHECK ) item.SetImage(image) self.SetColumn(col, item) def ClearColumnImage(self, col): """ Clears all the images in the specified column. :param `col`: the column index; """ self.SetColumnImage(col, -1) def Append(self, entry): """ Append an item to the L{UltimateListCtrl}. :param `entry`: should be a sequence with an item for each column. """ if entry: if wx.USE_UNICODE: cvtfunc = unicode else: cvtfunc = str pos = self.GetItemCount() self.InsertStringItem(pos, cvtfunc(entry[0])) for i in range(1, len(entry)): self.SetStringItem(pos, i, cvtfunc(entry[i])) return pos def SetFirstGradientColour(self, colour=None): """ Sets the first gradient colour for gradient-style selections. :param `colour`: if not ``None``, a valid `wx.Colour` instance. Otherwise, the colour is taken from the system value ``wx.SYS_COLOUR_HIGHLIGHT``. """ self._mainWin.SetFirstGradientColour(colour) def SetSecondGradientColour(self, colour=None): """ Sets the second gradient colour for gradient-style selections. :param `colour`: if not ``None``, a valid `wx.Colour` instance. Otherwise, the colour generated is a slightly darker version of the L{UltimateListCtrl} background colour. """ self._mainWin.SetSecondGradientColour(colour) def GetFirstGradientColour(self): """ Returns the first gradient colour for gradient-style selections. """ return self._mainWin.GetFirstGradientColour() def GetSecondGradientColour(self): """ Returns the second gradient colour for gradient-style selections. """ return self._mainWin.GetSecondGradientColour() def EnableSelectionGradient(self, enable=True): """ Globally enables/disables drawing of gradient selections. :param `enable`: ``True`` to enable gradient-style selections, ``False`` to disable it. :note: Calling this method disables any Vista-style selection previously enabled. """ self._mainWin.EnableSelectionGradient(enable) def SetGradientStyle(self, vertical=0): """ Sets the gradient style for gradient-style selections. :param `vertical`: 0 for horizontal gradient-style selections, 1 for vertical gradient-style selections. """ self._mainWin.SetGradientStyle(vertical) def GetGradientStyle(self): """ Returns the gradient style for gradient-style selections. :return: 0 for horizontal gradient-style selections, 1 for vertical gradient-style selections. """ return self._mainWin.GetGradientStyle() def EnableSelectionVista(self, enable=True): """ Globally enables/disables drawing of Windows Vista selections. :param `enable`: ``True`` to enable Vista-style selections, ``False`` to disable it. :note: Calling this method disables any gradient-style selection previously enabled. """ self._mainWin.EnableSelectionVista(enable) def SetBackgroundImage(self, image=None): """ Sets the L{UltimateListCtrl} background image. :param `image`: if not ``None``, an instance of `wx.Bitmap`. :note: At present, the background image can only be used in "tile" mode. :todo: Support background images also in stretch and centered modes. """ self._mainWin.SetBackgroundImage(image) def GetBackgroundImage(self): """ Returns the L{UltimateListCtrl} background image (if any). :note: At present, the background image can only be used in "tile" mode. :todo: Support background images also in stretch and centered modes. """ return self._mainWin.GetBackgroundImage() def SetWaterMark(self, watermark=None): """ Sets the L{UltimateListCtrl} watermark image to be displayed in the bottom right part of the window. :param `watermark`: if not ``None``, an instance of `wx.Bitmap`. :todo: Better support for this is needed. """ self._mainWin.SetWaterMark(watermark) def GetWaterMark(self): """ Returns the L{UltimateListCtrl} watermark image (if any), displayed in the bottom right part of the window. :todo: Better support for this is needed. """ return self._mainWin.GetWaterMark() def SetDisabledTextColour(self, colour): """ Sets the items disabled colour. :param `colour`: an instance of `wx.Colour`. """ self._mainWin.SetDisabledTextColour(colour) def GetDisabledTextColour(self): """ Returns the items disabled colour. """ return self._mainWin.GetDisabledTextColour() def GetHyperTextFont(self): """ Returns the font used to render an hypertext item. """ return self._mainWin.GetHyperTextFont() def SetHyperTextFont(self, font): """ Sets the font used to render hypertext items. :param `font`: a valid `wx.Font` instance. """ self._mainWin.SetHyperTextFont(font) def SetHyperTextNewColour(self, colour): """ Sets the colour used to render a non-visited hypertext item. :param `colour`: a valid `wx.Colour` instance. """ self._mainWin.SetHyperTextNewColour(colour) def GetHyperTextNewColour(self): """ Returns the colour used to render a non-visited hypertext item. """ return self._mainWin.GetHyperTextNewColour() def SetHyperTextVisitedColour(self, colour): """ Sets the colour used to render a visited hypertext item. :param `colour`: a valid `wx.Colour` instance. """ self._mainWin.SetHyperTextVisitedColour(colour) def GetHyperTextVisitedColour(self): """ Returns the colour used to render a visited hypertext item. """ return self._mainWin.GetHyperTextVisitedColour() def SetItemVisited(self, itemOrId, col=0, visited=True): """ Sets whether an hypertext item was visited or not. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to; :param `visited`: ``True`` to mark an hypertext item as visited, ``False`` otherwise. """ item = CreateListItem(itemOrId, col) return self._mainWin.SetItemVisited(item, visited) def GetItemVisited(self, itemOrId, col=0): """ Returns whether an hypertext item was visited. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to. """ item = CreateListItem(itemOrId, col) return self._mainWin.GetItemVisited(item) def GetItemWindow(self, itemOrId, col=0): """ Returns the window associated to the item (if any). :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to. """ item = CreateListItem(itemOrId, col) return self._mainWin.GetItemWindow(item) def SetItemWindow(self, itemOrId, col=0, wnd=None, expand=False): """ Sets the window for the given item. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to; :param `wnd`: a non-toplevel window to be displayed next to the item; :param `expand`: ``True`` to expand the column where the item/subitem lives, so that the window will be fully visible. """ item = CreateListItem(itemOrId, col) return self._mainWin.SetItemWindow(item, wnd, expand) def DeleteItemWindow(self, itemOrId, col=0): """ Deletes the window associated to an item (if any). :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to. """ item = CreateListItem(itemOrId, col) return self._mainWin.DeleteItemWindow(item) def GetItemWindowEnabled(self, itemOrId, col=0): """ Returns whether the window associated to the item is enabled. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to; """ item = CreateListItem(itemOrId, col) return self._mainWin.GetItemWindowEnabled(item) def SetItemWindowEnabled(self, itemOrId, col=0, enable=True): """ Enables/disables the window associated to the item. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to; :param `enable`: ``True`` to enable the associated window, ``False`` to disable it. """ item = CreateListItem(itemOrId, col) return self._mainWin.SetItemWindowEnabled(item, enable) def GetItemCustomRenderer(self, itemOrId, col=0): """ Returns the custom renderer used to draw the input item (if any). :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to. """ item = CreateListItem(itemOrId, col) return self._mainWin.GetItemCustomRenderer(item) def SetHeaderCustomRenderer(self, renderer=None): """ Associate a custom renderer with the header - all columns will use it. :param `renderer`: a class able to correctly render header buttons :note: the renderer class **must** implement the methods `DrawHeaderButton`, and `GetForegroundColor`. """ if not self.HasAGWFlag(ULC_REPORT): raise Exception("Custom renderers can be used on with style = ULC_REPORT") self._headerWin.SetCustomRenderer(renderer) def SetFooterCustomRenderer(self, renderer=None): """ Associate a custom renderer with the footer - all columns will use it. :param `renderer`: a class able to correctly render header buttons :note: the renderer class **must** implement the methods `DrawHeaderButton`, and `GetForegroundColor`. """ if not self.HasAGWFlag(ULC_REPORT) or not self.HasAGWFlag(ULC_FOOTER): raise Exception("Custom renderers can only be used on with style = ULC_REPORT | ULC_FOOTER") self._footerWin.SetCustomRenderer(renderer) def SetColumnCustomRenderer(self, col=0, renderer=None): """ Associate a custom renderer to this column's header. :param `col`: the column index. :param `renderer`: a class able to correctly render the input item. :note: the renderer class **must** implement the methods `DrawHeaderButton`, and `GetForegroundColor`. """ if not self.HasAGWFlag(ULC_REPORT): raise Exception("Custom renderers can be used on with style = ULC_REPORT") return self._mainWin.SetCustomRenderer(col, renderer) def SetItemCustomRenderer(self, itemOrId, col=0, renderer=None): """ Associate a custom renderer to this item. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to; :param `renderer`: a class able to correctly render the input item. :note: the renderer class **must** implement the methods `DrawSubItem`, `GetLineHeight` and `GetSubItemWidth`. """ if not self.HasAGWFlag(ULC_REPORT) or not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT): raise Exception("Custom renderers can be used on with style = ULC_REPORT | ULC_HAS_VARIABLE_ROW_HEIGHT") item = CreateListItem(itemOrId, col) return self._mainWin.SetItemCustomRenderer(item, renderer) def SetItemOverFlow(self, itemOrId, col=0, over=True): """ Sets the item in the overflow/non overflow state. An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to; :param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise. """ if not self.HasAGWFlag(ULC_REPORT) or self._mainWin.IsVirtual(): raise Exception("Overflowing items can be used only in report, non-virtual mode") item = CreateListItem(itemOrId, col) return self._mainWin.SetItemOverFlow(item, over) def GetItemOverFlow(self, itemOrId, col=0): """ Returns if the item is in the overflow state. An item/subitem may overwrite neighboring items/subitems if its text would not normally fit in the space allotted to it. :param `itemOrId`: an instance of L{UltimateListItem} or the item index; :param `col`: the column index to which the input item belongs to. """ item = CreateListItem(itemOrId, col) return self._mainWin.GetItemOverFlow(item) def IsVirtual(self): """ Returns ``True`` if the L{UltimateListCtrl} has the ``ULC_VIRTUAL`` style set. """ return self._mainWin.IsVirtual() def GetScrollPos(self): """ Returns the scrollbar position. :note: This method is forwarded to L{UltimateListMainWindow}. """ if self._mainWin: return self._mainWin.GetScrollPos() return 0 def SetScrollPos(self, orientation, pos, refresh=True): """ Sets the scrollbar position. :param `orientation`: determines the scrollbar whose position is to be set. May be ``wx.HORIZONTAL`` or ``wx.VERTICAL``; :param `pos`: the scrollbar position in scroll units; :param `refresh`: ``True`` to redraw the scrollbar, ``False`` otherwise. :note: This method is forwarded to L{UltimateListMainWindow}. """ if self._mainWin: self._mainWin.SetScrollPos(orientation, pos, refresh) def GetScrollThumb(self): """ Returns the scrollbar size in pixels. :note: This method is forwarded to L{UltimateListMainWindow}. """ if self._mainWin: return self._mainWin.GetScrollThumb() return 0 def GetScrollRange(self): """ Returns the scrollbar range in pixels. :note: This method is forwarded to L{UltimateListMainWindow}. """ if self._mainWin: return self._mainWin.GetScrollRange() return 0
djgagne/scikit-learn
refs/heads/master
sklearn/externals/joblib/_memory_helpers.py
303
try: # Available in Python 3 from tokenize import open as open_py_source except ImportError: # Copied from python3 tokenize from codecs import lookup, BOM_UTF8 import re from io import TextIOWrapper, open cookie_re = re.compile("coding[:=]\s*([-\w.]+)") def _get_normal_name(orig_enc): """Imitates get_normal_name in tokenizer.c.""" # Only care about the first 12 characters. enc = orig_enc[:12].lower().replace("_", "-") if enc == "utf-8" or enc.startswith("utf-8-"): return "utf-8" if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \ enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")): return "iso-8859-1" return orig_enc def _detect_encoding(readline): """ The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argment, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (left as bytes) it has read in. It detects the encoding from the presence of a utf-8 bom or an encoding cookie as specified in pep-0263. If both a bom and a cookie are present, but disagree, a SyntaxError will be raised. If the encoding cookie is an invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found, 'utf-8-sig' is returned. If no encoding is specified, then the default of 'utf-8' will be returned. """ bom_found = False encoding = None default = 'utf-8' def read_or_stop(): try: return readline() except StopIteration: return b'' def find_cookie(line): try: line_string = line.decode('ascii') except UnicodeDecodeError: return None matches = cookie_re.findall(line_string) if not matches: return None encoding = _get_normal_name(matches[0]) try: codec = lookup(encoding) except LookupError: # This behaviour mimics the Python interpreter raise SyntaxError("unknown encoding: " + encoding) if bom_found: if codec.name != 'utf-8': # This behaviour mimics the Python interpreter raise SyntaxError('encoding problem: utf-8') encoding += '-sig' return encoding first = read_or_stop() if first.startswith(BOM_UTF8): bom_found = True first = first[3:] default = 'utf-8-sig' if not first: return default, [] encoding = find_cookie(first) if encoding: return encoding, [first] second = read_or_stop() if not second: return default, [first] encoding = find_cookie(second) if encoding: return encoding, [first, second] return default, [first, second] def open_py_source(filename): """Open a file in read only mode using the encoding detected by detect_encoding(). """ buffer = open(filename, 'rb') encoding, lines = _detect_encoding(buffer.readline) buffer.seek(0) text = TextIOWrapper(buffer, encoding, line_buffering=True) text.mode = 'r' return text
hemmerling/codingdojo
refs/heads/master
src/game_of_life/python_coderetreat_socramob/cr_socramob01/pyunit/widgettests.py
3
#!/usr/bin/env python # # Unit tests for Widgets. Some of these tests intentionally fail. # # $Id: widgettests.py,v 1.8 2001/08/06 09:10:00 purcell Exp $ from widget import Widget import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget("The widget") def tearDown(self): self.widget.dispose() self.widget = None def testDefaultSize(self): assert self.widget.size() == (50,50), 'incorrect default size' def testResize(self): """Resizing of widgets Docstrings for test methods are used as the short description of the test when it is run. Only the first line is printed. """ # This is how to check that an expected exception really *is* thrown: self.assertRaises(ValueError, self.widget.resize, 0,0) self.widget.resize(100,150) assert self.widget.size() == (100,150), \ 'wrong size after resize' # Fancy way to build a suite class WidgetTestSuite(unittest.TestSuite): def __init__(self): unittest.TestSuite.__init__(self,map(WidgetTestCase, ("testDefaultSize", "testResize"))) # Simpler way def makeWidgetTestSuite(): suite = unittest.TestSuite() suite.addTest(WidgetTestCase("testDefaultSize")) suite.addTest(WidgetTestCase("testResize")) return suite def suite(): return unittest.makeSuite(WidgetTestCase) # Make this test module runnable from the command prompt if __name__ == "__main__": #unittest.main(defaultTest="WidgetTestCase:testResize") unittest.main()
mozilla/rna
refs/heads/master
rna/fields.py
1
from django import forms from django.utils.dateparse import parse_datetime class ISO8601DateTimeField(forms.DateTimeField): def strptime(self, value, format): return parse_datetime(value)
tsgit/invenio
refs/heads/prod
modules/websubmit/lib/functions/Print_Success_MBI.py
39
## This file is part of Invenio. ## Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. __revision__ = "$Id$" from invenio.config import \ CFG_SITE_NAME ## Description: function Print_Success_MBI ## This function displays a message telling the user the ## modification has been taken into account ## Author: T.Baron ## PARAMETERS: - def Print_Success_MBI(parameters, curdir, form, user_info=None): """ This function simply displays a text on the screen, telling the user the modification went fine. To be used in the Modify Record (MBI) action. """ global rn t="<b>Modification completed!</b><br /><br />" t+="These modifications on document %s will be processed as quickly as possible and made <br />available on the %s Server</b>" % (rn, CFG_SITE_NAME) return t
ubc/edx-platform
refs/heads/release
lms/djangoapps/discussion_api/tests/test_render.py
154
""" Tests for content rendering """ from unittest import TestCase import ddt from discussion_api.render import render_body def _add_p_tags(raw_body): """Return raw_body surrounded by p tags""" return "<p>{raw_body}</p>".format(raw_body=raw_body) @ddt.ddt class RenderBodyTest(TestCase): """Tests for render_body""" def test_empty(self): self.assertEqual(render_body(""), "") @ddt.data( ("*", "em"), ("**", "strong"), ("`", "code"), ) @ddt.unpack def test_markdown_inline(self, delimiter, tag): self.assertEqual( render_body("{delimiter}some text{delimiter}".format(delimiter=delimiter)), "<p><{tag}>some text</{tag}></p>".format(tag=tag) ) @ddt.data( "b", "blockquote", "code", "del", "dd", "dl", "dt", "em", "h1", "h2", "h3", "i", "kbd", "li", "ol", "p", "pre", "s", "sup", "sub", "strong", "strike", "ul" ) def test_openclose_tag(self, tag): raw_body = "<{tag}>some text</{tag}>".format(tag=tag) is_inline_tag = tag in ["b", "code", "del", "em", "i", "kbd", "s", "sup", "sub", "strong", "strike"] rendered_body = _add_p_tags(raw_body) if is_inline_tag else raw_body self.assertEqual(render_body(raw_body), rendered_body) @ddt.data("br", "hr") def test_selfclosing_tag(self, tag): raw_body = "<{tag}>".format(tag=tag) is_inline_tag = tag == "br" rendered_body = _add_p_tags(raw_body) if is_inline_tag else raw_body self.assertEqual(render_body(raw_body), rendered_body) @ddt.data("http", "https", "ftp") def test_allowed_a_tag(self, protocol): raw_body = '<a href="{protocol}://foo" title="bar">baz</a>'.format(protocol=protocol) self.assertEqual(render_body(raw_body), _add_p_tags(raw_body)) def test_disallowed_a_tag(self): raw_body = '<a href="gopher://foo">link content</a>' self.assertEqual(render_body(raw_body), "<p>link content</p>") @ddt.data("http", "https") def test_allowed_img_tag(self, protocol): raw_body = '<img src="{protocol}://foo" width="111" height="222" alt="bar" title="baz">'.format( protocol=protocol ) self.assertEqual(render_body(raw_body), _add_p_tags(raw_body)) def test_disallowed_img_tag(self): raw_body = '<img src="gopher://foo">' self.assertEqual(render_body(raw_body), "<p></p>") def test_script_tag(self): raw_body = '<script type="text/javascript">alert("evil script");</script>' self.assertEqual(render_body(raw_body), 'alert("evil script");') @ddt.data("p", "br", "li", "hr") # img is tested above def test_allowed_unpaired_tags(self, tag): raw_body = "foo<{tag}>bar".format(tag=tag) self.assertEqual(render_body(raw_body), _add_p_tags(raw_body)) def test_unpaired_start_tag(self): self.assertEqual(render_body("foo<i>bar"), "<p>foobar</p>") def test_unpaired_end_tag(self): self.assertEqual(render_body("foo</i>bar"), "<p>foobar</p>") def test_interleaved_tags(self): self.assertEqual( render_body("foo<i>bar<b>baz</i>quux</b>greg"), "<p>foo<i>barbaz</i>quuxgreg</p>" )
alianmohammad/pd-gem5-latest
refs/heads/master
src/arch/x86/isa/insts/simd64/integer/data_reordering/shuffle_and_swap.py
91
# Copyright (c) 2007 The Hewlett-Packard Development Company # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Gabe Black microcode = ''' def macroop PSHUFW_MMX_MMX_I { shuffle mmx, mmxm, mmxm, size=2, ext=imm }; def macroop PSHUFW_MMX_M_I { ldfp ufp1, seg, sib, disp, dataSize=8 shuffle mmx, ufp1, ufp1, size=2, ext=imm }; def macroop PSHUFW_MMX_P_I { rdip t7 ldfp ufp1, seg, riprel, disp, dataSize=8 shuffle mmx, ufp1, ufp1, size=2, ext=imm }; ''' # PSWAPD
tinyx/crabfactory
refs/heads/master
todolist/forms.py
1
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class TodoUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username', 'password1', 'password2', 'email')
xifle/greensd
refs/heads/master
lib/greensd/plugins/fsck.py
1
import greensd.plugin import greensd.logger import subprocess class fsck(greensd.plugin.Plugin): checkDone = False def isIdlePlugin(self): return True def _cleanup(self): # reload smb and mythtv-backend subprocess.call(['mount', '/home']) subprocess.call(['service', 'mythtv-backend', 'start']) subprocess.call(['service', 'smbd', 'start']) def idle(self, time): # do we have enough time? (2 hrs) if time < 7200 || self.checkDone: return False greensd.logger.logInfo("Executing fsck...") # okay, let's check the filesystem # stop mythtv daemon and smb daemon try: subprocess.check_call(['service', 'mythtv-backend', 'stop']) subprocess.check_call(['service', 'smbd', 'stop']) # unmount disk subprocess.check_call(['umount', '/home']) # check fs subprocess.check_call(["fsck", "-pfc", "/dev/sda3"]) self.checkDone = True greensd.logger.logInfo("...fsck executed") # cleanup self._cleanup() except Exception: self._cleanup() return True
Santei/django-profile
refs/heads/master
userprofile/views.py
8
from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.utils.translation import ugettext as _ from userprofile.forms import AvatarForm, AvatarCropForm, EmailValidationForm, \ ProfileForm, _RegistrationForm, LocationForm, \ ResendEmailValidationForm, PublicFieldsForm from userprofile.models import BaseProfile, DEFAULT_AVATAR_SIZE, MIN_AVATAR_SIZE, \ SAVE_IMG_PARAMS, DEFAULT_AVATAR from django.http import Http404 from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse from django.utils import simplejson from django.db import models from django.contrib.auth.models import User, SiteProfileNotAvailable from userprofile.models import EmailValidation, Avatar, UserProfileMediaNotFound, \ GoogleDataAPINotFound, S3BackendNotFound from django.template import RequestContext from cStringIO import StringIO from django.core.files.base import ContentFile import urlparse from django.conf import settings from xml.dom import minidom import urllib2 import random import cPickle as pickle import base64 import urllib import os from userprofile import signals import copy from django.contrib import messages from django.utils.encoding import iri_to_uri if hasattr(settings, "AWS_SECRET_ACCESS_KEY"): from backends.S3Storage import S3Storage if hasattr(settings, "AVATAR_QUOTA"): from userprofile.uploadhandler import QuotaUploadHandler try: from PIL import Image except ImportError: import Image if not settings.AUTH_PROFILE_MODULE: raise SiteProfileNotAvailable try: app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.') Profile = models.get_model(app_label, model_name) except (ImportError, ImproperlyConfigured): raise SiteProfileNotAvailable if not Profile: raise SiteProfileNotAvailable if not os.path.isdir(os.path.join(settings.MEDIA_ROOT, "userprofile")): raise UserProfileMediaNotFound GOOGLE_MAPS_API_KEY = hasattr(settings, "GOOGLE_MAPS_API_KEY") and \ settings.GOOGLE_MAPS_API_KEY or None AVATAR_WEBSEARCH = hasattr(settings, "AVATAR_WEBSEARCH") and \ settings.AVATAR_WEBSEARCH or None if AVATAR_WEBSEARCH: try: import gdata.service import gdata.photos.service except: raise GoogleDataAPINotFound def get_profiles(): return Profile.objects.order_by("-creation_date") def fetch_geodata(request, lat, lng): if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': url = "http://ws.geonames.org/countrySubdivision?lat=%s&lng=%s" % (lat, lng) dom = minidom.parse(urllib.urlopen(url)) country = dom.getElementsByTagName('countryCode') if len(country) >=1: country = country[0].childNodes[0].data region = dom.getElementsByTagName('adminName1') if len(region) >=1: region = region[0].childNodes[0].data return HttpResponse(simplejson.dumps({'success': True, 'country': country, 'region': region})) else: raise Http404() def public(request, username): try: profile = User.objects.get(username=username).get_profile() except: raise Http404 template = "userprofile/profile/public.html" data = { 'profile': profile, 'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY, 'DEFAULT_AVATAR_SIZE': DEFAULT_AVATAR_SIZE } signals.context_signal.send(sender=public, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request)) @login_required def overview(request): """ Main profile page """ profile, created = Profile.objects.get_or_create(user=request.user) validated = False try: email = EmailValidation.objects.exclude(verified=True).get(user=request.user).email except EmailValidation.DoesNotExist: email = request.user.email if email: validated = True fields = [{ 'name': f.name, 'verbose_name': f.verbose_name, 'value': getattr(profile, f.name) } for f in Profile._meta.fields if not (f in BaseProfile._meta.fields or f.name=='id')] template = "userprofile/profile/overview.html" data = { 'section': 'overview', 'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY, 'email': email, 'validated': validated, 'fields' : fields, 'DEFAULT_AVATAR_SIZE': DEFAULT_AVATAR_SIZE } signals.context_signal.send(sender=overview, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request)) @login_required def personal(request): """ Personal data of the user profile """ profile, created = Profile.objects.get_or_create(user=request.user) if request.method == "POST": old_profile = copy.copy(profile) form = ProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() messages.success(request, _("Your profile information has been updated successfully."), fail_silently=True) signal_responses = signals.post_signal.send(sender=personal, request=request, form=form, extra={'old_profile':old_profile}) last_response = signals.last_response(signal_responses) if last_response: return last_response else: form = ProfileForm(instance=profile) template = "userprofile/profile/personal.html" data = { 'section': 'personal', 'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY, 'form': form, } signals.context_signal.send(sender=personal, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request)) @login_required def location(request): """ Location selection of the user profile """ profile, created = Profile.objects.get_or_create(user=request.user) geoip = hasattr(settings, "GEOIP_PATH") if geoip and request.method == "GET" and request.GET.get('ip') == "1": from django.contrib.gis.utils import GeoIP g = GeoIP() c = g.city(request.META.get("REMOTE_ADDR")) if c and c.get("latitude") and c.get("longitude"): profile.latitude = "%.6f" % c.get("latitude") profile.longitude = "%.6f" % c.get("longitude") profile.country = c.get("country_code") profile.location = unicode(c.get("city"), "latin1") if request.method == "POST": form = LocationForm(request.POST, instance=profile) if form.is_valid(): form.save() messages.success(request, _("Your profile information has been updated successfully."), fail_silently=True) signal_responses = signals.post_signal.send(sender=location, request=request, form=form) last_response = signals.last_response(signal_responses) if last_response: return last_response else: form = LocationForm(instance=profile) template = "userprofile/profile/location.html" data = { 'section': 'location', 'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY, 'form': form, 'geoip': geoip } signals.context_signal.send(sender=location, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request)) @login_required def delete(request): if request.method == "POST": profile, created = Profile.objects.get_or_create(user=request.user) old_profile = copy.copy(profile) old_user = copy.copy(request.user) # Remove the profile and all the information Profile.objects.filter(user=request.user).delete() EmailValidation.objects.filter(user=request.user).delete() Avatar.objects.filter(user=request.user).delete() # Remove the e-mail of the account too request.user.email = '' request.user.first_name = '' request.user.last_name = '' request.user.save() messages.success(request, _("Your profile information has been removed successfully."), fail_silently=True) signal_responses = signals.post_signal.send(sender=delete, request=request, extra={'old_profile':old_profile, 'old_user': old_user}) return signals.last_response(signal_responses) or HttpResponseRedirect(reverse("profile_overview")) template = "userprofile/profile/delete.html" data = { 'section': 'delete', } signals.context_signal.send(sender=delete, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request)) @login_required def avatarchoose(request): """ Avatar choose """ profile, created = Profile.objects.get_or_create(user = request.user) images = dict() if hasattr(settings, "AVATAR_QUOTA"): request.upload_handlers.insert(0, QuotaUploadHandler()) if request.method == "POST": form = AvatarForm() if request.POST.get('keyword'): keyword = iri_to_uri(request.POST.get('keyword')) gd_client = gdata.photos.service.PhotosService() feed = gd_client.SearchCommunityPhotos(query = "%s&thumbsize=72c" % keyword.split(" ")[0], limit='48') for entry in feed.entry: images[entry.media.thumbnail[0].url] = entry.content.src else: form = AvatarForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data.get('url') or form.cleaned_data.get('photo') try: thumb = Image.open(ContentFile(image.read())) except: messages.error(request, _("This image can't be used as an avatar")) else: thumb.thumbnail((480, 480), Image.ANTIALIAS) f = StringIO() save_img_params = SAVE_IMG_PARAMS.get(thumb.format, {}) try: thumb.save(f, thumb.format, **SAVE_IMG_PARAMS.get(thumb.format, {})) except: thumb.save(f, thumb.format) f.seek(0) avatar = Avatar(user=request.user, image="", valid=False) file_ext = image.content_type.split("/")[1] # "image/gif" => "gif" if file_ext == 'pjpeg': file_ext = 'jpeg' avatar.image.save("%s.%s" % (request.user.username, file_ext), ContentFile(f.read())) avatar.save() signal_responses = signals.post_signal.send(sender=avatarchoose, request=request, form=form) return signals.last_response(signal_responses) or HttpResponseRedirect(reverse("profile_avatar_crop")) else: form = AvatarForm() if DEFAULT_AVATAR: base, filename = os.path.split(DEFAULT_AVATAR) filename, extension = os.path.splitext(filename) generic = "%s/%s.%d%s" % (base, filename, DEFAULT_AVATAR_SIZE, extension) generic = generic.replace(settings.MEDIA_ROOT, settings.MEDIA_URL) else: generic = "" template = "userprofile/avatar/choose.html" data = { 'generic': generic, 'form': form, "images": images, 'AVATAR_WEBSEARCH': AVATAR_WEBSEARCH, 'section': 'avatar', 'DEFAULT_AVATAR_SIZE': DEFAULT_AVATAR_SIZE, 'MIN_AVATAR_SIZE': MIN_AVATAR_SIZE } signals.context_signal.send(sender=avatarchoose, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request)) @login_required def avatarcrop(request): """ Avatar management """ avatar = get_object_or_404(Avatar, user=request.user, valid=False) if not request.method == "POST": form = AvatarCropForm() else: image = Image.open(ContentFile(avatar.image.read())) form = AvatarCropForm(image, request.POST) if form.is_valid(): top = int(form.cleaned_data.get('top')) left = int(form.cleaned_data.get('left')) right = int(form.cleaned_data.get('right')) bottom = int(form.cleaned_data.get('bottom')) if not (top or left or right or bottom): (width, height) = image.size if width > height: diff = (width-height) / 2 left = diff right = width-diff bottom = height else: diff = (height-width) / 2 top = diff right = width bottom = height-diff box = [ left, top, right, bottom ] image = image.crop(box) if hasattr(settings, "AWS_SECRET_ACCESS_KEY"): f = StringIO() image.save(f, image.format) f.seek(0) avatar.image.delete() file_ext = image.content_type.split("/")[1] # "image/gif" => "gif" if file_ext == 'pjpeg': file_ext = 'jpeg' avatar.image.save("%s.%s" % (request.user.username, file_ext), ContentFile(f.read())) else: image.save(avatar.image.path) avatar.valid = True avatar.save() messages.success(request, _("Your new avatar has been saved successfully."), fail_silently=True) signal_responses = signals.post_signal.send(sender=avatarcrop, request=request, form=form) return signals.last_response(signal_responses) or HttpResponseRedirect(reverse("profile_edit_avatar")) template = "userprofile/avatar/crop.html" data = { 'section': 'avatar', 'avatar': avatar, 'form': form, \ 'DEFAULT_AVATAR_SIZE': DEFAULT_AVATAR_SIZE, 'MIN_AVATAR_SIZE': MIN_AVATAR_SIZE } signals.context_signal.send(sender=avatarcrop, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request)) @login_required def avatardelete(request, avatar_id=False): if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': try: for avatar in Avatar.objects.filter(user=request.user): avatar.delete() return HttpResponse(simplejson.dumps({'success': True})) except: return HttpResponse(simplejson.dumps({'success': False})) else: raise Http404() def email_validation_process(request, key): """ Verify key and change email """ if EmailValidation.objects.verify(key=key): successful = True else: successful = False signal_responses = signals.post_signal.send(sender=email_validation_process, request=request, extra={'key': key, 'successful': successful}) last_response = signals.last_response(signal_responses) if last_response: return last_response template = "userprofile/account/email_validation_done.html" data = { 'successful': successful, } signals.context_signal.send(sender=email_validation_process, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request)) @login_required def email_validation(request): """ E-mail Change form """ if request.method == 'POST': form = EmailValidationForm(request.POST) if form.is_valid(): EmailValidation.objects.add(user=request.user, email=form.cleaned_data.get('email')) signal_responses = signals.post_signal.send(sender=email_validation, request=request, form=form) return signals.last_response(signal_responses) or HttpResponseRedirect(reverse("email_validation_processed")) else: form = EmailValidationForm() template = "userprofile/account/email_validation.html" data = { 'form': form, } signals.context_signal.send(sender=email_validation, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request)) def register(request): if request.method == 'POST': form = _RegistrationForm(request.POST) if form.is_valid(): newuser = form.save() signal_responses = signals.post_signal.send(sender=register, request=request, form=form, extra={'newuser': newuser}) return signals.last_response(signal_responses) or HttpResponseRedirect(reverse('signup_complete')) else: form = _RegistrationForm() template = "userprofile/account/registration.html" data = { 'form': form, } signals.context_signal.send(sender=register, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request)) def email_validation_reset(request): """ Resend the validation email """ if request.user.is_authenticated(): try: resend = EmailValidation.objects.exclude(verified=True).get(user=request.user).resend() response = "done" except EmailValidation.DoesNotExist: response = "failed" signal_responses = signals.post_signal.send(sender=email_validation_reset, request=request, extra={'response': response}) return signals.last_response(signal_responses) or HttpResponseRedirect(reverse("email_validation_reset_response", args=[response])) else: if request.method == 'POST': form = ResendEmailValidationForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') try: resend = EmailValidation.objects.exclude(verified=True).get(email=email).resend() response = "done" except EmailValidation.DoesNotExist: response = "failed" signal_responses = signals.post_signal.send(sender=email_validation_reset, request=request, extra={'response': response}) return signals.last_response(signal_responses) or HttpResponseRedirect(reverse("email_validation_reset_response", args=[response])) else: form = ResendEmailValidationForm() template = "userprofile/account/email_validation_reset.html" data = { 'form': form, } signals.context_signal.send(sender=email_validation_reset, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request))
SrNetoChan/Quantum-GIS
refs/heads/master
tests/src/python/test_qgsdatetimestatisticalsummary.py
45
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsDateTimeStatisticalSummary. .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ __author__ = 'Nyall Dawson' __date__ = '07/05/2016' __copyright__ = 'Copyright 2016, The QGIS Project' import qgis # NOQA from qgis.core import (QgsDateTimeStatisticalSummary, QgsInterval, NULL ) from qgis.PyQt.QtCore import QDateTime, QDate, QTime from qgis.testing import unittest class PyQgsDateTimeStatisticalSummary(unittest.TestCase): def testStats(self): # we test twice, once with values added as a list and once using values # added one-at-a-time dates = [QDateTime(QDate(2015, 3, 4), QTime(11, 10, 54)), QDateTime(QDate(2011, 1, 5), QTime(15, 3, 1)), QDateTime(QDate(2015, 3, 4), QTime(11, 10, 54)), QDateTime(QDate(2015, 3, 4), QTime(11, 10, 54)), QDateTime(QDate(2019, 12, 28), QTime(23, 10, 1)), QDateTime(), QDateTime(QDate(1998, 1, 2), QTime(1, 10, 54)), QDateTime(), QDateTime(QDate(2011, 1, 5), QTime(11, 10, 54))] s = QgsDateTimeStatisticalSummary() self.assertEqual(s.statistics(), QgsDateTimeStatisticalSummary.All) s.calculate(dates) s2 = QgsDateTimeStatisticalSummary() for d in dates: s2.addValue(d) s2.finalize() self.assertEqual(s.count(), 9) self.assertEqual(s2.count(), 9) self.assertEqual(s.countDistinct(), 6) self.assertEqual(s2.countDistinct(), 6) self.assertEqual(set(s.distinctValues()), set([QDateTime(QDate(2015, 3, 4), QTime(11, 10, 54)), QDateTime(QDate(2011, 1, 5), QTime(15, 3, 1)), QDateTime(QDate(2019, 12, 28), QTime(23, 10, 1)), QDateTime(), QDateTime(QDate(1998, 1, 2), QTime(1, 10, 54)), QDateTime(QDate(2011, 1, 5), QTime(11, 10, 54))])) self.assertEqual(s2.distinctValues(), s.distinctValues()) self.assertEqual(s.countMissing(), 2) self.assertEqual(s2.countMissing(), 2) self.assertEqual(s.min(), QDateTime(QDate(1998, 1, 2), QTime(1, 10, 54))) self.assertEqual(s2.min(), QDateTime(QDate(1998, 1, 2), QTime(1, 10, 54))) self.assertEqual(s.max(), QDateTime(QDate(2019, 12, 28), QTime(23, 10, 1))) self.assertEqual(s2.max(), QDateTime(QDate(2019, 12, 28), QTime(23, 10, 1))) self.assertEqual(s.range(), QgsInterval(693871147)) self.assertEqual(s2.range(), QgsInterval(693871147)) def testIndividualStats(self): # tests calculation of statistics one at a time, to make sure statistic calculations are not # dependent on each other tests = [{'stat': QgsDateTimeStatisticalSummary.Count, 'expected': 9}, {'stat': QgsDateTimeStatisticalSummary.CountDistinct, 'expected': 6}, {'stat': QgsDateTimeStatisticalSummary.CountMissing, 'expected': 2}, {'stat': QgsDateTimeStatisticalSummary.Min, 'expected': QDateTime(QDate(1998, 1, 2), QTime(1, 10, 54))}, {'stat': QgsDateTimeStatisticalSummary.Max, 'expected': QDateTime(QDate(2019, 12, 28), QTime(23, 10, 1))}, {'stat': QgsDateTimeStatisticalSummary.Range, 'expected': QgsInterval(693871147)}, ] # we test twice, once with values added as a list and once using values # added one-at-a-time s = QgsDateTimeStatisticalSummary() s3 = QgsDateTimeStatisticalSummary() for t in tests: # test constructor s2 = QgsDateTimeStatisticalSummary(t['stat']) self.assertEqual(s2.statistics(), t['stat']) s.setStatistics(t['stat']) self.assertEqual(s.statistics(), t['stat']) s3.setStatistics(t['stat']) dates = [QDateTime(QDate(2015, 3, 4), QTime(11, 10, 54)), QDateTime(QDate(2011, 1, 5), QTime(15, 3, 1)), QDateTime(QDate(2015, 3, 4), QTime(11, 10, 54)), QDateTime(QDate(2015, 3, 4), QTime(11, 10, 54)), QDateTime(QDate(2019, 12, 28), QTime(23, 10, 1)), QDateTime(), QDateTime(QDate(1998, 1, 2), QTime(1, 10, 54)), QDateTime(), QDateTime(QDate(2011, 1, 5), QTime(11, 10, 54))] s.calculate(dates) s3.reset() for d in dates: s3.addValue(d) s3.finalize() self.assertEqual(s.statistic(t['stat']), t['expected']) self.assertEqual(s3.statistic(t['stat']), t['expected']) # display name self.assertTrue(len(QgsDateTimeStatisticalSummary.displayName(t['stat'])) > 0) def testVariantStats(self): """ test with non-datetime values """ s = QgsDateTimeStatisticalSummary() self.assertEqual(s.statistics(), QgsDateTimeStatisticalSummary.All) s.calculate([QDateTime(QDate(2015, 3, 4), QTime(11, 10, 54)), 'asdasd', QDateTime(QDate(2015, 3, 4), QTime(11, 10, 54)), 34, QDateTime(QDate(2019, 12, 28), QTime(23, 10, 1)), QDateTime(), QDateTime(QDate(1998, 1, 2), QTime(1, 10, 54)), QDateTime(), QDateTime(QDate(2011, 1, 5), QTime(11, 10, 54))]) self.assertEqual(s.count(), 9) self.assertEqual(set(s.distinctValues()), set([QDateTime(QDate(2015, 3, 4), QTime(11, 10, 54)), QDateTime(QDate(2019, 12, 28), QTime(23, 10, 1)), QDateTime(QDate(1998, 1, 2), QTime(1, 10, 54)), QDateTime(QDate(2011, 1, 5), QTime(11, 10, 54)), QDateTime()])) self.assertEqual(s.countMissing(), 4) self.assertEqual(s.min(), QDateTime(QDate(1998, 1, 2), QTime(1, 10, 54))) self.assertEqual(s.max(), QDateTime(QDate(2019, 12, 28), QTime(23, 10, 1))) self.assertEqual(s.range(), QgsInterval(693871147)) def testDates(self): """ test with date values """ s = QgsDateTimeStatisticalSummary() self.assertEqual(s.statistics(), QgsDateTimeStatisticalSummary.All) s.calculate([QDate(2015, 3, 4), QDate(2015, 3, 4), QDate(2019, 12, 28), QDate(), QDate(1998, 1, 2), QDate(), QDate(2011, 1, 5)]) self.assertEqual(s.count(), 7) self.assertEqual(set(s.distinctValues()), set([ QDateTime(QDate(2015, 3, 4), QTime()), QDateTime(QDate(2019, 12, 28), QTime()), QDateTime(QDate(1998, 1, 2), QTime()), QDateTime(), QDateTime(QDate(2011, 1, 5), QTime())])) self.assertEqual(s.countMissing(), 2) self.assertEqual(s.min(), QDateTime(QDate(1998, 1, 2), QTime())) self.assertEqual(s.max(), QDateTime(QDate(2019, 12, 28), QTime())) self.assertEqual(s.range(), QgsInterval(693792000)) def testTimes(self): """ test with time values """ s = QgsDateTimeStatisticalSummary() self.assertEqual(s.statistics(), QgsDateTimeStatisticalSummary.All) s.calculate([QTime(11, 3, 4), QTime(15, 3, 4), QTime(19, 12, 28), QTime(), QTime(8, 1, 2), QTime(), QTime(19, 12, 28)]) self.assertEqual(s.count(), 7) self.assertEqual(s.countDistinct(), 5) self.assertEqual(s.countMissing(), 2) self.assertEqual(s.min().time(), QTime(8, 1, 2)) self.assertEqual(s.max().time(), QTime(19, 12, 28)) self.assertEqual(s.statistic(QgsDateTimeStatisticalSummary.Min), QTime(8, 1, 2)) self.assertEqual(s.statistic(QgsDateTimeStatisticalSummary.Max), QTime(19, 12, 28)) self.assertEqual(s.range(), QgsInterval(40286)) def testMissing(self): s = QgsDateTimeStatisticalSummary() s.calculate([NULL, 'not a date']) self.assertEqual(s.countMissing(), 2) if __name__ == '__main__': unittest.main()
csdl/makahiki
refs/heads/master
makahiki/apps/widgets/prizes/templatetags/prize_tags.py
9
"""template tag definition for Prize page""" from django import template register = template.Library() def user_tickets(raffle_prize, user): """return the allocate ticket for user""" return raffle_prize.allocated_tickets(user) def user_odds(raffle_prize, user): """return the user odd for the prize""" total_tickets = raffle_prize.allocated_tickets() if total_tickets == 0: return "0%" tickets = raffle_prize.allocated_tickets(user) odds = (float(tickets) * 100.0) / float(total_tickets) return "%0.1f%%" % (odds,) register.filter("user_tickets", user_tickets) register.filter("user_odds", user_odds) # Borrowed from http://djangosnippets.org/snippets/552/ # This locale setting uses the environment's locale setting. import locale #locale.setlocale(locale.LC_ALL, settings.LOCALE_SETTING) locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') @register.filter() def currency(value): """return the currency character from the locale""" return locale.currency(value, grouping=True)
hainm/statsmodels
refs/heads/master
statsmodels/sandbox/distributions/try_pot.py
34
# -*- coding: utf-8 -*- """ Created on Wed May 04 06:09:18 2011 @author: josef """ from __future__ import print_function import numpy as np def mean_residual_life(x, frac=None, alpha=0.05): '''emprirical mean residual life or expected shortfall Parameters ---------- todo: check formula for std of mean doesn't include case for all observations last observations std is zero vectorize loop using cumsum frac doesn't work yet ''' axis = 0 #searchsorted is 1d only x = np.asarray(x) nobs = x.shape[axis] xsorted = np.sort(x, axis=axis) if frac is None: xthreshold = xsorted else: xthreshold = xsorted[np.floor(nobs * frac).astype(int)] #use searchsorted instead of simple index in case of ties xlargerindex = np.searchsorted(xsorted, xthreshold, side='right') #replace loop with cumsum ? result = [] for i in range(len(xthreshold)-1): k_ind = xlargerindex[i] rmean = x[k_ind:].mean() rstd = x[k_ind:].std() #this doesn't work for last observations, nans rmstd = rstd/np.sqrt(nobs-k_ind) #std error of mean, check formula result.append((k_ind, xthreshold[i], rmean, rmstd)) res = np.array(result) crit = 1.96 # todo: without loading stats, crit = -stats.t.ppf(0.05) confint = res[:,1:2] + crit * res[:,-1:] * np.array([[-1,1]]) return np.column_stack((res, confint)) expected_shortfall = mean_residual_life #alias if __name__ == "__main__": rvs = np.random.standard_t(5, size= 10) res = mean_residual_life(rvs) print(res) rmean = [rvs[i:].mean() for i in range(len(rvs))] print(res[:,2] - rmean[1:]) ''' >>> mean_residual_life(rvs, frac= 0.5) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "E:\Josef\eclipsegworkspace\statsmodels-josef-experimental-030\scikits\statsmodels\sandbox\distributions\try_pot.py", line 35, in mean_residual_life for i in range(len(xthreshold)-1): TypeError: object of type 'numpy.float64' has no len() >>> mean_residual_life(rvs, frac= [0.5]) array([[ 1. , -1.16904459, 0.35165016, 0.41090978, -1.97442776, -0.36366142], [ 1. , -1.16904459, 0.35165016, 0.41090978, -1.97442776, -0.36366142], [ 1. , -1.1690445 '''
FireWRT/OpenWrt-Firefly-Libraries
refs/heads/master
staging_dir/target-mipsel_1004kc+dsp_uClibc-0.9.33.2/usr/lib/python3.4/sqlite3/test/dump.py
119
# Author: Paul Kippes <kippesp@gmail.com> import unittest import sqlite3 as sqlite class DumpTests(unittest.TestCase): def setUp(self): self.cx = sqlite.connect(":memory:") self.cu = self.cx.cursor() def tearDown(self): self.cx.close() def CheckTableDump(self): expected_sqls = [ """CREATE TABLE "index"("index" blob);""" , """INSERT INTO "index" VALUES(X'01');""" , """CREATE TABLE "quoted""table"("quoted""field" text);""" , """INSERT INTO "quoted""table" VALUES('quoted''value');""" , "CREATE TABLE t1(id integer primary key, s1 text, " \ "t1_i1 integer not null, i2 integer, unique (s1), " \ "constraint t1_idx1 unique (i2));" , "INSERT INTO \"t1\" VALUES(1,'foo',10,20);" , "INSERT INTO \"t1\" VALUES(2,'foo2',30,30);" , "CREATE TABLE t2(id integer, t2_i1 integer, " \ "t2_i2 integer, primary key (id)," \ "foreign key(t2_i1) references t1(t1_i1));" , "CREATE TRIGGER trigger_1 update of t1_i1 on t1 " \ "begin " \ "update t2 set t2_i1 = new.t1_i1 where t2_i1 = old.t1_i1; " \ "end;" , "CREATE VIEW v1 as select * from t1 left join t2 " \ "using (id);" ] [self.cu.execute(s) for s in expected_sqls] i = self.cx.iterdump() actual_sqls = [s for s in i] expected_sqls = ['BEGIN TRANSACTION;'] + expected_sqls + \ ['COMMIT;'] [self.assertEqual(expected_sqls[i], actual_sqls[i]) for i in range(len(expected_sqls))] def CheckUnorderableRow(self): # iterdump() should be able to cope with unorderable row types (issue #15545) class UnorderableRow: def __init__(self, cursor, row): self.row = row def __getitem__(self, index): return self.row[index] self.cx.row_factory = UnorderableRow CREATE_ALPHA = """CREATE TABLE "alpha" ("one");""" CREATE_BETA = """CREATE TABLE "beta" ("two");""" expected = [ "BEGIN TRANSACTION;", CREATE_ALPHA, CREATE_BETA, "COMMIT;" ] self.cu.execute(CREATE_BETA) self.cu.execute(CREATE_ALPHA) got = list(self.cx.iterdump()) self.assertEqual(expected, got) def suite(): return unittest.TestSuite(unittest.makeSuite(DumpTests, "Check")) def test(): runner = unittest.TextTestRunner() runner.run(suite()) if __name__ == "__main__": test()
mcltn/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()
Fale/ansible
refs/heads/devel
lib/ansible/module_utils/common/_utils.py
97
# Copyright (c) 2018, Ansible Project # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) from __future__ import absolute_import, division, print_function __metaclass__ = type """ Modules in _utils are waiting to find a better home. If you need to use them, be prepared for them to move to a different location in the future. """ def get_all_subclasses(cls): ''' Recursively search and find all subclasses of a given class :arg cls: A python class :rtype: set :returns: The set of python classes which are the subclasses of `cls`. In python, you can use a class's :py:meth:`__subclasses__` method to determine what subclasses of a class exist. However, `__subclasses__` only goes one level deep. This function searches each child class's `__subclasses__` method to find all of the descendent classes. It then returns an iterable of the descendent classes. ''' # Retrieve direct subclasses subclasses = set(cls.__subclasses__()) to_visit = list(subclasses) # Then visit all subclasses while to_visit: for sc in to_visit: # The current class is now visited, so remove it from list to_visit.remove(sc) # Appending all subclasses to visit and keep a reference of available class for ssc in sc.__subclasses__(): if ssc not in subclasses: to_visit.append(ssc) subclasses.add(ssc) return subclasses
Goutte/Ni
refs/heads/master
v1/web/apostrophePlugin/js/fckeditor/editor/filemanager/connectors/py/wsgi.py
39
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector/QuickUpload for Python (WSGI wrapper). See config.py for configuration settings """ from connector import FCKeditorConnector from upload import FCKeditorQuickUpload import cgitb from cStringIO import StringIO # Running from WSGI capable server (recomended) def App(environ, start_response): "WSGI entry point. Run the connector" if environ['SCRIPT_NAME'].endswith("connector.py"): conn = FCKeditorConnector(environ) elif environ['SCRIPT_NAME'].endswith("upload.py"): conn = FCKeditorQuickUpload(environ) else: start_response ("200 Ok", [('Content-Type','text/html')]) yield "Unknown page requested: " yield environ['SCRIPT_NAME'] return try: # run the connector data = conn.doResponse() # Start WSGI response: start_response ("200 Ok", conn.headers) # Send response text yield data except: start_response("500 Internal Server Error",[("Content-type","text/html")]) file = StringIO() cgitb.Hook(file = file).handle() yield file.getvalue()
clonetwin26/buck
refs/heads/master
programs/file_locks.py
11
# Copyright 2016-present Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import errno import os BUCK_LOCK_FILE_NAME = '.buck_lock' if os.name == 'posix': import fcntl def _fcntl_with_exception_handling(f, exclusive): lock_type = fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH try: fcntl.lockf(f.fileno(), lock_type | fcntl.LOCK_NB) return True except IOError as e: if e.errno in [errno.EACCES, errno.EAGAIN]: return False raise else: def _fcntl_with_exception_handling(f, exclusive): return True def acquire_shared_lock(f): """ Acquires a shared posix advisory lock on a file in a non-blocking way. The f argument should be a file (ideally opened with 'a+', as that works for both shared and exclusive locks). Returns True on success, False if the lock cannot be taken, throws on error. """ return _fcntl_with_exception_handling(f, exclusive=False) def acquire_exclusive_lock(f): """ Acquires an exclusive posix advisory lock on a file in a non-blocking way. The f argument should be a file (ideally opened with 'a+', as that works for both shared and exclusive locks). Returns True on success, False if the lock cannot be taken, throws on error. """ return _fcntl_with_exception_handling(f, exclusive=True) def rmtree_if_can_lock(root): """ Removes the directory and sub-directories under root, except any directories which have a `.buck_lock` file present, which are only deleted if an exclusive lock can be obtained on the lock file. """ lock_file_path = os.path.join(root, BUCK_LOCK_FILE_NAME) lock_file = None if os.path.exists(lock_file_path): lock_file = open(lock_file_path, 'a+') if not acquire_exclusive_lock(lock_file): lock_file.close() return for name in os.listdir(root): p = os.path.join(root, name) if os.path.isdir(p): rmtree_if_can_lock(p) else: try: os.unlink(p) except (IOError, OSError): # Ignore errors like shutil.rmtree pass try: os.rmdir(root) except (IOError, OSError): # Ignore errors like shutil.rmtree pass if lock_file is not None: lock_file.close()
asajeffrey/servo
refs/heads/master
tests/wpt/web-platform-tests/service-workers/service-worker/resources/success.py
20
def main(request, response): headers = [] if b"ACAOrigin" in request.GET: for item in request.GET[b"ACAOrigin"].split(b","): headers.append((b"Access-Control-Allow-Origin", item)) return headers, b"{ \"result\": \"success\" }"
craigcook/bedrock
refs/heads/master
bedrock/base/tests/test_context_processors.py
10
from django.template.loader import render_to_string from django.test import TestCase, RequestFactory import jinja2 from lib.l10n_utils import translation class TestContext(TestCase): def setUp(self): translation.activate('en-US') self.factory = RequestFactory() translation.activate('en-US') def render(self, content, request=None): if not request: request = self.factory.get('/') tpl = jinja2.Template(content) return render_to_string(tpl, request=request) def test_request(self): assert self.render('{{ request.path }}') == '/' def test_settings(self): assert self.render('{{ settings.LANGUAGE_CODE }}') == 'en-US' def test_languages(self): assert self.render("{{ LANGUAGES['en-us'] }}") == 'English (US)' def test_lang_setting(self): assert self.render("{{ LANG }}") == 'en-US' def test_lang_dir(self): assert self.render("{{ DIR }}") == 'ltr'
TomLottermann/django-avatar
refs/heads/master
tests/settings.py
71
from django.conf.urls.defaults import patterns, include, handler500, handler404 DEFAULT_CHARSET = 'utf-8' DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = ':memory:' ROOT_URLCONF = 'settings' STATIC_URL = '/site_media/static/' SITE_ID = 1 INSTALLED_APPS = ( 'django.contrib.sessions', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'django.contrib.comments', 'avatar', ) TEMPLATE_LOADERS = ( 'django.template.loaders.app_directories.load_template_source', ) AVATAR_ALLOWED_FILE_EXTS = ('.jpg', '.png') AVATAR_MAX_SIZE = 1024 * 1024 AVATAR_MAX_AVATARS_PER_USER = 20 urlpatterns = patterns('', (r'^avatar/', include('avatar.urls')), ) def __exported_functionality__(): return (handler500, handler404)
haoyunfeix/crosswalk-test-suite
refs/heads/master
apptools/apptools-linux-tests/apptools/manifest_package_id.py
15
#!/usr/bin/env python # # Copyright (c) 2015 Intel Corporation. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of works must retain the original copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the original copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this work without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: # Liu, Yun <yunx.liu@intel.com> import unittest import os import comm from xml.etree import ElementTree import json class TestCrosswalkApptoolsFunctions(unittest.TestCase): def test_packageID(self): comm.setUp() comm.create(self) os.chdir(comm.TEST_PROJECT_COMM) with open(comm.TEMP_DATA_PATH + comm.TEST_PROJECT_COMM + "/app/manifest.json") as json_file: data = json.load(json_file) comm.cleanTempData(comm.TEST_PROJECT_COMM) self.assertEquals(data['xwalk_package_id'].strip(os.linesep), comm.TEST_PROJECT_COMM) def test_update_packageID(self): comm.setUp() comm.create(self) os.chdir(comm.TEST_PROJECT_COMM) jsonfile = open(comm.TEMP_DATA_PATH + comm.TEST_PROJECT_COMM + "/app/manifest.json", "r") jsons = jsonfile.read() jsonfile.close() jsonDict = json.loads(jsons) jsonDict["xwalk_package_id"] = "org.test.foo" json.dump(jsonDict, open(comm.TEMP_DATA_PATH + comm.TEST_PROJECT_COMM + "/app/manifest.json", "w")) buildcmd = "crosswalk-app build" return_code = os.system(buildcmd) comm.cleanTempData(comm.TEST_PROJECT_COMM) self.assertNotEquals(return_code, 0) if __name__ == '__main__': unittest.main()
fidomason/kbengine
refs/heads/master
kbe/res/scripts/common/Lib/site-packages/pip/_vendor/html5lib/treewalkers/pulldom.py
1729
from __future__ import absolute_import, division, unicode_literals from xml.dom.pulldom import START_ELEMENT, END_ELEMENT, \ COMMENT, IGNORABLE_WHITESPACE, CHARACTERS from . import _base from ..constants import voidElements class TreeWalker(_base.TreeWalker): def __iter__(self): ignore_until = None previous = None for event in self.tree: if previous is not None and \ (ignore_until is None or previous[1] is ignore_until): if previous[1] is ignore_until: ignore_until = None for token in self.tokens(previous, event): yield token if token["type"] == "EmptyTag": ignore_until = previous[1] previous = event if ignore_until is None or previous[1] is ignore_until: for token in self.tokens(previous, None): yield token elif ignore_until is not None: raise ValueError("Illformed DOM event stream: void element without END_ELEMENT") def tokens(self, event, next): type, node = event if type == START_ELEMENT: name = node.nodeName namespace = node.namespaceURI attrs = {} for attr in list(node.attributes.keys()): attr = node.getAttributeNode(attr) attrs[(attr.namespaceURI, attr.localName)] = attr.value if name in voidElements: for token in self.emptyTag(namespace, name, attrs, not next or next[1] is not node): yield token else: yield self.startTag(namespace, name, attrs) elif type == END_ELEMENT: name = node.nodeName namespace = node.namespaceURI if name not in voidElements: yield self.endTag(namespace, name) elif type == COMMENT: yield self.comment(node.nodeValue) elif type in (IGNORABLE_WHITESPACE, CHARACTERS): for token in self.text(node.nodeValue): yield token else: yield self.unknown(type)
splotz90/urh
refs/heads/master
src/urh/ui/delegates/SimulatorSettingsComboBoxDelegate.py
1
from PyQt5.QtWidgets import QItemDelegate, QStyle, QStyleOptionViewItem, QComboBox, QWidget from PyQt5.QtCore import Qt, QModelIndex, QAbstractItemModel, pyqtSlot from urh.controller.SendRecvSettingsDialogController import SendRecvSettingsDialogController from urh.dev.BackendHandler import BackendHandler from urh import SimulatorSettings class SimulatorSettingsComboBoxDelegate(QItemDelegate): def __init__(self, controller, is_rx=True, parent=None): super().__init__(parent) self.controller = controller self.generator_tab_controller = controller.generator_tab_controller self.project_manager = controller.project_manager self.compare_frame_controller = controller.compare_frame_controller self.editor = None self.is_rx = is_rx self.backend_handler = BackendHandler() @property def is_tx(self): return not self.is_rx def createEditor(self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex): self.editor = QComboBox(parent) self.load_combobox() self.editor.activated.connect(self.combobox_activated) return self.editor def load_combobox(self): self.editor.blockSignals(True) self.editor.clear() for profile in SimulatorSettings.profiles: if self.is_rx and profile['supports_rx']: self.editor.addItem(profile['name'], profile) if self.is_tx and profile['supports_tx']: self.editor.addItem(profile['name'], profile) self.editor.addItem("...") self.editor.blockSignals(False) def setEditorData(self, editor: QWidget, index: QModelIndex): self.editor.blockSignals(True) item = index.model().data(index, Qt.EditRole) self.editor.setCurrentIndex(self.find_index(item)) self.editor.blockSignals(False) def setModelData(self, editor: QWidget, model: QAbstractItemModel, index: QModelIndex): model.setData(index, editor.itemData(editor.currentIndex()), Qt.EditRole) def dialog_finished(self): self.load_combobox() selected_profile = SimulatorSettings.profiles[self.sender().ui.comboBoxProfiles.currentIndex()] self.editor.setCurrentIndex(self.find_index(selected_profile)) self.commitData.emit(self.editor) def find_index(self, profile): indx = self.editor.findData(profile) return self.editor.count() - 1 if indx == -1 else indx @pyqtSlot(int) def combobox_activated(self, index: int): if index == -1: return pm = self.project_manager if index == self.editor.count() - 1: signal = None for proto in self.compare_frame_controller.protocol_list: signal = proto.signal if signal: break if signal: bit_len = signal.bit_len mod_type = signal.modulation_type tolerance = signal.tolerance noise = signal.noise_threshold center = signal.qad_center else: bit_len = 100 mod_type = 1 tolerance = 5 noise = 0.001 center = 0.02 dialog = SendRecvSettingsDialogController(pm, noise, center, bit_len, tolerance, mod_type, self.generator_tab_controller, parent=self.editor) dialog.finished.connect(self.dialog_finished) dialog.show()
plotly/python-api
refs/heads/master
packages/python/plotly/plotly/graph_objs/layout/template/data/_funnelarea.py
2
from plotly.graph_objs import Funnelarea
tangyiyong/odoo
refs/heads/8.0
openerp/report/printscreen/ps_list.py
381
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import openerp from openerp.report.interface import report_int import openerp.tools as tools from openerp.tools.safe_eval import safe_eval as eval from lxml import etree from openerp.report import render, report_sxw import locale import time, os from operator import itemgetter from datetime import datetime class report_printscreen_list(report_int): def __init__(self, name): report_int.__init__(self, name) self.context = {} self.groupby = [] self.cr='' def _parse_node(self, root_node): result = [] for node in root_node: field_name = node.get('name') if not eval(str(node.attrib.get('invisible',False)),{'context':self.context}): if node.tag == 'field': if field_name in self.groupby: continue result.append(field_name) else: result.extend(self._parse_node(node)) return result def _parse_string(self, view): try: dom = etree.XML(view.encode('utf-8')) except Exception: dom = etree.XML(view) return self._parse_node(dom) def create(self, cr, uid, ids, datas, context=None): if not context: context={} self.cr=cr self.context = context self.groupby = context.get('group_by',[]) self.groupby_no_leaf = context.get('group_by_no_leaf',False) registry = openerp.registry(cr.dbname) model = registry[datas['model']] model_id = registry['ir.model'].search(cr, uid, [('model','=',model._name)]) model_desc = model._description if model_id: model_desc = registry['ir.model'].browse(cr, uid, model_id[0], context).name self.title = model_desc datas['ids'] = ids result = model.fields_view_get(cr, uid, view_type='tree', context=context) fields_order = self.groupby + self._parse_string(result['arch']) if self.groupby: rows = [] def get_groupby_data(groupby = [], domain = []): records = model.read_group(cr, uid, domain, fields_order, groupby , 0, None, context) for rec in records: rec['__group'] = True rec['__no_leaf'] = self.groupby_no_leaf rec['__grouped_by'] = groupby[0] if (isinstance(groupby, list) and groupby) else groupby for f in fields_order: if f not in rec: rec.update({f:False}) elif isinstance(rec[f], tuple): rec[f] = rec[f][1] rows.append(rec) inner_groupby = (rec.get('__context', {})).get('group_by',[]) inner_domain = rec.get('__domain', []) if inner_groupby: get_groupby_data(inner_groupby, inner_domain) else: if self.groupby_no_leaf: continue child_ids = model.search(cr, uid, inner_domain) res = model.read(cr, uid, child_ids, result['fields'].keys(), context) res.sort(lambda x,y: cmp(ids.index(x['id']), ids.index(y['id']))) rows.extend(res) dom = [('id','in',ids)] if self.groupby_no_leaf and len(ids) and not ids[0]: dom = datas.get('_domain',[]) get_groupby_data(self.groupby, dom) else: rows = model.read(cr, uid, datas['ids'], result['fields'].keys(), context) ids2 = map(itemgetter('id'), rows) # getting the ids from read result if datas['ids'] != ids2: # sorted ids were not taken into consideration for print screen rows_new = [] for id in datas['ids']: rows_new += [elem for elem in rows if elem['id'] == id] rows = rows_new res = self._create_table(uid, datas['ids'], result['fields'], fields_order, rows, context, model_desc) return self.obj.get(), 'pdf' def _create_table(self, uid, ids, fields, fields_order, results, context, title=''): pageSize=[297.0, 210.0] new_doc = etree.Element("report") config = etree.SubElement(new_doc, 'config') def _append_node(name, text): n = etree.SubElement(config, name) n.text = text #_append_node('date', time.strftime('%d/%m/%Y')) _append_node('date', time.strftime(str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y')))) _append_node('PageSize', '%.2fmm,%.2fmm' % tuple(pageSize)) _append_node('PageWidth', '%.2f' % (pageSize[0] * 2.8346,)) _append_node('PageHeight', '%.2f' %(pageSize[1] * 2.8346,)) _append_node('report-header', title) registry = openerp.registry(self.cr.dbname) _append_node('company', registry['res.users'].browse(self.cr,uid,uid).company_id.name) rpt_obj = registry['res.users'] rml_obj=report_sxw.rml_parse(self.cr, uid, rpt_obj._name,context) _append_node('header-date', str(rml_obj.formatLang(time.strftime("%Y-%m-%d"),date=True))+' ' + str(time.strftime("%H:%M"))) l = [] t = 0 strmax = (pageSize[0]-40) * 2.8346 temp = [] tsum = [] for i in range(0, len(fields_order)): temp.append(0) tsum.append(0) ince = -1 for f in fields_order: s = 0 ince += 1 if fields[f]['type'] in ('date','time','datetime','float','integer'): s = 60 strmax -= s if fields[f]['type'] in ('float','integer'): temp[ince] = 1 else: t += fields[f].get('size', 80) / 28 + 1 l.append(s) for pos in range(len(l)): if not l[pos]: s = fields[fields_order[pos]].get('size', 80) / 28 + 1 l[pos] = strmax * s / t _append_node('tableSize', ','.join(map(str,l)) ) header = etree.SubElement(new_doc, 'header') for f in fields_order: field = etree.SubElement(header, 'field') field.text = tools.ustr(fields[f]['string'] or '') lines = etree.SubElement(new_doc, 'lines') for line in results: node_line = etree.SubElement(lines, 'row') count = -1 for f in fields_order: float_flag = 0 count += 1 if fields[f]['type']=='many2one' and line[f]: if not line.get('__group'): line[f] = line[f][1] if fields[f]['type']=='selection' and line[f]: for key, value in fields[f]['selection']: if key == line[f]: line[f] = value break if fields[f]['type'] in ('one2many','many2many') and line[f]: line[f] = '( '+tools.ustr(len(line[f])) + ' )' if fields[f]['type'] == 'float' and line[f]: precision=(('digits' in fields[f]) and fields[f]['digits'][1]) or 2 prec ='%.' + str(precision) +'f' line[f]=prec%(line[f]) float_flag = 1 if fields[f]['type'] == 'date' and line[f]: new_d1 = line[f] if not line.get('__group'): format = str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y')) d1 = datetime.strptime(line[f],'%Y-%m-%d') new_d1 = d1.strftime(format) line[f] = new_d1 if fields[f]['type'] == 'time' and line[f]: new_d1 = line[f] if not line.get('__group'): format = str(locale.nl_langinfo(locale.T_FMT)) d1 = datetime.strptime(line[f], '%H:%M:%S') new_d1 = d1.strftime(format) line[f] = new_d1 if fields[f]['type'] == 'datetime' and line[f]: new_d1 = line[f] if not line.get('__group'): format = str(locale.nl_langinfo(locale.D_FMT).replace('%y', '%Y'))+' '+str(locale.nl_langinfo(locale.T_FMT)) d1 = datetime.strptime(line[f], '%Y-%m-%d %H:%M:%S') new_d1 = d1.strftime(format) line[f] = new_d1 if line.get('__group'): col = etree.SubElement(node_line, 'col', para='group', tree='no') else: col = etree.SubElement(node_line, 'col', para='yes', tree='no') # Prevent empty labels in groups if f == line.get('__grouped_by') and line.get('__group') and not line[f] and not float_flag and not temp[count]: col.text = line[f] = 'Undefined' col.set('tree', 'undefined') if line[f] is not None: col.text = tools.ustr(line[f] or '') if float_flag: col.set('tree','float') if line.get('__no_leaf') and temp[count] == 1 and f != 'id' and not line['__context']['group_by']: tsum[count] = float(tsum[count]) + float(line[f]) if not line.get('__group') and f != 'id' and temp[count] == 1: tsum[count] = float(tsum[count]) + float(line[f]) else: col.text = '/' node_line = etree.SubElement(lines, 'row') for f in range(0, len(fields_order)): col = etree.SubElement(node_line, 'col', para='group', tree='no') col.set('tree', 'float') if tsum[f] is not None: if tsum[f] != 0.0: digits = fields[fields_order[f]].get('digits', (16, 2)) prec = '%%.%sf' % (digits[1], ) total = prec % (tsum[f], ) txt = str(total or '') else: txt = str(tsum[f] or '') else: txt = '/' if f == 0: txt ='Total' col.set('tree','no') col.text = tools.ustr(txt or '') transform = etree.XSLT( etree.parse(os.path.join(tools.config['root_path'], 'addons/base/report/custom_new.xsl'))) rml = etree.tostring(transform(new_doc)) self.obj = render.rml(rml, title=self.title) self.obj.render() return True report_printscreen_list('report.printscreen.list') # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
wagnerand/addons-server
refs/heads/master
src/olympia/versions/migrations/0005_auto_20200518_1259.py
6
# Generated by Django 2.2.12 on 2020-05-18 12:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('versions', '0004_auto_20200512_1718'), ] operations = [ migrations.AlterField( model_name='version', name='source_git_hash', field=models.CharField(blank=True, max_length=40, null=True), ), ]
NKSG/ns-3-tcpbolt
refs/heads/master
src/energy/bindings/callbacks_list.py
85
callback_classes = [ ['void', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ]
Distrotech/intellij-community
refs/heads/master
python/testData/quickFixes/PyMakeFunctionFromMethodQuickFixTest/usageImport_after.py
83
import test b = test b.foo(1)
shft117/SteckerApp
refs/heads/master
erpnext/hr/doctype/employee_internal_work_history/employee_internal_work_history.py
121
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class EmployeeInternalWorkHistory(Document): pass
JioCloud/nova_test_latest
refs/heads/master
nova/api/openstack/compute/contrib/volumes.py
30
# Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """The volumes extension.""" from oslo_log import log as logging from oslo_utils import strutils from oslo_utils import uuidutils import webob from webob import exc from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import compute from nova import exception from nova.i18n import _ from nova.i18n import _LI from nova import objects from nova import volume LOG = logging.getLogger(__name__) authorize = extensions.extension_authorizer('compute', 'volumes') authorize_attach = extensions.extension_authorizer('compute', 'volume_attachments') def _translate_volume_detail_view(context, vol): """Maps keys for volumes details view.""" d = _translate_volume_summary_view(context, vol) # No additional data / lookups at the moment return d def _translate_volume_summary_view(context, vol): """Maps keys for volumes summary view.""" d = {} d['id'] = vol['id'] d['status'] = vol['status'] d['size'] = vol['size'] d['availabilityZone'] = vol['availability_zone'] d['createdAt'] = vol['created_at'] if vol['attach_status'] == 'attached': d['attachments'] = [_translate_attachment_detail_view(vol['id'], vol['instance_uuid'], vol['mountpoint'])] else: d['attachments'] = [{}] d['displayName'] = vol['display_name'] d['displayDescription'] = vol['display_description'] if vol['volume_type_id'] and vol.get('volume_type'): d['volumeType'] = vol['volume_type']['name'] else: d['volumeType'] = vol['volume_type_id'] d['snapshotId'] = vol['snapshot_id'] LOG.info(_LI("vol=%s"), vol, context=context) if vol.get('volume_metadata'): d['metadata'] = vol.get('volume_metadata') else: d['metadata'] = {} return d class VolumeController(wsgi.Controller): """The Volumes API controller for the OpenStack API.""" def __init__(self): self.volume_api = volume.API() super(VolumeController, self).__init__() def show(self, req, id): """Return data about the given volume.""" context = req.environ['nova.context'] authorize(context) try: vol = self.volume_api.get(context, id) except exception.NotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) return {'volume': _translate_volume_detail_view(context, vol)} def delete(self, req, id): """Delete a volume.""" context = req.environ['nova.context'] authorize(context) LOG.info(_LI("Delete volume with id: %s"), id, context=context) try: self.volume_api.delete(context, id) except exception.NotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) return webob.Response(status_int=202) def index(self, req): """Returns a summary list of volumes.""" return self._items(req, entity_maker=_translate_volume_summary_view) def detail(self, req): """Returns a detailed list of volumes.""" return self._items(req, entity_maker=_translate_volume_detail_view) def _items(self, req, entity_maker): """Returns a list of volumes, transformed through entity_maker.""" context = req.environ['nova.context'] authorize(context) volumes = self.volume_api.get_all(context) limited_list = common.limited(volumes, req) res = [entity_maker(context, vol) for vol in limited_list] return {'volumes': res} def create(self, req, body): """Creates a new volume.""" context = req.environ['nova.context'] authorize(context) if not self.is_valid_body(body, 'volume'): msg = _("volume not specified") raise exc.HTTPBadRequest(explanation=msg) vol = body['volume'] vol_type = vol.get('volume_type', None) metadata = vol.get('metadata', None) snapshot_id = vol.get('snapshot_id') if snapshot_id is not None: try: snapshot = self.volume_api.get_snapshot(context, snapshot_id) except exception.SnapshotNotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) else: snapshot = None size = vol.get('size', None) if size is None and snapshot is not None: size = snapshot['volume_size'] LOG.info(_LI("Create volume of %s GB"), size, context=context) availability_zone = vol.get('availability_zone', None) try: new_volume = self.volume_api.create( context, size, vol.get('display_name'), vol.get('display_description'), snapshot=snapshot, volume_type=vol_type, metadata=metadata, availability_zone=availability_zone ) except exception.InvalidInput as err: raise exc.HTTPBadRequest(explanation=err.format_message()) # TODO(vish): Instance should be None at db layer instead of # trying to lazy load, but for now we turn it into # a dict to avoid an error. retval = _translate_volume_detail_view(context, dict(new_volume)) result = {'volume': retval} location = '%s/%s' % (req.url, new_volume['id']) return wsgi.ResponseObject(result, headers=dict(location=location)) def _translate_attachment_detail_view(volume_id, instance_uuid, mountpoint): """Maps keys for attachment details view.""" d = _translate_attachment_summary_view(volume_id, instance_uuid, mountpoint) # No additional data / lookups at the moment return d def _translate_attachment_summary_view(volume_id, instance_uuid, mountpoint): """Maps keys for attachment summary view.""" d = {} # NOTE(justinsb): We use the volume id as the id of the attachment object d['id'] = volume_id d['volumeId'] = volume_id d['serverId'] = instance_uuid if mountpoint: d['device'] = mountpoint return d class VolumeAttachmentController(wsgi.Controller): """The volume attachment API controller for the OpenStack API. A child resource of the server. Note that we use the volume id as the ID of the attachment (though this is not guaranteed externally) """ def __init__(self, ext_mgr=None): self.compute_api = compute.API() self.volume_api = volume.API() self.ext_mgr = ext_mgr super(VolumeAttachmentController, self).__init__() def index(self, req, server_id): """Returns the list of volume attachments for a given instance.""" context = req.environ['nova.context'] authorize_attach(context, action='index') return self._items(req, server_id, entity_maker=_translate_attachment_summary_view) def show(self, req, server_id, id): """Return data about the given volume attachment.""" context = req.environ['nova.context'] authorize(context) authorize_attach(context, action='show') volume_id = id instance = common.get_instance(self.compute_api, context, server_id) bdms = objects.BlockDeviceMappingList.get_by_instance_uuid( context, instance.uuid) if not bdms: msg = _("Instance %s is not attached.") % server_id raise exc.HTTPNotFound(explanation=msg) assigned_mountpoint = None for bdm in bdms: if bdm.volume_id == volume_id: assigned_mountpoint = bdm.device_name break if assigned_mountpoint is None: msg = _("volume_id not found: %s") % volume_id raise exc.HTTPNotFound(explanation=msg) return {'volumeAttachment': _translate_attachment_detail_view( volume_id, instance.uuid, assigned_mountpoint)} def _validate_volume_id(self, volume_id): if not uuidutils.is_uuid_like(volume_id): msg = _("Bad volumeId format: volumeId is " "not in proper format (%s)") % volume_id raise exc.HTTPBadRequest(explanation=msg) def create(self, req, server_id, body): """Attach a volume to an instance.""" context = req.environ['nova.context'] authorize(context) authorize_attach(context, action='create') if not self.is_valid_body(body, 'volumeAttachment'): msg = _("volumeAttachment not specified") raise exc.HTTPBadRequest(explanation=msg) try: volume_id = body['volumeAttachment']['volumeId'] except KeyError: msg = _("volumeId must be specified.") raise exc.HTTPBadRequest(explanation=msg) device = body['volumeAttachment'].get('device') self._validate_volume_id(volume_id) LOG.info(_LI("Attach volume %(volume_id)s to instance %(server_id)s " "at %(device)s"), {'volume_id': volume_id, 'device': device, 'server_id': server_id}, context=context) instance = common.get_instance(self.compute_api, context, server_id) try: device = self.compute_api.attach_volume(context, instance, volume_id, device) except exception.NotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'attach_volume', server_id) # The attach is async attachment = {} attachment['id'] = volume_id attachment['serverId'] = server_id attachment['volumeId'] = volume_id attachment['device'] = device # NOTE(justinsb): And now, we have a problem... # The attach is async, so there's a window in which we don't see # the attachment (until the attachment completes). We could also # get problems with concurrent requests. I think we need an # attachment state, and to write to the DB here, but that's a bigger # change. # For now, we'll probably have to rely on libraries being smart # TODO(justinsb): How do I return "accepted" here? return {'volumeAttachment': attachment} def update(self, req, server_id, id, body): if (not self.ext_mgr or not self.ext_mgr.is_loaded('os-volume-attachment-update')): raise exc.HTTPBadRequest() context = req.environ['nova.context'] authorize(context) authorize_attach(context, action='update') if not self.is_valid_body(body, 'volumeAttachment'): msg = _("volumeAttachment not specified") raise exc.HTTPBadRequest(explanation=msg) old_volume_id = id old_volume = self.volume_api.get(context, old_volume_id) try: new_volume_id = body['volumeAttachment']['volumeId'] except KeyError: msg = _("volumeId must be specified.") raise exc.HTTPBadRequest(explanation=msg) self._validate_volume_id(new_volume_id) new_volume = self.volume_api.get(context, new_volume_id) instance = common.get_instance(self.compute_api, context, server_id) bdms = objects.BlockDeviceMappingList.get_by_instance_uuid( context, instance.uuid) found = False try: for bdm in bdms: if bdm.volume_id != old_volume_id: continue try: self.compute_api.swap_volume(context, instance, old_volume, new_volume) found = True break except exception.VolumeUnattached: # The volume is not attached. Treat it as NotFound # by falling through. pass except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'swap_volume', server_id) if not found: msg = _("volume_id not found: %s") % old_volume_id raise exc.HTTPNotFound(explanation=msg) else: return webob.Response(status_int=202) def delete(self, req, server_id, id): """Detach a volume from an instance.""" context = req.environ['nova.context'] authorize(context) authorize_attach(context, action='delete') volume_id = id LOG.info(_LI("Detach volume %s"), volume_id, context=context) instance = common.get_instance(self.compute_api, context, server_id) volume = self.volume_api.get(context, volume_id) bdms = objects.BlockDeviceMappingList.get_by_instance_uuid( context, instance.uuid) if not bdms: msg = _("Instance %s is not attached.") % server_id raise exc.HTTPNotFound(explanation=msg) found = False try: for bdm in bdms: if bdm.volume_id != volume_id: continue if bdm.is_root: msg = _("Can't detach root device volume") raise exc.HTTPForbidden(explanation=msg) try: self.compute_api.detach_volume(context, instance, volume) found = True break except exception.VolumeUnattached: # The volume is not attached. Treat it as NotFound # by falling through. pass except exception.InstanceIsLocked as e: raise exc.HTTPConflict(explanation=e.format_message()) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'detach_volume', server_id) if not found: msg = _("volume_id not found: %s") % volume_id raise exc.HTTPNotFound(explanation=msg) else: return webob.Response(status_int=202) def _items(self, req, server_id, entity_maker): """Returns a list of attachments, transformed through entity_maker.""" context = req.environ['nova.context'] authorize(context) instance = common.get_instance(self.compute_api, context, server_id) bdms = objects.BlockDeviceMappingList.get_by_instance_uuid( context, instance.uuid) limited_list = common.limited(bdms, req) results = [] for bdm in limited_list: if bdm.volume_id: results.append(entity_maker(bdm.volume_id, bdm.instance_uuid, bdm.device_name)) return {'volumeAttachments': results} def _translate_snapshot_detail_view(context, vol): """Maps keys for snapshots details view.""" d = _translate_snapshot_summary_view(context, vol) # NOTE(gagupta): No additional data / lookups at the moment return d def _translate_snapshot_summary_view(context, vol): """Maps keys for snapshots summary view.""" d = {} d['id'] = vol['id'] d['volumeId'] = vol['volume_id'] d['status'] = vol['status'] # NOTE(gagupta): We map volume_size as the snapshot size d['size'] = vol['volume_size'] d['createdAt'] = vol['created_at'] d['displayName'] = vol['display_name'] d['displayDescription'] = vol['display_description'] return d class SnapshotController(wsgi.Controller): """The Snapshots API controller for the OpenStack API.""" def __init__(self): self.volume_api = volume.API() super(SnapshotController, self).__init__() def show(self, req, id): """Return data about the given snapshot.""" context = req.environ['nova.context'] authorize(context) try: vol = self.volume_api.get_snapshot(context, id) except exception.NotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) return {'snapshot': _translate_snapshot_detail_view(context, vol)} def delete(self, req, id): """Delete a snapshot.""" context = req.environ['nova.context'] authorize(context) LOG.info(_LI("Delete snapshot with id: %s"), id, context=context) try: self.volume_api.delete_snapshot(context, id) except exception.NotFound as e: raise exc.HTTPNotFound(explanation=e.format_message()) return webob.Response(status_int=202) def index(self, req): """Returns a summary list of snapshots.""" return self._items(req, entity_maker=_translate_snapshot_summary_view) def detail(self, req): """Returns a detailed list of snapshots.""" return self._items(req, entity_maker=_translate_snapshot_detail_view) def _items(self, req, entity_maker): """Returns a list of snapshots, transformed through entity_maker.""" context = req.environ['nova.context'] authorize(context) snapshots = self.volume_api.get_all_snapshots(context) limited_list = common.limited(snapshots, req) res = [entity_maker(context, snapshot) for snapshot in limited_list] return {'snapshots': res} def create(self, req, body): """Creates a new snapshot.""" context = req.environ['nova.context'] authorize(context) if not self.is_valid_body(body, 'snapshot'): msg = _("snapshot not specified") raise exc.HTTPBadRequest(explanation=msg) snapshot = body['snapshot'] volume_id = snapshot['volume_id'] LOG.info(_LI("Create snapshot from volume %s"), volume_id, context=context) force = snapshot.get('force', False) try: force = strutils.bool_from_string(force, strict=True) except ValueError: msg = _("Invalid value '%s' for force.") % force raise exc.HTTPBadRequest(explanation=msg) if force: create_func = self.volume_api.create_snapshot_force else: create_func = self.volume_api.create_snapshot new_snapshot = create_func(context, volume_id, snapshot.get('display_name'), snapshot.get('display_description')) retval = _translate_snapshot_detail_view(context, new_snapshot) return {'snapshot': retval} class Volumes(extensions.ExtensionDescriptor): """Volumes support.""" name = "Volumes" alias = "os-volumes" namespace = "http://docs.openstack.org/compute/ext/volumes/api/v1.1" updated = "2011-03-25T00:00:00Z" def get_resources(self): resources = [] # NOTE(justinsb): No way to provide singular name ('volume') # Does this matter? res = extensions.ResourceExtension('os-volumes', VolumeController(), collection_actions={'detail': 'GET'}) resources.append(res) attachment_controller = VolumeAttachmentController(self.ext_mgr) res = extensions.ResourceExtension('os-volume_attachments', attachment_controller, parent=dict( member_name='server', collection_name='servers')) resources.append(res) res = extensions.ResourceExtension('os-volumes_boot', inherits='servers') resources.append(res) res = extensions.ResourceExtension('os-snapshots', SnapshotController(), collection_actions={'detail': 'GET'}) resources.append(res) return resources
smarkwell/asuswrt-merlin
refs/heads/master
release/src/router/samba36/source4/scripting/python/samba/netcmd/newuser.py
20
#!/usr/bin/env python # # Adds a new user to a Samba4 server # Copyright Jelmer Vernooij 2008 # # Based on the original in EJS: # Copyright Andrew Tridgell 2005 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import samba.getopt as options from samba.netcmd import Command, CommandError, Option import ldb from getpass import getpass from samba.auth import system_session from samba.samdb import SamDB class cmd_newuser(Command): """Creates a new user""" synopsis = "newuser [options] <username> [<password>]" takes_optiongroups = { "sambaopts": options.SambaOptions, "versionopts": options.VersionOptions, "credopts": options.CredentialsOptions, } takes_options = [ Option("-H", help="LDB URL for database or target server", type=str), Option("--must-change-at-next-login", help="Force password to be changed on next login", action="store_true"), Option("--use-username-as-cn", help="Force use of username as user's CN", action="store_true"), Option("--userou", help="Alternative location (without domainDN counterpart) to default CN=Users in which new user object will be created", type=str), Option("--surname", help="User's surname", type=str), Option("--given-name", help="User's given name", type=str), Option("--initials", help="User's initials", type=str), Option("--profile-path", help="User's profile path", type=str), Option("--script-path", help="User's logon script path", type=str), Option("--home-drive", help="User's home drive letter", type=str), Option("--home-directory", help="User's home directory path", type=str), Option("--job-title", help="User's job title", type=str), Option("--department", help="User's department", type=str), Option("--company", help="User's company", type=str), Option("--description", help="User's description", type=str), Option("--mail-address", help="User's email address", type=str), Option("--internet-address", help="User's home page", type=str), Option("--telephone-number", help="User's phone number", type=str), Option("--physical-delivery-office", help="User's office location", type=str), ] takes_args = ["username", "password?"] def run(self, username, password=None, credopts=None, sambaopts=None, versionopts=None, H=None, must_change_at_next_login=None, use_username_as_cn=None, userou=None, surname=None, given_name=None, initials=None, profile_path=None, script_path=None, home_drive=None, home_directory=None, job_title=None, department=None, company=None, description=None, mail_address=None, internet_address=None, telephone_number=None, physical_delivery_office=None): if password is None: password = getpass("New Password: ") lp = sambaopts.get_loadparm() creds = credopts.get_credentials(lp) try: samdb = SamDB(url=H, session_info=system_session(), credentials=creds, lp=lp) samdb.newuser(username, password, force_password_change_at_next_login_req=must_change_at_next_login, useusernameascn=use_username_as_cn, userou=userou, surname=surname, givenname=given_name, initials=initials, profilepath=profile_path, homedrive=home_drive, scriptpath=script_path, homedirectory=home_directory, jobtitle=job_title, department=department, company=company, description=description, mailaddress=mail_address, internetaddress=internet_address, telephonenumber=telephone_number, physicaldeliveryoffice=physical_delivery_office) except Exception, e: raise CommandError('Failed to create user "%s"' % username, e) print("User %s created successfully" % username)
lowitty/alarmfiles
refs/heads/master
lib/pysnmp/smi/mibs/instances/__SNMPv2-MIB.py
6
from sys import version from time import time from pysnmp import __version__ ( MibScalarInstance, TimeTicks) = mibBuilder.importSymbols( 'SNMPv2-SMI', 'MibScalarInstance', 'TimeTicks' ) ( sysDescr, sysObjectID, sysUpTime, sysContact, sysName, sysLocation, sysServices, sysORLastChange, snmpInPkts, snmpOutPkts, snmpInBadVersions, snmpInBadCommunityNames, snmpInBadCommunityUses, snmpInASNParseErrs, snmpInTooBigs, snmpInNoSuchNames, snmpInBadValues, snmpInReadOnlys, snmpInGenErrs, snmpInTotalReqVars, snmpInTotalSetVars, snmpInGetRequests, snmpInGetNexts, snmpInSetRequests, snmpInGetResponses, snmpInTraps, snmpOutTooBigs, snmpOutNoSuchNames, snmpOutBadValues, snmpOutGenErrs, snmpOutSetRequests, snmpOutGetResponses, snmpOutTraps, snmpEnableAuthenTraps, snmpSilentDrops, snmpProxyDrops, snmpTrapOID, coldStart, snmpSetSerialNo ) = mibBuilder.importSymbols( 'SNMPv2-MIB', 'sysDescr', 'sysObjectID', 'sysUpTime', 'sysContact', 'sysName', 'sysLocation', 'sysServices', 'sysORLastChange', 'snmpInPkts', 'snmpOutPkts', 'snmpInBadVersions', 'snmpInBadCommunityNames', 'snmpInBadCommunityUses', 'snmpInASNParseErrs', 'snmpInTooBigs', 'snmpInNoSuchNames', 'snmpInBadValues', 'snmpInReadOnlys', 'snmpInGenErrs', 'snmpInTotalReqVars', 'snmpInTotalSetVars', 'snmpInGetRequests', 'snmpInGetNexts', 'snmpInSetRequests', 'snmpInGetResponses', 'snmpInTraps', 'snmpOutTooBigs', 'snmpOutNoSuchNames', 'snmpOutBadValues', 'snmpOutGenErrs', 'snmpOutSetRequests', 'snmpOutGetResponses', 'snmpOutTraps', 'snmpEnableAuthenTraps', 'snmpSilentDrops', 'snmpProxyDrops', 'snmpTrapOID', 'coldStart', 'snmpSetSerialNo' ) __sysDescr = MibScalarInstance(sysDescr.name, (0,), sysDescr.syntax.clone("PySNMP engine version %s, Python %s" % (__version__, version.replace('\n', ' ').replace('\r', ' ')))) __sysObjectID = MibScalarInstance(sysObjectID.name, (0,), sysObjectID.syntax.clone((1,3,6,1,4,1,20408))) class SysUpTime(TimeTicks): createdAt = time() def clone(self, **kwargs): if 'value' not in kwargs: kwargs['value'] = int((time()-self.createdAt)*100) return TimeTicks.clone(self, **kwargs) __sysUpTime = MibScalarInstance(sysUpTime.name, (0,), SysUpTime(0)) __sysContact = MibScalarInstance(sysContact.name, (0,), sysContact.syntax.clone('')) __sysName = MibScalarInstance(sysName.name, (0,), sysName.syntax.clone('')) __sysLocation = MibScalarInstance(sysLocation.name, (0,), sysLocation.syntax.clone('')) __sysServices = MibScalarInstance(sysServices.name, (0,), sysServices.syntax.clone(0)) __sysORLastChange = MibScalarInstance(sysORLastChange.name, (0,), sysORLastChange.syntax.clone(0)) __snmpInPkts = MibScalarInstance(snmpInPkts.name, (0,), snmpInPkts.syntax.clone(0)) __snmpOutPkts = MibScalarInstance(snmpOutPkts.name, (0,), snmpOutPkts.syntax.clone(0)) __snmpInBadVersions = MibScalarInstance(snmpInBadVersions.name, (0,), snmpInBadVersions.syntax.clone(0)) __snmpInBadCommunityNames = MibScalarInstance(snmpInBadCommunityNames.name, (0,), snmpInBadCommunityNames.syntax.clone(0)) __snmpInBadCommunityUses = MibScalarInstance(snmpInBadCommunityUses.name, (0,), snmpInBadCommunityUses.syntax.clone(0)) __snmpInASNParseErrs = MibScalarInstance(snmpInASNParseErrs.name, (0,), snmpInASNParseErrs.syntax.clone(0)) __snmpInTooBigs = MibScalarInstance(snmpInTooBigs.name, (0,), snmpInTooBigs.syntax.clone(0)) __snmpInNoSuchNames = MibScalarInstance(snmpInNoSuchNames.name, (0,), snmpInNoSuchNames.syntax.clone(0)) __snmpInBadValues = MibScalarInstance(snmpInBadValues.name, (0,), snmpInBadValues.syntax.clone(0)) __snmpInReadOnlys = MibScalarInstance(snmpInReadOnlys.name, (0,), snmpInReadOnlys.syntax.clone(0)) __snmpInGenErrs = MibScalarInstance(snmpInGenErrs.name, (0,), snmpInGenErrs.syntax.clone(0)) __snmpInTotalReqVars = MibScalarInstance(snmpInTotalReqVars.name, (0,), snmpInTotalReqVars.syntax.clone(0)) __snmpInTotalSetVars = MibScalarInstance(snmpInTotalSetVars.name, (0,), snmpInTotalSetVars.syntax.clone(0)) __snmpInGetRequests = MibScalarInstance(snmpInGetRequests.name, (0,), snmpInGetRequests.syntax.clone(0)) __snmpInGetNexts = MibScalarInstance(snmpInGetNexts.name, (0,), snmpInGetNexts.syntax.clone(0)) __snmpInSetRequests = MibScalarInstance(snmpInSetRequests.name, (0,), snmpInSetRequests.syntax.clone(0)) __snmpInGetResponses = MibScalarInstance(snmpInGetResponses.name, (0,), snmpInGetResponses.syntax.clone(0)) __snmpInTraps = MibScalarInstance(snmpInTraps.name, (0,), snmpInTraps.syntax.clone(0)) __snmpOutTooBigs = MibScalarInstance(snmpOutTooBigs.name, (0,), snmpOutTooBigs.syntax.clone(0)) __snmpOutNoSuchNames = MibScalarInstance(snmpOutNoSuchNames.name, (0,), snmpOutNoSuchNames.syntax.clone(0)) __snmpOutBadValues = MibScalarInstance(snmpOutBadValues.name, (0,), snmpOutBadValues.syntax.clone(0)) __snmpOutGenErrs = MibScalarInstance(snmpOutGenErrs.name, (0,), snmpOutGenErrs.syntax.clone(0)) __snmpOutSetRequests = MibScalarInstance(snmpOutSetRequests.name, (0,), snmpOutSetRequests.syntax.clone(0)) __snmpOutGetResponses = MibScalarInstance(snmpOutGetResponses.name, (0,), snmpOutGetResponses.syntax.clone(0)) __snmpOutTraps = MibScalarInstance(snmpOutTraps.name, (0,), snmpOutTraps.syntax.clone(0)) __snmpEnableAuthenTraps = MibScalarInstance(snmpEnableAuthenTraps.name, (0,), snmpEnableAuthenTraps.syntax.clone(1)) __snmpSilentDrops = MibScalarInstance(snmpSilentDrops.name, (0,), snmpSilentDrops.syntax.clone(0)) __snmpProxyDrops = MibScalarInstance(snmpProxyDrops.name, (0,), snmpProxyDrops.syntax.clone(0)) __snmpTrapOID = MibScalarInstance(snmpTrapOID.name, (0,), snmpTrapOID.syntax.clone(coldStart.name)) __snmpSetSerialNo = MibScalarInstance(snmpSetSerialNo.name, (0,), snmpSetSerialNo.syntax.clone(0)) mibBuilder.exportSymbols( "__SNMPv2-MIB", sysDescr = __sysDescr, sysObjectID = __sysObjectID, sysUpTime = __sysUpTime, sysContact = __sysContact, sysName = __sysName, sysLocation = __sysLocation, sysServices = __sysServices, sysORLastChange = __sysORLastChange, snmpInPkts = __snmpInPkts, snmpOutPkts = __snmpOutPkts, snmpInBadVersions = __snmpInBadVersions, snmpInBadCommunityNames = __snmpInBadCommunityNames, snmpInBadCommunityUses = __snmpInBadCommunityUses, snmpInASNParseErrs = __snmpInASNParseErrs, snmpInTooBigs = __snmpInTooBigs, snmpInNoSuchNames = __snmpInNoSuchNames, snmpInBadValues = __snmpInBadValues, snmpInReadOnlys = __snmpInReadOnlys, snmpInGenErrs = __snmpInGenErrs, snmpInTotalReqVars = __snmpInTotalReqVars, snmpInTotalSetVars = __snmpInTotalSetVars, snmpInGetRequests = __snmpInGetRequests, snmpInGetNexts = __snmpInGetNexts, snmpInSetRequests = __snmpInSetRequests, snmpInGetResponses = __snmpInGetResponses, snmpInTraps = __snmpInTraps, snmpOutTooBigs = __snmpOutTooBigs, snmpOutNoSuchNames = __snmpOutNoSuchNames, snmpOutBadValues = __snmpOutBadValues, snmpOutGenErrs = __snmpOutGenErrs, snmpOutSetRequests = __snmpOutSetRequests, snmpOutGetResponses = __snmpOutGetResponses, snmpOutTraps = __snmpOutTraps, snmpEnableAuthenTraps = __snmpEnableAuthenTraps, snmpSilentDrops = __snmpSilentDrops, snmpProxyDrops = __snmpProxyDrops, snmpTrapOID = __snmpTrapOID, snmpSetSerialNo = __snmpSetSerialNo )
mmnelemane/neutron
refs/heads/master
neutron/services/qos/qos_consts.py
24
# Copyright (c) 2015 Red Hat 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. RULE_TYPE_BANDWIDTH_LIMIT = 'bandwidth_limit' VALID_RULE_TYPES = [RULE_TYPE_BANDWIDTH_LIMIT] QOS_POLICY_ID = 'qos_policy_id'
ms-iot/python
refs/heads/develop
cpython/Lib/idlelib/idle_test/test_autoexpand.py
20
"""Unit tests for idlelib.AutoExpand""" import unittest from test.support import requires from tkinter import Text, Tk #from idlelib.idle_test.mock_tk import Text from idlelib.AutoExpand import AutoExpand class Dummy_Editwin: # AutoExpand.__init__ only needs .text def __init__(self, text): self.text = text class AutoExpandTest(unittest.TestCase): @classmethod def setUpClass(cls): if 'tkinter' in str(Text): requires('gui') cls.tk = Tk() cls.text = Text(cls.tk) else: cls.text = Text() cls.auto_expand = AutoExpand(Dummy_Editwin(cls.text)) @classmethod def tearDownClass(cls): if hasattr(cls, 'tk'): cls.tk.destroy() del cls.tk del cls.text, cls.auto_expand def tearDown(self): self.text.delete('1.0', 'end') def test_get_prevword(self): text = self.text previous = self.auto_expand.getprevword equal = self.assertEqual equal(previous(), '') text.insert('insert', 't') equal(previous(), 't') text.insert('insert', 'his') equal(previous(), 'this') text.insert('insert', ' ') equal(previous(), '') text.insert('insert', 'is') equal(previous(), 'is') text.insert('insert', '\nsample\nstring') equal(previous(), 'string') text.delete('3.0', 'insert') equal(previous(), '') text.delete('1.0', 'end') equal(previous(), '') def test_before_only(self): previous = self.auto_expand.getprevword expand = self.auto_expand.expand_word_event equal = self.assertEqual self.text.insert('insert', 'ab ac bx ad ab a') equal(self.auto_expand.getwords(), ['ab', 'ad', 'ac', 'a']) expand('event') equal(previous(), 'ab') expand('event') equal(previous(), 'ad') expand('event') equal(previous(), 'ac') expand('event') equal(previous(), 'a') def test_after_only(self): # Also add punctuation 'noise' that should be ignored. text = self.text previous = self.auto_expand.getprevword expand = self.auto_expand.expand_word_event equal = self.assertEqual text.insert('insert', 'a, [ab] ac: () bx"" cd ac= ad ya') text.mark_set('insert', '1.1') equal(self.auto_expand.getwords(), ['ab', 'ac', 'ad', 'a']) expand('event') equal(previous(), 'ab') expand('event') equal(previous(), 'ac') expand('event') equal(previous(), 'ad') expand('event') equal(previous(), 'a') def test_both_before_after(self): text = self.text previous = self.auto_expand.getprevword expand = self.auto_expand.expand_word_event equal = self.assertEqual text.insert('insert', 'ab xy yz\n') text.insert('insert', 'a ac by ac') text.mark_set('insert', '2.1') equal(self.auto_expand.getwords(), ['ab', 'ac', 'a']) expand('event') equal(previous(), 'ab') expand('event') equal(previous(), 'ac') expand('event') equal(previous(), 'a') def test_other_expand_cases(self): text = self.text expand = self.auto_expand.expand_word_event equal = self.assertEqual # no expansion candidate found equal(self.auto_expand.getwords(), []) equal(expand('event'), 'break') text.insert('insert', 'bx cy dz a') equal(self.auto_expand.getwords(), []) # reset state by successfully expanding once # move cursor to another position and expand again text.insert('insert', 'ac xy a ac ad a') text.mark_set('insert', '1.7') expand('event') initial_state = self.auto_expand.state text.mark_set('insert', '1.end') expand('event') new_state = self.auto_expand.state self.assertNotEqual(initial_state, new_state) if __name__ == '__main__': unittest.main(verbosity=2)
malemburg/epcon
refs/heads/ep2017
documents/badge/ep2012/conf.py
7
# -*- coding: UTF-8 -*- from PIL import Image, ImageFont from PyQRNative import QRCode, QRErrorCorrectLevel _FONT_NAME = 'Arial_Unicode.ttf' _FONTS = { 'name': ImageFont.truetype(_FONT_NAME, 16 * 8), 'name_small': ImageFont.truetype(_FONT_NAME, 10 * 8), 'info': ImageFont.truetype(_FONT_NAME, 8 * 8), } PY_LOGO = Image.open('logo.png').convert('RGBA').resize((64, 64)) def tickets(tickets): groups = {} for k in ('staff', 'lite', 'standard', 'day1', 'day2', 'day3', 'day4', 'day5'): groups[k] = { 'image': Image.open(k + '.png').convert('RGBA'), 'attendees': [], } for t in tickets: if t.get('staff'): g = 'staff' else: if t['fare']['code'][2] == 'D': g = 'day' + t['days'].split(',')[0] if g not in groups: g = 'day1' elif t['fare']['code'][2] == 'S': g = 'standard' elif t['fare']['code'][2] == 'L': g = 'lite' else: 1/0 groups[g]['attendees'].append(t) for v in groups.values(): v['attendees'].sort(key=lambda x: x['name']) return groups # http://stackoverflow.com/questions/765736/using-pil-to-make-all-white-pixels-transparent#answer-4531395 def distance2(a, b): return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]) + (a[2] - b[2]) * (a[2] - b[2]) def makeColorTransparent(image, color, thresh2=0): from PIL import ImageMath image = image.convert("RGBA") red, green, blue, alpha = image.split() image.putalpha(ImageMath.eval("""convert(((((t - d(c, (r, g, b))) >> 31) + 1) ^ 1) * a, 'L')""", t=thresh2, d=distance2, c=color, r=red, g=green, b=blue, a=alpha)) return image def ticket(image, ticket, utils): image = image.copy() if not ticket: return image import string _multi = ( 'pier maria', 'gian battista', 'arnaldo miguel', 'dr. yves', 'dr. stefan', 'mr yun', ) check = ticket['name'].lower() for x in _multi: if check.startswith(x): first_name = ticket['name'][:len(x)].strip() last_name = ticket['name'][len(x):].strip() break else: try: first_name, last_name = ticket['name'].split(' ', 1) except ValueError: first_name = ticket['name'] last_name = '' tagline = ticket.get('tagline', '').strip() first_name = first_name.upper().strip() last_name = string.capwords(last_name.strip()) color_name = 75, 129, 135 color_info = 125, 111, 96 w = image.size[0] / 2 name_width = max( _FONTS['name'].getsize(first_name)[0], _FONTS['name'].getsize(last_name)[0]) if name_width > w - 60: font = _FONTS['name_small'] name_y = 400, 510 else: font = _FONTS['name'] name_y = 460, 590 if ticket['badge_image']: logo = Image.open(ticket['badge_image']).resize((64, 64)) if logo.mode != 'RGBA': if logo.mode == 'LA': logo = logo.convert('RGBA') else: if logo.mode != 'RGB': logo = logo.convert('RGB') logo = makeColorTransparent(logo, logo.getpixel((0, 0)), thresh2=150) else: logo = PY_LOGO rows = [ (first_name, (50, name_y[0]), font, color_name), (last_name, (50, name_y[1]), font, color_name), (tagline, (50, 880), _FONTS['info'], color_info), ] + [ (logo, (50 + (logo.size[0] + 20) * ix, 700)) for ix in range(ticket.get('experience', 0)) ] mirrored = [ (row[0], ) + ((w + row[1][0], row[1][1]),) + row[2:] for row in rows ] for row in rows + mirrored: if isinstance(row[0], Image.Image): image.paste(row[0], row[1], row[0]) else: t, pos, font, color = row utils['draw_info'](image, w - 60, t, pos, font, color) if ticket.get('profile-link'): qr = QRCode(8, QRErrorCorrectLevel.H) qr.addData(ticket['profile-link']) qr.make() im = qr.makeImage().resize((int(18*0.03937*300), int(18*0.03937*300))) image.paste(im, (w + 600, 1030)) return image
mattclay/ansible
refs/heads/devel
lib/ansible/utils/sentinel.py
93
# Copyright (c) 2019 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type class Sentinel: """ Object which can be used to mark whether an entry as being special A sentinel value demarcates a value or marks an entry as having a special meaning. In C, the Null byte is used as a sentinel for the end of a string. In Python, None is often used as a Sentinel in optional parameters to mean that the parameter was not set by the user. You should use None as a Sentinel value any Python code where None is not a valid entry. If None is a valid entry, though, then you need to create a different value, which is the purpose of this class. Example of using Sentinel as a default parameter value:: def confirm_big_red_button(tristate=Sentinel): if tristate is Sentinel: print('You must explicitly press the big red button to blow up the base') elif tristate is True: print('Countdown to destruction activated') elif tristate is False: print('Countdown stopped') elif tristate is None: print('Waiting for more input') Example of using Sentinel to tell whether a dict which has a default value has been changed:: values = {'one': Sentinel, 'two': Sentinel} defaults = {'one': 1, 'two': 2} # [.. Other code which does things including setting a new value for 'one' ..] values['one'] = None # [..] print('You made changes to:') for key, value in values.items(): if value is Sentinel: continue print('%s: %s' % (key, value) """ def __new__(cls): """ Return the cls itself. This makes both equality and identity True for comparing the class to an instance of the class, preventing common usage errors. Preferred usage:: a = Sentinel if a is Sentinel: print('Sentinel value') However, these are True as well, eliminating common usage errors:: if Sentinel is Sentinel(): print('Sentinel value') if Sentinel == Sentinel(): print('Sentinel value') """ return cls
aostapenko/manila
refs/heads/master
manila/tests/runtime_conf.py
2
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo.config import cfg CONF = cfg.CONF CONF.register_opt(cfg.IntOpt('runtime_answer', default=54, help='test flag'))
anistark/mozillians
refs/heads/master
vendor-local/lib/python/rest_framework/utils/mediatypes.py
7
""" Handling of media types, as found in HTTP Content-Type and Accept headers. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7 """ from __future__ import unicode_literals from django.http.multipartparser import parse_header from rest_framework import HTTP_HEADER_ENCODING def media_type_matches(lhs, rhs): """ Returns ``True`` if the media type in the first argument <= the media type in the second argument. The media types are strings as described by the HTTP spec. Valid media type strings include: 'application/json; indent=4' 'application/json' 'text/*' '*/*' """ lhs = _MediaType(lhs) rhs = _MediaType(rhs) return lhs.match(rhs) def order_by_precedence(media_type_lst): """ Returns a list of sets of media type strings, ordered by precedence. Precedence is determined by how specific a media type is: 3. 'type/subtype; param=val' 2. 'type/subtype' 1. 'type/*' 0. '*/*' """ ret = [set(), set(), set(), set()] for media_type in media_type_lst: precedence = _MediaType(media_type).precedence ret[3 - precedence].add(media_type) return [media_types for media_types in ret if media_types] class _MediaType(object): def __init__(self, media_type_str): if media_type_str is None: media_type_str = '' self.orig = media_type_str self.full_type, self.params = parse_header(media_type_str.encode(HTTP_HEADER_ENCODING)) self.main_type, sep, self.sub_type = self.full_type.partition('/') def match(self, other): """Return true if this MediaType satisfies the given MediaType.""" for key in self.params.keys(): if key != 'q' and other.params.get(key, None) != self.params.get(key, None): return False if self.sub_type != '*' and other.sub_type != '*' and other.sub_type != self.sub_type: return False if self.main_type != '*' and other.main_type != '*' and other.main_type != self.main_type: return False return True @property def precedence(self): """ Return a precedence level from 0-3 for the media type given how specific it is. """ if self.main_type == '*': return 0 elif self.sub_type == '*': return 1 elif not self.params or list(self.params.keys()) == ['q']: return 2 return 3 def __str__(self): return self.__unicode__().encode('utf-8') def __unicode__(self): ret = "%s/%s" % (self.main_type, self.sub_type) for key, val in self.params.items(): ret += "; %s=%s" % (key, val) return ret
ITNG/ng-utils
refs/heads/master
itng/common/views/__init__.py
1
from ..decorators import login_exempt from .form import MultipleFormView __all__ = ('LoginExemptMixin', 'PublicMixin', 'MultipleFormView') class LoginExemptMixin(object): @classmethod def as_view(cls, **kwargs): view = super(LoginExemptMixin, cls).as_view(**kwargs) return login_exempt(view) PublicMixin = LoginExemptMixin
okamstudio/godot
refs/heads/master
platform/osx/platform_osx_builders.py
21
"""Functions used to generate source files during build time All such functions are invoked in a subprocess on Windows to prevent build flakiness. """ import os from platform_methods import subprocess_main def make_debug_osx(target, source, env): if (env["macports_clang"] != 'no'): mpprefix = os.environ.get("MACPORTS_PREFIX", "/opt/local") mpclangver = env["macports_clang"] os.system(mpprefix + '/libexec/llvm-' + mpclangver + '/bin/llvm-dsymutil {0} -o {0}.dSYM'.format(target[0])) else: os.system('dsymutil {0} -o {0}.dSYM'.format(target[0])) os.system('strip -u -r {0}'.format(target[0])) if __name__ == '__main__': subprocess_main(globals())
cournape/pig-it
refs/heads/master
pygit/test.py
1
import os from binascii import \ a2b_hex from object import \ from_filename, Blob, Tree, RawEntry, parse_object, CommitHeader, \ Commit SHA1_TO_FILE = { '1b8ae996b7685aa07180a050332df81e0a6be40e': 'commit1', '815fa52ea791bf9a0d152ca3386d61d3ad023a5a': 'tree1', '00909da106de7af4a10f609de58136c47ca3221e': 'tree2', '379bf459121513d43d0758e2b57629c064a5f727': 'tree3', '6ff9ac7448e894a8df4bbb6dc248f8fac255c86b': 'subdir1', 'a94e2db7b97aab44f1ec897c10e0bdf2e5dbd80f': 'README', 'dc1b915cba9cd6efd61c353fefb96823aaf2dd8f': 'TODO'} FILE_TO_SHA1 = dict([(v, k) for k, v in SHA1_TO_FILE.items()]) # Raw content of each git object (as they are on-disk, excluding header) SHA1_TO_CONTENT = { '1b8ae996b7685aa07180a050332df81e0a6be40e': """\ tree 815fa52ea791bf9a0d152ca3386d61d3ad023a5a author David Cournapeau <cournape@gmail.com> 1254378435 +0900 committer David Cournapeau <cournape@gmail.com> 1254378435 +0900 Initial commit.\n""", '815fa52ea791bf9a0d152ca3386d61d3ad023a5a': '%d %s\0%s' % (100644, 'TODO', a2b_hex(FILE_TO_SHA1['TODO'])), '00909da106de7af4a10f609de58136c47ca3221e': '%d %s\0%s' % (100644, 'README', a2b_hex(FILE_TO_SHA1['README'])) + \ '%d %s\0%s' % (100644, 'TODO', a2b_hex(FILE_TO_SHA1['TODO'])), '379bf459121513d43d0758e2b57629c064a5f727': '%d %s\0%s' % (100644, 'README', a2b_hex(FILE_TO_SHA1['README'])) + \ '%d %s\0%s' % (100644, 'TODO', a2b_hex(FILE_TO_SHA1['TODO'])) + \ '%d %s\0%s' % (40000, 'subdir1', a2b_hex(FILE_TO_SHA1['subdir1'])), 'dc1b915cba9cd6efd61c353fefb96823aaf2dd8f': 'TODO Content.\n'} class TestRawObject: """Test that we parse raw objects correctly: we just test whether we parse the header correctly, and that content match with the one hardcoded in SHA1_TO_CONTENT.""" def test(self): for sha1, ref_content in SHA1_TO_CONTENT.items(): f = open(SHA1_TO_FILE[sha1]) try: content = parse_object(f.read())[0] assert content == ref_content finally: f.close() class TestBlob: def test_from_content(self): sha1name = 'dc1b915cba9cd6efd61c353fefb96823aaf2dd8f' content = SHA1_TO_CONTENT[sha1name] blob = Blob(content) assert blob.sha1() == sha1name def test_parse(self): # file which contains the content of a blob object filename = 'TODO' o = from_filename(filename) try: real_filename = SHA1_TO_FILE[o.sha1()] assert real_filename == filename except KeyError: assert False, "Wrong sha1" assert o.content == SHA1_TO_CONTENT[o.sha1()] class TestTree: def test_from_entries(self): sha1name = '815fa52ea791bf9a0d152ca3386d61d3ad023a5a' raw_entries = [RawEntry(os.stat('TODO').st_mode, 'TODO', FILE_TO_SHA1['TODO'])] tree = Tree(raw_entries) assert tree.sha1() == sha1name def test_simple_parse(self): # file which contains the content of a tree object for filename in ['tree1', 'tree2']: o = from_filename(filename) assert o.sha1() == FILE_TO_SHA1[filename] # Testing for sha1 should be enough, but we double check here assert o.content == SHA1_TO_CONTENT[o.sha1()] def test_simple_parse2(self): # this tree contains a subtree filename = 'tree3' o = from_filename(filename) assert o.sha1() == FILE_TO_SHA1[filename] # Testing for sha1 should be enough, but we double check here assert o.content == SHA1_TO_CONTENT[o.sha1()] class TestCommit: def test_from_content(self): author = 'David Cournapeau <cournape@gmail.com> 1254378435 +0900' committer = 'David Cournapeau <cournape@gmail.com> 1254378435 +0900' tree = '815fa52ea791bf9a0d152ca3386d61d3ad023a5a' message = "Initial commit.\n" header = CommitHeader(author, committer, tree) commit = Commit(header, message) assert commit.content[:30] == SHA1_TO_CONTENT[FILE_TO_SHA1['commit1']][:30] assert commit.sha1() == FILE_TO_SHA1['commit1']
AutorestCI/azure-sdk-for-python
refs/heads/master
azure-mgmt-rdbms/azure/mgmt/rdbms/mysql/operations/check_name_availability_operations.py
1
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- import uuid from msrest.pipeline import ClientRawResponse from msrestazure.azure_exceptions import CloudError from .. import models class CheckNameAvailabilityOperations(object): """CheckNameAvailabilityOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An objec model deserializer. :ivar api_version: The API version to use for the request. Constant value: "2017-04-30-preview". """ def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self.api_version = "2017-04-30-preview" self.config = config def execute( self, name, type=None, custom_headers=None, raw=False, **operation_config): """Check the availability of name for resource. :param name: Resource name to verify. :type name: str :param type: Resource type used for verification. :type type: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: NameAvailability or ClientRawResponse if raw=true :rtype: ~azure.mgmt.rdbms.mysql.models.NameAvailability or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ name_availability_request = models.NameAvailabilityRequest(name=name, type=type) # Construct URL url = '/subscriptions/{subscriptionId}/providers/Microsoft.DBforMySQL/checkNameAvailability' path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(name_availability_request, 'NameAvailabilityRequest') # Construct and send request request = self._client.post(url, query_parameters) response = self._client.send( request, header_parameters, body_content, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp deserialized = None if response.status_code == 200: deserialized = self._deserialize('NameAvailability', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
gdimitris/ChessPuzzlerBackend
refs/heads/master
Virtual_Environment/lib/python2.7/site-packages/migrate/versioning/util/__init__.py
33
#!/usr/bin/env python # -*- coding: utf-8 -*- """.. currentmodule:: migrate.versioning.util""" import warnings import logging from decorator import decorator from pkg_resources import EntryPoint import six from sqlalchemy import create_engine from sqlalchemy.engine import Engine from sqlalchemy.pool import StaticPool from migrate import exceptions from migrate.versioning.util.keyedinstance import KeyedInstance from migrate.versioning.util.importpath import import_path log = logging.getLogger(__name__) def load_model(dotted_name): """Import module and use module-level variable". :param dotted_name: path to model in form of string: ``some.python.module:Class`` .. versionchanged:: 0.5.4 """ if isinstance(dotted_name, six.string_types): if ':' not in dotted_name: # backwards compatibility warnings.warn('model should be in form of module.model:User ' 'and not module.model.User', exceptions.MigrateDeprecationWarning) dotted_name = ':'.join(dotted_name.rsplit('.', 1)) return EntryPoint.parse('x=%s' % dotted_name).load(False) else: # Assume it's already loaded. return dotted_name def asbool(obj): """Do everything to use object as bool""" if isinstance(obj, six.string_types): obj = obj.strip().lower() if obj in ['true', 'yes', 'on', 'y', 't', '1']: return True elif obj in ['false', 'no', 'off', 'n', 'f', '0']: return False else: raise ValueError("String is not true/false: %r" % obj) if obj in (True, False): return bool(obj) else: raise ValueError("String is not true/false: %r" % obj) def guess_obj_type(obj): """Do everything to guess object type from string Tries to convert to `int`, `bool` and finally returns if not succeded. .. versionadded: 0.5.4 """ result = None try: result = int(obj) except: pass if result is None: try: result = asbool(obj) except: pass if result is not None: return result else: return obj @decorator def catch_known_errors(f, *a, **kw): """Decorator that catches known api errors .. versionadded: 0.5.4 """ try: return f(*a, **kw) except exceptions.PathFoundError as e: raise exceptions.KnownError("The path %s already exists" % e.args[0]) def construct_engine(engine, **opts): """.. versionadded:: 0.5.4 Constructs and returns SQLAlchemy engine. Currently, there are 2 ways to pass create_engine options to :mod:`migrate.versioning.api` functions: :param engine: connection string or a existing engine :param engine_dict: python dictionary of options to pass to `create_engine` :param engine_arg_*: keyword parameters to pass to `create_engine` (evaluated with :func:`migrate.versioning.util.guess_obj_type`) :type engine_dict: dict :type engine: string or Engine instance :type engine_arg_*: string :returns: SQLAlchemy Engine .. note:: keyword parameters override ``engine_dict`` values. """ if isinstance(engine, Engine): return engine elif not isinstance(engine, six.string_types): raise ValueError("you need to pass either an existing engine or a database uri") # get options for create_engine if opts.get('engine_dict') and isinstance(opts['engine_dict'], dict): kwargs = opts['engine_dict'] else: kwargs = dict() # DEPRECATED: handle echo the old way echo = asbool(opts.get('echo', False)) if echo: warnings.warn('echo=True parameter is deprecated, pass ' 'engine_arg_echo=True or engine_dict={"echo": True}', exceptions.MigrateDeprecationWarning) kwargs['echo'] = echo # parse keyword arguments for key, value in six.iteritems(opts): if key.startswith('engine_arg_'): kwargs[key[11:]] = guess_obj_type(value) log.debug('Constructing engine') # TODO: return create_engine(engine, poolclass=StaticPool, **kwargs) # seems like 0.5.x branch does not work with engine.dispose and staticpool return create_engine(engine, **kwargs) @decorator def with_engine(f, *a, **kw): """Decorator for :mod:`migrate.versioning.api` functions to safely close resources after function usage. Passes engine parameters to :func:`construct_engine` and resulting parameter is available as kw['engine']. Engine is disposed after wrapped function is executed. .. versionadded: 0.6.0 """ url = a[0] engine = construct_engine(url, **kw) try: kw['engine'] = engine return f(*a, **kw) finally: if isinstance(engine, Engine) and engine is not url: log.debug('Disposing SQLAlchemy engine %s', engine) engine.dispose() class Memoize(object): """Memoize(fn) - an instance which acts like fn but memoizes its arguments Will only work on functions with non-mutable arguments ActiveState Code 52201 """ def __init__(self, fn): self.fn = fn self.memo = {} def __call__(self, *args): if args not in self.memo: self.memo[args] = self.fn(*args) return self.memo[args]
meolu/walle-web
refs/heads/master
walle/config/settings.py
1
# -*- coding: utf-8 -*- """Application configuration.""" import os from datetime import timedelta class Config(object): """Base configuration.""" VERSION = '2.0.1' SECRET_KEY = os.environ.get('WALLE_SECRET', 'secret-key') APP_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir)) BCRYPT_LOG_ROUNDS = 13 ASSETS_DEBUG = False WTF_CSRF_ENABLED = False DEBUG_TB_ENABLED = False DEBUG_TB_INTERCEPT_REDIRECTS = False # Can be "memcached", "redis", etc. CACHE_TYPE = 'simple' SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_COMMIT_ON_TEARDOWN = True LOGIN_DISABLED = False # 设置session的保存时间。 PERMANENT_SESSION_LIFETIME = timedelta(days=1) # 前端项目部署路径 FE_PATH = os.path.abspath(PROJECT_ROOT + '/fe/') + '/' AVATAR_PATH = '/avatar/' UPLOAD_AVATAR = FE_PATH + AVATAR_PATH # 邮箱配置 MAIL_SERVER = 'smtp.exmail.qq.com' MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USE_TLS = False MAIL_DEFAULT_SENDER = 'service@walle-web.io' MAIL_USERNAME = 'service@walle-web.io' MAIL_PASSWORD = 'Ki9y&3U82' # 日志 LOG_PATH = os.path.join(PROJECT_ROOT, 'logs') LOG_PATH_ERROR = os.path.join(LOG_PATH, 'error.log') LOG_PATH_INFO = os.path.join(LOG_PATH, 'info.log') LOG_FILE_MAX_BYTES = 100 * 1024 * 1024 # 轮转数量是 10 个 LOG_FILE_BACKUP_COUNT = 10 LOG_FORMAT = "%(asctime)s %(thread)d %(message)s" # 登录cookie 防止退出浏览器重新登录 COOKIE_ENABLE = False
m8ttyB/socorro
refs/heads/master
alembic/versions/e4d30f140ed_add_new_rule_to_copy.py
14
"""Add new rule to copy Plugin url and comment Revision ID: e4d30f140ed Revises: 22e4e60e03f Create Date: 2013-05-22 08:01:54.873655 """ # revision identifiers, used by Alembic. revision = 'e4d30f140ed' down_revision = '22e4e60e03f' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql import sqlalchemy.types as types from sqlalchemy.sql import table, column class CITEXT(types.UserDefinedType): name = 'citext' def get_col_spec(self): return 'CITEXT' def bind_processor(self, dialect): def process(value): return value return process def result_processor(self, dialect, coltype): def process(value): return value return process def __repr__(self): return "citext" def upgrade(): transform_rule = table('transform_rules', column(u'transform_rule_id', sa.INTEGER()), column(u'category', CITEXT()), column(u'rule_order', sa.INTEGER()), column(u'action', sa.TEXT()), column(u'action_args', sa.TEXT()), column(u'action_kwargs', sa.TEXT()), column(u'predicate', sa.TEXT()), column(u'predicate_args', sa.TEXT()), column(u'predicate_kwargs', sa.TEXT())) # Indexes op.bulk_insert(transform_rule, [{ "category": 'processor.json_rewrite' , "predicate": 'socorro.lib.transform_rules.is_not_null_predicate' , "predicate_args": '' , "predicate_kwargs": 'key="PluginContentURL"' , "action": 'socorro.processor.processor.json_reformat_action' , "action_args": '' , "action_kwargs": 'key="URL", format_str="%(PluginContentURL)s"' , "rule_order": '5' }, { "category": 'processor.json_rewrite' , "predicate": 'socorro.lib.transform_rules.is_not_null_predicate' , "predicate_args": '' , "predicate_kwargs": 'key="PluginUserComment"' , "action": 'socorro.processor.processor.json_reformat_action' , "action_args": '' , "action_kwargs": 'key="Comments", format_str="%(PluginUserComment)s"' , "rule_order": '6' }]) def downgrade(): op.execute(""" DELETE from transform_rules where action_kwargs IN ('key="Comments", format_str="%(PluginUserComment)s"' , 'key="URL", format_str="%(PluginContentURL)s"'); """)
juanmirocks/LocText
refs/heads/develop
resources/features/selected/0_False_LinearSVC-1486292275.065055-NAMES.py
2
[ "SentenceFeatureGenerator::1.1_counts_individual_int_individual_e_1_[0]", # 0 "SentenceFeatureGenerator::1.1_counts_individual_int_individual_e_3_[0]", # 1 "SentenceFeatureGenerator::3_order_[0]", # 2 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_1_<NOUN>_[0]", # 3 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<[SOURCE ~~ PUNCT>_[0]", # 4 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<PUNCT ~~ VERB>_[0]", # 5 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<NOUN ~~ NOUN>_[0]", # 6 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<VERB ~~ NOUN ~~ PUNCT>_[0]", # 7 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NOUN ~~ PUNCT ~~ ADJ>_[0]", # 8 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NOUN ~~ PUNCT ~~ NOUN>_[0]", # 9 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<PUNCT ~~ NOUN ~~ NOUN>_[0]", # 10 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<as>_[0]", # 11 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<an>_[0]", # 12 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_1_<ADP>_[0]", # 13 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_1_<NUM>_[0]", # 14 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_1_<DET>_[0]", # 15 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<[SOURCE ~~ NOUN>_[0]", # 16 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<PUNCT ~~ DET>_[0]", # 17 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_1_<VERB>_[0]", # 18 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_1_<NOUN>_[0]", # 19 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_1_<nsubj>_[0]", # 20 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_1_<prep>_[0]", # 21 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_2_<NOUN ~~ NOUN>_[0]", # 22 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<[SOURCE ~~ VERB ~~ ADP>_[0]", # 23 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<VERB ~~ ADP ~~ NOUN>_[0]", # 24 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<ADP ~~ NOUN ~~ NOUN>_[0]", # 25 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<prep ~~ pobj ~~ appos>_[0]", # 26 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_1_<PROPN>_[0]", # 27 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<e_1 ~~ e_1>_[0]", # 28 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<DET ~~ ADJ>_[0]", # 29 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<NOUN ~~ PROPN>_[0]", # 30 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<PUNCT ~~ CONJ>_[0]", # 31 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<PUNCT ~~ CONJ ~~ DET>_[0]", # 32 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<CONJ ~~ DET ~~ TARGET]>_[0]", # 33 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<[SOURCE ~~ VERB>_[0]", # 34 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NOUN ~~ PUNCT ~~ TARGET]>_[0]", # 35 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<amod ~~ appos>_[0]", # 36 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<[SOURCE ~~ NOUN ~~ TARGET]>_[0]", # 37 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_3_<[SOURCE ~~ form ~~ form>_[0]", # 38 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<,>_[0]", # 39 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<[SOURCE ~~ ,>_[0]", # 40 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<, ~~ TARGET]>_[0]", # 41 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<to>_[0]", # 42 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<exit>_[0]", # 43 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_1_<advcl>_[0]", # 44 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_2_<VERB ~~ VERB>_[0]", # 45 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<pobj ~~ prep>_[0]", # 46 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<prep ~~ advcl>_[0]", # 47 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<in>_[0]", # 48 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<ADP ~~ NOUN>_[0]", # 49 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<ADP ~~ ADJ>_[0]", # 50 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<[SOURCE ~~ VERB ~~ VERB>_[0]", # 51 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<VERB ~~ VERB ~~ ADP>_[0]", # 52 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_1_<dobj>_[0]", # 53 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<nsubj ~~ advcl>_[0]", # 54 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<dobj ~~ amod>_[0]", # 55 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<VERB ~~ NOUN ~~ TARGET]>_[0]", # 56 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<mutant>_[0]", # 57 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_1_<SYM>_[0]", # 58 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<, ~~ the>_[0]", # 59 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<DET ~~ PROPN>_[0]", # 60 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_3_<the ~~ e_1 ~~ e_1>_[0]", # 61 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<accumulate>_[0]", # 62 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_2_<VERB ~~ ADJ>_[0]", # 63 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_2_<ADP ~~ TARGET]>_[0]", # 64 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<acl ~~ prep>_[0]", # 65 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<[SOURCE ~~ NOUN ~~ ADP>_[0]", # 66 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<NOUN ~~ ADP ~~ NOUN>_[0]", # 67 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<ADP ~~ NOUN ~~ ADP>_[0]", # 68 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<NOUN ~~ ADP ~~ VERB>_[0]", # 69 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<pobj ~~ prep ~~ pobj>_[0]", # 70 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<acl ~~ prep ~~ pobj>_[0]", # 71 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<cell>_[0]", # 72 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<with>_[0]", # 73 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<the ~~ e_2>_[0]", # 74 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<e_2 ~~ of>_[0]", # 75 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<e_1 ~~ and>_[0]", # 76 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<with ~~ the>_[0]", # 77 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NOUN ~~ ADP ~~ NOUN>_[0]", # 78 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<ADP ~~ NOUN ~~ VERB>_[0]", # 79 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<DET ~~ PROPN ~~ NOUN>_[0]", # 80 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NOUN ~~ ADP ~~ DET>_[0]", # 81 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_1_<nsubjpass>_[0]", # 82 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<VERB ~~ DET ~~ TARGET]>_[0]", # 83 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<of>_[0]", # 84 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<cell>_[0]", # 85 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<[SOURCE ~~ of>_[0]", # 86 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_2_<NOUN ~~ VERB>_[0]", # 87 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<prep ~~ pobj ~~ acl>_[0]", # 88 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<dobj ~~ acl>_[0]", # 89 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<acl ~~ pobj>_[0]", # 90 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<amod ~~ prep>_[0]", # 91 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<amod ~~ prep ~~ pobj>_[0]", # 92 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<[SOURCE ~~ in>_[0]", # 93 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<pobj ~~ compound>_[0]", # 94 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<be>_[0]", # 95 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<class>_[0]", # 96 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<relate>_[0]", # 97 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<on ~~ TARGET]>_[0]", # 98 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<ADP ~~ TARGET]>_[0]", # 99 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<[SOURCE ~~ VERB ~~ DET>_[0]", # 100 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<be>_[0]", # 101 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<NOUN ~~ NOUN ~~ VERB>_[0]", # 102 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<NOUN ~~ CONJ>_[0]", # 103 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<CONJ ~~ VERB>_[0]", # 104 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<DET ~~ NOUN ~~ PUNCT>_[0]", # 105 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<CONJ ~~ VERB ~~ VERB>_[0]", # 106 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<VERB ~~ ADP ~~ ADJ>_[0]", # 107 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_1_<nummod>_[0]", # 108 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<VERB ~~ VERB ~~ ADP>_[0]", # 109 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<expression>_[0]", # 110 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NOUN ~~ ADP ~~ TARGET]>_[0]", # 111 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<) ~~ be>_[0]", # 112 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<PROPN ~~ PUNCT>_[0]", # 113 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<VERB ~~ ADJ ~~ NOUN>_[0]", # 114 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NOUN ~~ ADP ~~ VERB>_[0]", # 115 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<from>_[0]", # 116 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_1_<acomp>_[0]", # 117 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_1_<advmod>_[0]", # 118 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<pcomp ~~ prep>_[0]", # 119 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<nsubj ~~ acomp ~~ prep>_[0]", # 120 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<with ~~ e_1>_[0]", # 121 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<ADP ~~ PROPN>_[0]", # 122 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<PROPN ~~ ADP>_[0]", # 123 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<VERB ~~ PROPN>_[0]", # 124 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_3_<[SOURCE ~~ colocalizes ~~ with>_[0]", # 125 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NUM ~~ ADP ~~ DET>_[0]", # 126 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<DET ~~ NOUN ~~ TARGET]>_[0]", # 127 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_3_<[SOURCE ~~ and ~~ e_1>_[0]", # 128 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_2_<[SOURCE ~~ PROPN>_[0]", # 129 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<conj ~~ pobj>_[0]", # 130 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<conj ~~ conj>_[0]", # 131 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<[SOURCE ~~ in>_[0]", # 132 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<[SOURCE ~~ NOUN ~~ TARGET]>_[0]", # 133 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<transporter>_[0]", # 134 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<that>_[0]", # 135 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<e_1 ~~ ,>_[0]", # 136 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<ADV ~~ VERB>_[0]", # 137 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_3_<e_1 ~~ e_1 ~~ ,>_[0]", # 138 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_3_<e_1 ~~ ( ~~ e_1>_[0]", # 139 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NOUN ~~ NOUN ~~ NUM>_[0]", # 140 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<VERB ~~ ADV ~~ VERB>_[0]", # 141 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_2_<NOUN ~~ PROPN>_[0]", # 142 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<appos ~~ appos>_[0]", # 143 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<[SOURCE ~~ PUNCT ~~ NOUN>_[0]", # 144 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<both>_[0]", # 145 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<e_3>_[0]", # 146 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<localize ~~ to>_[0]", # 147 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<of ~~ e_3>_[0]", # 148 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<PUNCT ~~ ADP>_[0]", # 149 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<ADP ~~ PROPN ~~ NUM>_[0]", # 150 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<pobj ~~ amod>_[0]", # 151 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<prep ~~ pobj ~~ amod>_[0]", # 152 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<DET ~~ NOUN ~~ PART>_[0]", # 153 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<prep ~~ nsubj>_[0]", # 154 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<ccomp ~~ dobj>_[0]", # 155 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<pobj ~~ prep ~~ nsubj>_[0]", # 156 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<with ~~ TARGET]>_[0]", # 157 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_1_<nmod>_[0]", # 158 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_1_<agent>_[0]", # 159 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_2_<ADV ~~ VERB>_[0]", # 160 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<of ~~ a>_[0]", # 161 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<PROPN ~~ VERB>_[0]", # 162 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<involve ~~ in>_[0]", # 163 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<protein>_[0]", # 164 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<VERB ~~ NOUN ~~ ADP>_[0]", # 165 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<protein>_[0]", # 166 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<of ~~ activity>_[0]", # 167 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<and ~~ the>_[0]", # 168 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NOUN ~~ PUNCT ~~ CONJ>_[0]", # 169 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<DET ~~ NOUN ~~ NOUN>_[0]", # 170 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<[SOURCE ~~ protein>_[0]", # 171 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<DET ~~ VERB ~~ NOUN>_[0]", # 172 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<conj ~~ nsubj>_[0]", # 173 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<e_3 ~~ TARGET]>_[0]", # 174 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<nsubj ~~ dobj>_[0]", # 175 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<PUNCT ~~ ADP ~~ NOUN>_[0]", # 176 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<tag>_[0]", # 177 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<advmod ~~ dobj>_[0]", # 178 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<advmod ~~ dobj ~~ compound>_[0]", # 179 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<gene>_[0]", # 180 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<[SOURCE ~~ by>_[0]", # 181 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NOUN ~~ NOUN ~~ PROPN>_[0]", # 182 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NOUN ~~ PROPN ~~ PROPN>_[0]", # 183 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<activate>_[0]", # 184 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<require>_[0]", # 185 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<biogenesis>_[0]", # 186 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<modulates>_[0]", # 187 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<glycosylation>_[0]", # 188 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NOUN ~~ ADJ ~~ NOUN>_[0]", # 189 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<expression ~~ TARGET]>_[0]", # 190 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<and ~~ TARGET]>_[0]", # 191 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<PUNCT ~~ CONJ ~~ TARGET]>_[0]", # 192 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<NOUN ~~ NOUN ~~ ADP>_[0]", # 193 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<DET ~~ ADV>_[0]", # 194 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<VERB ~~ VERB ~~ PART>_[0]", # 195 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<be ~~ protein>_[0]", # 196 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<induce>_[0]", # 197 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<e_2 ~~ and>_[0]", # 198 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<and ~~ inhibit>_[0]", # 199 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<retention ~~ inhibit>_[0]", # 200 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<ADP ~~ ADP ~~ TARGET]>_[0]", # 201 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<nsubj ~~ dobj ~~ compound>_[0]", # 202 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<compound ~~ conj>_[0]", # 203 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<dobj ~~ advcl>_[0]", # 204 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<pobj ~~ prep ~~ dobj>_[0]", # 205 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<function ~~ TARGET]>_[0]", # 206 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<VERB ~~ ADJ ~~ TARGET]>_[0]", # 207 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<nmod ~~ pobj>_[0]", # 208 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<ADP ~~ PROPN ~~ TARGET]>_[0]", # 209 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_3_<[SOURCE ~~ be ~~ require>_[0]", # 210 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<PUNCT ~~ ADV ~~ PUNCT>_[0]", # 211 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<function>_[0]", # 212 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<of ~~ e_1>_[0]", # 213 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_3_<- ~~ independent ~~ function>_[0]", # 214 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_3_<[SOURCE ~~ function ~~ require>_[0]", # 215 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<of ~~ function>_[0]", # 216 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_3_<[SOURCE ~~ of ~~ function>_[0]", # 217 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<pobj ~~ prep ~~ nsubjpass>_[0]", # 218 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<pobj ~~ nmod>_[0]", # 219 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<prep ~~ pobj ~~ nmod>_[0]", # 220 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<PUNCT ~~ ADP ~~ VERB>_[0]", # 221 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<signal>_[0]", # 222 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<[SOURCE ~~ signal>_[0]", # 223 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<amod ~~ nsubj>_[0]", # 224 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<show>_[0]", # 225 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<dobj ~~ ccomp>_[0]", # 226 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<ubiquitination>_[0]", # 227 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<ubiquitination>_[0]", # 228 "DependencyFeatureGenerator::23_PD_pos_N_gram_PD_3_<[SOURCE ~~ ADP ~~ TARGET]>_[0]", # 229 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<activation>_[0]", # 230 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NOUN ~~ VERB ~~ PROPN>_[0]", # 231 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NUM ~~ NOUN ~~ ADP>_[0]", # 232 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<region>_[0]", # 233 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<ADJ ~~ ADP ~~ PROPN>_[0]", # 234 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<nsubj ~~ advcl ~~ nsubjpass>_[0]", # 235 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_3_<e_1 ~~ , ~~ the>_[0]", # 236 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<advcl ~~ prep>_[0]", # 237 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<[SOURCE ~~ from>_[0]", # 238 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<into ~~ TARGET]>_[0]", # 239 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<ADP ~~ ADJ ~~ TARGET]>_[0]", # 240 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<ADV ~~ TARGET]>_[0]", # 241 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<this>_[0]", # 242 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<DET ~~ ADJ ~~ ADJ>_[0]", # 243 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<ADP ~~ PROPN ~~ PUNCT>_[0]", # 244 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<compromise>_[0]", # 245 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<fuse>_[0]", # 246 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<acl ~~ acomp>_[0]", # 247 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NOUN ~~ PUNCT ~~ PUNCT>_[0]", # 248 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<vesicle>_[0]", # 249 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<dispensable>_[0]", # 250 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<be ~~ dispensable>_[0]", # 251 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<dispensable ~~ for>_[0]", # 252 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_3_<be ~~ dispensable ~~ for>_[0]", # 253 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<e_1 ~~ to>_[0]", # 254 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<location>_[0]", # 255 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<[SOURCE ~~ location>_[0]", # 256 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<[SOURCE ~~ location>_[0]", # 257 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<, ~~ to>_[0]", # 258 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<, ~~ while>_[0]", # 259 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_2_<appos ~~ compound>_[0]", # 260 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<PUNCT ~~ VERB ~~ TARGET]>_[0]", # 261 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<important>_[0]", # 262 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<morphology>_[0]", # 263 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<pobj ~~ amod ~~ npadvmod>_[0]", # 264 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<defect>_[0]", # 265 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<cohesin>_[0]", # 266 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<assembly>_[0]", # 267 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_3_<[SOURCE ~~ determine ~~ localize>_[0]", # 268 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<[SOURCE ~~ TARGET]>_[0]", # 269 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<significantly>_[0]", # 270 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<be ~~ significantly>_[0]", # 271 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<at ~~ have>_[0]", # 272 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_3_<[SOURCE ~~ at ~~ have>_[0]", # 273 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_3_<[SOURCE ~~ recruitment ~~ of>_[0]", # 274 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<prep ~~ nsubj ~~ prep>_[0]", # 275 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_3_<[SOURCE ~~ domain ~~ of>_[0]", # 276 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_3_<[SOURCE ~~ domain ~~ of>_[0]", # 277 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<reconfiguring>_[0]", # 278 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<division ~~ TARGET]>_[0]", # 279 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<abundance ~~ TARGET]>_[0]", # 280 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<eliminate>_[0]", # 281 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<from ~~ through>_[0]", # 282 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_3_<from ~~ through ~~ TARGET]>_[0]", # 283 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_1_<stress>_[0]", # 284 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<[SOURCE ~~ stress>_[0]", # 285 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_1_<stress>_[0]", # 286 "DependencyFeatureGenerator::26_PD_undirected_edges_N_gram_PD_3_<appos ~~ nsubj ~~ dobj>_[0]", # 287 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_3_<localization ~~ disrupt ~~ by>_[0]", # 288 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_3_<e_1 ~~ to ~~ TARGET]>_[0]", # 289 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<that ~~ u>_[0]", # 290 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_2_<require ~~ e_1>_[0]", # 291 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_2_<PRON ~~ NUM>_[0]", # 292 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_3_<show ~~ that ~~ u>_[0]", # 293 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_3_<first ~~ require ~~ e_1>_[0]", # 294 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<ADP ~~ PRON ~~ NUM>_[0]", # 295 "DependencyFeatureGenerator::19_LD_pos_N_gram_LD_3_<NUM ~~ ADV ~~ VERB>_[0]", # 296 "DependencyFeatureGenerator::22_PD_bow_N_gram_PD_2_<show ~~ require>_[0]", # 297 "DependencyFeatureGenerator::18_LD_bow_N_gram_LD_3_<[SOURCE ~~ to ~~ mediate>_[0]", # 298 "IsSpecificProteinType::40_is_marker_[0]", # 299 "LocalizationRelationsRatios::50_corpus_unnormalized_total_background_loc_rels_ratios_[0]", # 300 "LocalizationRelationsRatios::58_SwissProt_normalized_exists_relation_[0]", # 301 ]
adelton/django
refs/heads/master
django/utils/feedgenerator.py
183
""" Syndication feed generation library -- used for generating RSS, etc. Sample usage: >>> from django.utils import feedgenerator >>> feed = feedgenerator.Rss201rev2Feed( ... title="Poynter E-Media Tidbits", ... link="http://www.poynter.org/column.asp?id=31", ... description="A group Weblog by the sharpest minds in online media/journalism/publishing.", ... language="en", ... ) >>> feed.add_item( ... title="Hello", ... link="http://www.holovaty.com/test/", ... description="Testing." ... ) >>> with open('test.rss', 'w') as fp: ... feed.write(fp, 'utf-8') For definitions of the different versions of RSS, see: http://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss """ from __future__ import unicode_literals import datetime import warnings from django.utils import datetime_safe, six from django.utils.deprecation import RemovedInDjango20Warning from django.utils.encoding import force_text, iri_to_uri from django.utils.six import StringIO from django.utils.six.moves.urllib.parse import urlparse from django.utils.xmlutils import SimplerXMLGenerator def rfc2822_date(date): # We can't use strftime() because it produces locale-dependent results, so # we have to map english month and day names manually months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',) days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') # Support datetime objects older than 1900 date = datetime_safe.new_datetime(date) # We do this ourselves to be timezone aware, email.Utils is not tz aware. dow = days[date.weekday()] month = months[date.month - 1] time_str = date.strftime('%s, %%d %s %%Y %%H:%%M:%%S ' % (dow, month)) if six.PY2: # strftime returns a byte string in Python 2 time_str = time_str.decode('utf-8') offset = date.utcoffset() # Historically, this function assumes that naive datetimes are in UTC. if offset is None: return time_str + '-0000' else: timezone = (offset.days * 24 * 60) + (offset.seconds // 60) hour, minute = divmod(timezone, 60) return time_str + '%+03d%02d' % (hour, minute) def rfc3339_date(date): # Support datetime objects older than 1900 date = datetime_safe.new_datetime(date) time_str = date.strftime('%Y-%m-%dT%H:%M:%S') if six.PY2: # strftime returns a byte string in Python 2 time_str = time_str.decode('utf-8') offset = date.utcoffset() # Historically, this function assumes that naive datetimes are in UTC. if offset is None: return time_str + 'Z' else: timezone = (offset.days * 24 * 60) + (offset.seconds // 60) hour, minute = divmod(timezone, 60) return time_str + '%+03d:%02d' % (hour, minute) def get_tag_uri(url, date): """ Creates a TagURI. See http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id """ bits = urlparse(url) d = '' if date is not None: d = ',%s' % datetime_safe.new_datetime(date).strftime('%Y-%m-%d') return 'tag:%s%s:%s/%s' % (bits.hostname, d, bits.path, bits.fragment) class SyndicationFeed(object): "Base class for all syndication feeds. Subclasses should provide write()" def __init__(self, title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs): to_unicode = lambda s: force_text(s, strings_only=True) if categories: categories = [force_text(c) for c in categories] if ttl is not None: # Force ints to unicode ttl = force_text(ttl) self.feed = { 'title': to_unicode(title), 'link': iri_to_uri(link), 'description': to_unicode(description), 'language': to_unicode(language), 'author_email': to_unicode(author_email), 'author_name': to_unicode(author_name), 'author_link': iri_to_uri(author_link), 'subtitle': to_unicode(subtitle), 'categories': categories or (), 'feed_url': iri_to_uri(feed_url), 'feed_copyright': to_unicode(feed_copyright), 'id': feed_guid or link, 'ttl': ttl, } self.feed.update(kwargs) self.items = [] def add_item(self, title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, unique_id_is_permalink=None, enclosure=None, categories=(), item_copyright=None, ttl=None, updateddate=None, **kwargs): """ Adds an item to the feed. All args are expected to be Python Unicode objects except pubdate and updateddate, which are datetime.datetime objects, and enclosure, which is an instance of the Enclosure class. """ to_unicode = lambda s: force_text(s, strings_only=True) if categories: categories = [to_unicode(c) for c in categories] if ttl is not None: # Force ints to unicode ttl = force_text(ttl) item = { 'title': to_unicode(title), 'link': iri_to_uri(link), 'description': to_unicode(description), 'author_email': to_unicode(author_email), 'author_name': to_unicode(author_name), 'author_link': iri_to_uri(author_link), 'pubdate': pubdate, 'updateddate': updateddate, 'comments': to_unicode(comments), 'unique_id': to_unicode(unique_id), 'unique_id_is_permalink': unique_id_is_permalink, 'enclosure': enclosure, 'categories': categories or (), 'item_copyright': to_unicode(item_copyright), 'ttl': ttl, } item.update(kwargs) self.items.append(item) def num_items(self): return len(self.items) def root_attributes(self): """ Return extra attributes to place on the root (i.e. feed/channel) element. Called from write(). """ return {} def add_root_elements(self, handler): """ Add elements in the root (i.e. feed/channel) element. Called from write(). """ pass def item_attributes(self, item): """ Return extra attributes to place on each item (i.e. item/entry) element. """ return {} def add_item_elements(self, handler, item): """ Add elements on each item (i.e. item/entry) element. """ pass def write(self, outfile, encoding): """ Outputs the feed in the given encoding to outfile, which is a file-like object. Subclasses should override this. """ raise NotImplementedError('subclasses of SyndicationFeed must provide a write() method') def writeString(self, encoding): """ Returns the feed in the given encoding as a string. """ s = StringIO() self.write(s, encoding) return s.getvalue() def latest_post_date(self): """ Returns the latest item's pubdate or updateddate. If no items have either of these attributes this returns the current date/time. """ latest_date = None date_keys = ('updateddate', 'pubdate') for item in self.items: for date_key in date_keys: item_date = item.get(date_key) if item_date: if latest_date is None or item_date > latest_date: latest_date = item_date return latest_date or datetime.datetime.now() class Enclosure(object): "Represents an RSS enclosure" def __init__(self, url, length, mime_type): "All args are expected to be Python Unicode objects" self.length, self.mime_type = length, mime_type self.url = iri_to_uri(url) class RssFeed(SyndicationFeed): content_type = 'application/rss+xml; charset=utf-8' def write(self, outfile, encoding): handler = SimplerXMLGenerator(outfile, encoding) handler.startDocument() handler.startElement("rss", self.rss_attributes()) handler.startElement("channel", self.root_attributes()) self.add_root_elements(handler) self.write_items(handler) self.endChannelElement(handler) handler.endElement("rss") def rss_attributes(self): return {"version": self._version, "xmlns:atom": "http://www.w3.org/2005/Atom"} def write_items(self, handler): for item in self.items: handler.startElement('item', self.item_attributes(item)) self.add_item_elements(handler, item) handler.endElement("item") def add_root_elements(self, handler): handler.addQuickElement("title", self.feed['title']) handler.addQuickElement("link", self.feed['link']) handler.addQuickElement("description", self.feed['description']) if self.feed['feed_url'] is not None: handler.addQuickElement("atom:link", None, {"rel": "self", "href": self.feed['feed_url']}) if self.feed['language'] is not None: handler.addQuickElement("language", self.feed['language']) for cat in self.feed['categories']: handler.addQuickElement("category", cat) if self.feed['feed_copyright'] is not None: handler.addQuickElement("copyright", self.feed['feed_copyright']) handler.addQuickElement("lastBuildDate", rfc2822_date(self.latest_post_date())) if self.feed['ttl'] is not None: handler.addQuickElement("ttl", self.feed['ttl']) def endChannelElement(self, handler): handler.endElement("channel") @property def mime_type(self): warnings.warn( 'The mime_type attribute of RssFeed is deprecated. ' 'Use content_type instead.', RemovedInDjango20Warning, stacklevel=2 ) return self.content_type class RssUserland091Feed(RssFeed): _version = "0.91" def add_item_elements(self, handler, item): handler.addQuickElement("title", item['title']) handler.addQuickElement("link", item['link']) if item['description'] is not None: handler.addQuickElement("description", item['description']) class Rss201rev2Feed(RssFeed): # Spec: http://blogs.law.harvard.edu/tech/rss _version = "2.0" def add_item_elements(self, handler, item): handler.addQuickElement("title", item['title']) handler.addQuickElement("link", item['link']) if item['description'] is not None: handler.addQuickElement("description", item['description']) # Author information. if item["author_name"] and item["author_email"]: handler.addQuickElement("author", "%s (%s)" % (item['author_email'], item['author_name'])) elif item["author_email"]: handler.addQuickElement("author", item["author_email"]) elif item["author_name"]: handler.addQuickElement("dc:creator", item["author_name"], {"xmlns:dc": "http://purl.org/dc/elements/1.1/"}) if item['pubdate'] is not None: handler.addQuickElement("pubDate", rfc2822_date(item['pubdate'])) if item['comments'] is not None: handler.addQuickElement("comments", item['comments']) if item['unique_id'] is not None: guid_attrs = {} if isinstance(item.get('unique_id_is_permalink'), bool): guid_attrs['isPermaLink'] = str( item['unique_id_is_permalink']).lower() handler.addQuickElement("guid", item['unique_id'], guid_attrs) if item['ttl'] is not None: handler.addQuickElement("ttl", item['ttl']) # Enclosure. if item['enclosure'] is not None: handler.addQuickElement("enclosure", '', {"url": item['enclosure'].url, "length": item['enclosure'].length, "type": item['enclosure'].mime_type}) # Categories. for cat in item['categories']: handler.addQuickElement("category", cat) class Atom1Feed(SyndicationFeed): # Spec: http://atompub.org/2005/07/11/draft-ietf-atompub-format-10.html content_type = 'application/atom+xml; charset=utf-8' ns = "http://www.w3.org/2005/Atom" def write(self, outfile, encoding): handler = SimplerXMLGenerator(outfile, encoding) handler.startDocument() handler.startElement('feed', self.root_attributes()) self.add_root_elements(handler) self.write_items(handler) handler.endElement("feed") def root_attributes(self): if self.feed['language'] is not None: return {"xmlns": self.ns, "xml:lang": self.feed['language']} else: return {"xmlns": self.ns} def add_root_elements(self, handler): handler.addQuickElement("title", self.feed['title']) handler.addQuickElement("link", "", {"rel": "alternate", "href": self.feed['link']}) if self.feed['feed_url'] is not None: handler.addQuickElement("link", "", {"rel": "self", "href": self.feed['feed_url']}) handler.addQuickElement("id", self.feed['id']) handler.addQuickElement("updated", rfc3339_date(self.latest_post_date())) if self.feed['author_name'] is not None: handler.startElement("author", {}) handler.addQuickElement("name", self.feed['author_name']) if self.feed['author_email'] is not None: handler.addQuickElement("email", self.feed['author_email']) if self.feed['author_link'] is not None: handler.addQuickElement("uri", self.feed['author_link']) handler.endElement("author") if self.feed['subtitle'] is not None: handler.addQuickElement("subtitle", self.feed['subtitle']) for cat in self.feed['categories']: handler.addQuickElement("category", "", {"term": cat}) if self.feed['feed_copyright'] is not None: handler.addQuickElement("rights", self.feed['feed_copyright']) def write_items(self, handler): for item in self.items: handler.startElement("entry", self.item_attributes(item)) self.add_item_elements(handler, item) handler.endElement("entry") def add_item_elements(self, handler, item): handler.addQuickElement("title", item['title']) handler.addQuickElement("link", "", {"href": item['link'], "rel": "alternate"}) if item['pubdate'] is not None: handler.addQuickElement('published', rfc3339_date(item['pubdate'])) if item['updateddate'] is not None: handler.addQuickElement('updated', rfc3339_date(item['updateddate'])) # Author information. if item['author_name'] is not None: handler.startElement("author", {}) handler.addQuickElement("name", item['author_name']) if item['author_email'] is not None: handler.addQuickElement("email", item['author_email']) if item['author_link'] is not None: handler.addQuickElement("uri", item['author_link']) handler.endElement("author") # Unique ID. if item['unique_id'] is not None: unique_id = item['unique_id'] else: unique_id = get_tag_uri(item['link'], item['pubdate']) handler.addQuickElement("id", unique_id) # Summary. if item['description'] is not None: handler.addQuickElement("summary", item['description'], {"type": "html"}) # Enclosure. if item['enclosure'] is not None: handler.addQuickElement("link", '', {"rel": "enclosure", "href": item['enclosure'].url, "length": item['enclosure'].length, "type": item['enclosure'].mime_type}) # Categories. for cat in item['categories']: handler.addQuickElement("category", "", {"term": cat}) # Rights. if item['item_copyright'] is not None: handler.addQuickElement("rights", item['item_copyright']) @property def mime_type(self): warnings.warn( 'The mime_type attribute of Atom1Feed is deprecated. ' 'Use content_type instead.', RemovedInDjango20Warning, stacklevel=2 ) return self.content_type # This isolates the decision of what the system default is, so calling code can # do "feedgenerator.DefaultFeed" instead of "feedgenerator.Rss201rev2Feed". DefaultFeed = Rss201rev2Feed
Cisco-Talos/pyrebox
refs/heads/master
mw_monitor2/ida_scripts/mw_monitor_binary_log_reader.py
2
# ------------------------------------------------------------------------- # # Copyright (C) 2018 Cisco Talos Security Intelligence and Research Group # # PyREBox: Python scriptable Reverse Engineering Sandbox # Author: Xabier Ugarte-Pedrero # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # 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. # # ------------------------------------------------------------------------- #!/usr/bin/python import pickle import sys def read_stream(f_in): data = pickle.load(f_in) if type(data) is list: for proc in data: print proc.__str__() else: for proc in data.procs: print proc.__str__() if __name__ == "__main__": if len(sys.argv) != 2: print "Usage: %s <file>" % (sys.argv[0]) with open(sys.argv[1], "rb") as f: read_stream(f)
reinout/django
refs/heads/master
django/conf/locale/id/formats.py
65
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j N Y' DATETIME_FORMAT = "j N Y, G.i" TIME_FORMAT = 'G.i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd-m-Y' SHORT_DATETIME_FORMAT = 'd-m-Y G.i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d-%m-%y', '%d/%m/%y', # '25-10-09', 25/10/09' '%d-%m-%Y', '%d/%m/%Y', # '25-10-2009', 25/10/2009' '%d %b %Y', # '25 Oct 2006', '%d %B %Y', # '25 October 2006' ] TIME_INPUT_FORMATS = [ '%H.%M.%S', # '14.30.59' '%H.%M', # '14.30' ] DATETIME_INPUT_FORMATS = [ '%d-%m-%Y %H.%M.%S', # '25-10-2009 14.30.59' '%d-%m-%Y %H.%M.%S.%f', # '25-10-2009 14.30.59.000200' '%d-%m-%Y %H.%M', # '25-10-2009 14.30' '%d-%m-%Y', # '25-10-2009' '%d-%m-%y %H.%M.%S', # '25-10-09' 14.30.59' '%d-%m-%y %H.%M.%S.%f', # '25-10-09' 14.30.59.000200' '%d-%m-%y %H.%M', # '25-10-09' 14.30' '%d-%m-%y', # '25-10-09'' '%m/%d/%y %H.%M.%S', # '10/25/06 14.30.59' '%m/%d/%y %H.%M.%S.%f', # '10/25/06 14.30.59.000200' '%m/%d/%y %H.%M', # '10/25/06 14.30' '%m/%d/%y', # '10/25/06' '%m/%d/%Y %H.%M.%S', # '25/10/2009 14.30.59' '%m/%d/%Y %H.%M.%S.%f', # '25/10/2009 14.30.59.000200' '%m/%d/%Y %H.%M', # '25/10/2009 14.30' '%m/%d/%Y', # '10/25/2009' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
fake-name/ReadableWebProxy
refs/heads/master
WebMirror/management/rss_parser_funcs/feed_parse_extract50Translations.py
1
def extract50Translations(item): """ Parser for '50% Translations' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'WATTT' in item['tags']: return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, postfix=postfix) return False
heke123/chromium-crosswalk
refs/heads/master
chrome/browser/resources/chromeos/chromevox/tools/publish_webstore_extension.py
15
#!/usr/bin/env python # 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. '''Publishes a set of extensions to the webstore. Given an unpacked extension, compresses and sends to the Chrome webstore. Releasing to the webstore should involve the following manual steps before running this script: 1. clean the output directory. 2. make a release build. 3. run manual smoke tests. 4. run automated tests. ''' import webstore_extension_util import generate_manifest import json import optparse import os import sys import tempfile from zipfile import ZipFile _CHROMEVOX_ID = 'kgejglhpjiefppelpmljglcjbhoiplfn' _SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) _CHROME_SOURCE_DIR = os.path.normpath( os.path.join( _SCRIPT_DIR, *[os.path.pardir] * 6)) sys.path.insert( 0, os.path.join(_CHROME_SOURCE_DIR, 'build', 'util')) import version # A list of files (or directories) to exclude from the webstore build. EXCLUDE_PATHS = [ 'manifest.json', 'manifest_guest.json', ] def CreateOptionParser(): parser = optparse.OptionParser(description=__doc__) parser.usage = ( '%prog --client_secret <client_secret> extension_id:extension_path ...') parser.add_option('-c', '--client_secret', dest='client_secret', action='store', metavar='CLIENT_SECRET') parser.add_option('-p', '--publish', action='store_true', help='publish the extension(s)') return parser def GetVersion(): '''Returns the chrome version string.''' filename = os.path.join(_CHROME_SOURCE_DIR, 'chrome', 'VERSION') values = version.fetch_values([filename]) return version.subst_template('@MAJOR@.@MINOR@.@BUILD@.@PATCH@', values) def MakeChromeVoxManifest(): '''Create a manifest for the webstore. Returns: Temporary file with generated manifest. ''' new_file = tempfile.NamedTemporaryFile(mode='w+a', bufsize=0) in_file_name = os.path.join(_SCRIPT_DIR, os.path.pardir, 'manifest.json.jinja2') context = { 'is_guest_manifest': '0', 'is_js_compressed': '1', 'set_version': GetVersion() } generate_manifest.processJinjaTemplate(in_file_name, new_file.name, context) return new_file def RunInteractivePrompt(client_secret, output_path): input = '' while True: print 'u upload' print 'g get upload status' print 't publish trusted tester' print 'p publish public' print 'q quit' input = raw_input('Please select an option: ') input = input.strip() if input == 'g': print ('Upload status: %s' % webstore_extension_util.GetUploadStatus(client_secret).read()) elif input == 'u': print ('Uploaded with status: %s' % webstore_extension_util.PostUpload(output_path.name, client_secret)) elif input == 't': print ('Published to trusted testers with status: %s' % webstore_extension_util.PostPublishTrustedTesters( client_secret).read()) elif input == 'p': print ('Published to public with status: %s' % webstore_extension_util.PostPublish(client_secret).read()) elif input == 'q': sys.exit() else: print 'Unrecognized option: %s' % input def main(): options, args = CreateOptionParser().parse_args() if len(args) < 1 or not options.client_secret: print 'Expected at least one argument and --client_secret flag' print str(args) sys.exit(1) client_secret = options.client_secret for extension in args: webstore_extension_util.g_app_id, extension_path = extension.split(':') output_path = tempfile.NamedTemporaryFile() extension_path = os.path.expanduser(extension_path) is_chromevox = webstore_extension_util.g_app_id == _CHROMEVOX_ID with ZipFile(output_path, 'w') as zip: for root, dirs, files in os.walk(extension_path): rel_path = os.path.join(os.path.relpath(root, extension_path), '') if is_chromevox and rel_path in EXCLUDE_PATHS: continue for extension_file in files: if is_chromevox and extension_file in EXCLUDE_PATHS: continue zip.write(os.path.join(root, extension_file), os.path.join(rel_path, extension_file)) if is_chromevox: manifest_file = MakeChromeVoxManifest() zip.write(manifest_file.name, 'manifest.json') print 'Created extension zip file in %s' % output_path.name print 'Please run manual smoke tests before proceeding.' if options.publish: print('Uploading...%s' % webstore_extension_util.PostUpload(output_path.name, client_secret)) print('publishing...%s' % webstore_extension_util.PostPublish(client_secret).read()) else: RunInteractivePrompt(client_secret, output_path) if __name__ == '__main__': main()
BFH-E2d/iotdemo
refs/heads/master
lorawan/migrations/0005_message.py
2
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-11 13:35 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('lorawan', '0004_device_status'), ] operations = [ migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('content', models.BinaryField()), ('datetime', models.DateTimeField()), ('port', models.PositiveIntegerField()), ('device', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='lorawan.Device')), ], ), ]
hendrikwout/pynacolada
refs/heads/master
trash/procnc.py
2
import os import pickle import pylab as pl from operator import itemgetter import netcdf import numpy as np import sys from operator import mul from ncdftools import nccopydimension from Scientific.IO import NetCDF from array import array import struct def nctypecode(dtype): # purose: netcdf-typecode from array-dtype if ((dtype == np.dtype('float32')) or (np.dtype == 'float32')): return 'f' elif ((dtype == np.dtype('float64')) or (np.dtype == 'float64')): return 'd' elif ((dtype == np.dtype('int32')) or (np.dtype == 'int32')): return 'i' elif ((dtype == np.dtype('int64')) or (np.dtype == 'int64')): return 'l' class SomeError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) def ncvartypeoffset(ncfile,var): """ purpose: get binary data type and offset of a variable in netcdf file unfortunately, getting these properties are not explicitely implemented in scipy, but most of this code is stolen from scipy: /usr/lib/python2.7/dist-packages/scipy/io/netcdf.py ncfile is a scipy.io.netcdf.netcdf_file var variable we want to calculate the offset from """ oripos=ncfile.fp.tell() ncfile.fp.seek(0) magic = ncfile.fp.read(3) ncfile.__dict__['version_byte'] = np.fromstring(ncfile.fp.read(1), '>b')[0] # Read file headers and set data. ncfile._read_numrecs() ncfile._read_dim_array() ncfile._read_gatt_array() header = ncfile.fp.read(4) count = ncfile._unpack_int() vars = [] for ic in range(count): vars.append(list(ncfile._read_var())) ivar = np.where(np.array(vars) == var)[0][0] ncfile.fp.seek(oripos) return vars[ivar][6] , vars[ivar][7] def rwicecube(filestream,shp,refiter,dimiter,dimpos,refnoiter,dimnoiter,icecube,vtype,vsize,voffset,rwchsize,mode): """ read or write data icecube from binary data and put it in an array filestream: binary file reference shp: shape of the filestream refiter: reference to dimensions over which no slice is performed pos: current index position of the non-sliced dimensions """ # e.g. shp = (200,100,50,50,20) # refiter = (1,3,4) # dimpos = (5,10,9) # extend so that structured arrays are read at once lennoiter = long(1) for irefnoiter,erefnoiter in enumerate(refnoiter): lennoiter = lennoiter*dimnoiter[irefnoiter] fpos = 0 # e.g. fpos = (9)+ 20*(10) + 50*50*20*(5) for idimpos,edimpos in enumerate(dimpos): curadd = np.mod(edimpos,dimiter[idimpos]) #e.g. if edimpos == (5): curadd = 50*50*20*(5) # exclude trivial special case of only 1 iteration step # --> in that case fpos is just zero. if refiter != [-1]: if ((refiter[idimpos] + 1) < len(shp)): for i in range(refiter[idimpos] + 1,len(shp)) : curadd = curadd * shp[i] fpos = fpos + curadd # Initialize (for reading) or prepare (for writing) icecube array if mode == 'read': icecube = np.zeros((lennoiter,),dtype=vtype)*np.nan elif mode == 'write': icecube = np.reshape(icecube,(lennoiter,)) dimnoiterpos = [0]*len(dimnoiter) # print icecube,dimnoiterpos j = 0 while j < lennoiter: fposicecube = fpos for idimpos,edimpos in enumerate(dimnoiterpos): curadd = np.mod(edimpos,dimnoiter[idimpos]) # e.g. fposicecube = (1)*52 # e.g. fposicecube = (9)+ 20*(10) + 50*50*20*(5) if ((refnoiter[idimpos] + 1) < len(shp)): for i in range(refnoiter[idimpos] + 1,len(shp)) : curadd = curadd * shp[i] fposicecube = fposicecube + curadd if mode == 'read': filestream.seek(voffset+vsize*fposicecube) temp = np.fromfile(filestream,dtype='='+vtype[1],count=rwchsize) temp.byteswap(True) icecube[j:(j+rwchsize)] = temp elif mode == 'write': filestream.seek(voffset+vsize*fposicecube) fpointout.seek(voffset+vsize*fposicecube) # filestream.seek(voffset+vsize*fposicecube) testdata[fposicecube:(fposicecube+rwchsize)] = np.array(icecube[j:(j+rwchsize)],dtype=vtype[1]) # little = struct.pack('>'+'d'*len(icecube[j:(j+rwchsize)]), *icecube[j:(j+rwchsize)]) # # Seek to offset based on piece index # #print little # filestream.write(little) # filestream.write(np.array(icecube[j:(j+rwchsize)],dtype=vtype)) # # np.array(icecube[j:(j+rwchsize)],dtype=vtype[1]).byteswap().tofile(filestream) temp = np.array(icecube[j:(j+rwchsize)],dtype='>d') filestream.write(temp) fpointout.write(temp) # # print temp # # filestream.write(temp[:]) # # little = struct.pack('<'+'B'*len(temp), *temp) # # print icecube.byteswap().dtype # # print voffset, vsize, fposicecube, vtype, rwchsize, icecube.dtype# ,icecube[j:(j+rwchsize)] # go to next data strip if dimnoiterpos != []: # rwchsize: allow reading of chunks for the inner dimensions dimnoiterpos[-1] = dimnoiterpos[-1] + rwchsize for idimidx,edimidx in enumerate(reversed(dimnoiterpos)): if idimidx > 0: while dimnoiterpos[idimidx] >= dimnoiter[idimidx]: dimnoiterpos[idimidx-1] = dimnoiterpos[idimidx-1] + 1 dimnoiterpos[idimidx] -= dimnoiter[idimidx] j = j+rwchsize icecube.shape = dimnoiter if mode == 'read': return icecube def writeicecubeps(fstream,shp,refiter,dimiter,dimiterpos,refnoiter,dimnoiter,data,vtype,vsize,voffset,rwchsize): """ write an icecube and perform an in-memory Post Swap of dimensions before (very fast) hereby, we acquire the order of the icecube dimensions """ refnoitersort,trns,dimnoitersort = zip(*sorted(zip(refnoiter,range(len(refnoiter)),dimnoiter),key=itemgetter(0,1))) rwicecube(fstream,shp,refiter,dimiter,dimiterpos,refnoitersort,dimnoitersort,np.transpose(data,trns),vtype,vsize,voffset,rwchsize,'write') def readicecubeps(fstream,shp,refiter,dimiter,dimiterpos,refnoiter,dimnoiter,vtype,vsize,voffset,rwchsize): """ read an icecube by sorting the indices (highest at the back). perform an in-memory Post Swap of dimensions (very fast) to compensate for the sorting. we allow reading in chunks according to the inner dimensions. They will be mostly there because we allow an max-icecubesize """ refnoitersort,trns,dimnoitersort = zip(*sorted(zip(refnoiter,range(len(refnoiter)),dimnoiter),key=itemgetter(0,1))) icecube =rwicecube(fstream,shp,refiter,dimiter,dimiterpos,refnoitersort,dimnoitersort,None,vtype,vsize,voffset,rwchsize,'read') # build the 'inverse permutation' operator for tranposition before writeout inv = range(len(trns)) for itrns, etrns in enumerate(trns): inv[etrns] = itrns return np.transpose(icecube,inv) fnin = '/home/hendrik/data/belgium_aq/rcm/aq09/stage1/int2lm/laf2009010100_urb_ahf.nc' print fnin # fobjin = open(fnin,'rb') fin = NetCDF.NetCDFFile(fnin,'r') fnout = '/home/hendrik/data/belgium_aq/rcm/aq09/stage1/int2lm/laf2009010100_urb_ahf2.nc' os.system('rm '+fnout) print fnout # fobjout = open(fnout,'wb+') fout = NetCDF.NetCDFFile(fnout,'w') fnpointout = '/home/hendrik/data/belgium_aq/rcm/aq09/stage1/int2lm/laf2009010100_urb_ahf4.nc' os.system('rm '+fnpointout) print fnpointout # fobjout = open(fnpointout,'wb+') fpointout = open(fnpointout,'w') # we kunnen eens proberen om een variabele aan te maken met een vooraf gespecifieerde dimensie! datin = [[fin,'QV'],[fin,'rlat']] datout = [[fout,'QV'],[fout,'TEST']] # adtypeoutspec = [None,None] # to be obtained automatically from the data output stream (if it already exists) # selection of function dimension input func = lambda x, y: (np.array([[[np.mean(x)]],[[np.mean(x)]]],dtype=np.float) , np.array([[[np.mean(x)]],[[np.mean(x)]]],dtype=np.float)) # *(1.+np.zeros(x.shape)) dnamsel = ('rlon','time','t') # obtain definitions of the variable stream input vsdin = [] # input variable stream definitions for idatin,edatin in enumerate(datin): # read in scipy.netcdf mode to obtain varariable offsets # obtain file name from open netcdf!! very nasty!!! ncfn = str(datin[idatin][0])[19:(str(datin[idatin][0]).index("'",19))] nctemp = netcdf.netcdf_file(ncfn,'r') # nctemp = datin[idatin][0] vsdin.append(dict()) vsdin[idatin]['dnams'] = [] for idim,edim in enumerate(nctemp.variables[datin[idatin][1]].dimensions): vsdin[idatin]['dnams'].append(str(edim)) vsdin[idatin]['dims'] = list(nctemp.variables[datin[idatin][1]].shape) vsdin[idatin]['itemsize'] = nctemp.variables[datin[idatin][1]].itemsize() vsdin[idatin]['dtype'] = nctemp.variables[datin[idatin][1]]._dtype vsdin[idatin]['voffset'] = nctemp.variables[datin[idatin][1]]._voffset nctemp.close() # obtain definitions of the variable stream output vsdout = [] # input variable stream definitions for idatout,edatout in enumerate(datout): vsdout.append(dict()) if edatout[1] in edatout[0].variables: vsdout[idatout]['dnams'] = [] for idim,edim in enumerate(datout[idatout][0].variables[datout[idatout][1]].dimensions): vsdout[idatout]['dnams'].append(str(edim)) vsdout[idatout]['dims'] = list(datout[idatout][0].variables[datout[idatout][1]].shape) vsdout[idatout]['itemsize'] = datout[idatout][0].variables[datout[idatout][1]].itemsize() vsdout[idatout]['dtype']= datout[idatout][0].variables[datout[idatout][1]]._dtype vsdout[idatout]['voffset'] = datout[idatout][0].variables[datout[idatout][1]]._voffset else: # the variable doesn't exists (we will create it afterwards) vsdout[idatout]['dnams'] = None vsdout[idatout]['dims'] = None vsdout[idatout]['itemsize'] = None vsdout[idatout]['dtype'] = None # collecting the involved dimensions (will be considered as the standard output dimensions) dnamsstd = [] # standard output dimensions: list of all output dimensions: this is collected from the input dimensions, the output dimensions and the selected/processed dimensions dimsstd = [] # maximum length of an output dimension idimsstd = 0 for ivsdin,evsdin in enumerate(vsdin): dnaminlast = None index = 0 for idnam,ednam in reversed(list(enumerate(evsdin['dnams']))): if ednam not in dnamsstd: # In dnamsstd, ednam should be just after the dimensions preceding ednams in dnams # # actually, we also want that, in dnamsstd, ednam should be just before the dimensions succeeding ednams in dnams. Sometimes, this is not possible at the same time. But it will be the case if that is possible when applying one of the criteria index = 0 # print 'dnamsstd: ', evsdin,dnamsstd for idnam2,ednam2 in enumerate(dnamsstd): # print ednam,ednam2,idnam2,evsdin['dnams'][0:idnam2+1] if ednam2 in evsdin['dnams'][0:(idnam+1)]: # print index index = max(index,dnamsstd.index(ednam2) + 1) dnamsstd.insert(index,ednam) if ednam not in dnamsel: dimsstd.insert(index,int(vsdin[ivsdin]['dims'][idnam])) else: # In this case, wait for assigning the output dimensions. This actually depends on the specified function dimsstd.insert(index,None) else: if ((vsdin[ivsdin]['dims'][idnam] != 1) & (dimsstd[dnamsstd.index(ednam)] != 1) & \ # we allow non-equal dimension lengths, as long as the dimension is covered/captured by the function # maybe still allow non-equal dimension length not covered by the function???? (dimsstd[dnamsstd.index(ednam)] != None) & \ (vsdin[ivsdin]['dims'][idnam] != dimsstd[dnamsstd.index(ednam)])): raise SomeError("The corresponding output dnamensions (index: "+str(dnamsstd.index(ednam))+") of the input variable "+str(ivsdin)+ " "+ str(idnam)+ " "+" have a different length and not equal to 1.") else: # None means it's considered by the function if (dimsstd[dnamsstd.index(ednam)] != None): dimsstd[dnamsstd.index(ednam)] = max(dimsstd[dnamsstd.index(ednam)],vsdin[ivsdin]['dims'][idnam]) print 'Preliminary output dimensions: ', zip(dnamsstd,dimsstd) idnam = 0 # add the missing dimensions selected for the function for idnamsel,ednamsel in enumerate(dnamsel): if ednamsel not in dnamsstd: dnamsstd.insert(idnam,ednamsel) dimsstd.insert(idnam,None) # to be defined from the function idnam = idnam+1 # moet dit ook hier niet boven geimplementeerd worden? else: idnam = dnamsstd.index(ednam)+1 # adimsstd: list the specific output dimensions # if function dimension: data output dimension should be the same as the function output dimension, but this should be checked afterwards. # if not function dimension: # # look what's the output dimension like. If the dimension is not in the output variable, we add a dummy 1-dimension # we need to create/list adimsstd also before!! And then append them with the missing dimensions, as dummy 1-dimensions. If that is not sufficient, we will just get an error message. # get references to the standard output dimensions on which the function is applied refdfuncstd = [] for idnamsel,ednamsel in enumerate(dnamsel): refdfuncstd.append(dnamsstd.index(ednamsel)) # all output dimensions are now collected... # add the standard output dimensions that are missing in each seperate input variable as a dummy 1-dimension for ivsdin,evsdin in enumerate(vsdin): idnam = 0 for idnamsstd,ednamsstd in enumerate(dnamsstd): if ednamsstd not in vsdin[ivsdin]['dnams']: vsdin[ivsdin]['dnams'].insert(idnam,ednamsstd) vsdin[ivsdin]['dims'].insert(idnam,1) idnam = idnam + 1 else: idnam = vsdin[ivsdin]['dnams'].index(ednamsstd) + 1 # do the same for the data output variables # # vsdin[ivsdin]['refdstd']: references of data stream dimensions (vsdin[..]['dnams'] to the standard dimensions (dnamsstd) for ivsdin,evsdin in enumerate(vsdin): vsdin[ivsdin]['refdstd']= list([]) for idim,edim in enumerate(vsdin[ivsdin]['dnams']): vsdin[ivsdin]['refdstd'].append(dnamsstd.index(edim)) for ivsdout,evsdout in enumerate(vsdout): if vsdout[ivsdout]['dnams'] == None: vsdout[ivsdout]['dnams'] = dnamsstd # adimfuncin: the input dimensions of the function based on the refdfuncstd # adimfuncin: the dimensions of the function input adimfuncin = np.zeros((len(vsdin),len(refdfuncstd)),dtype='int32') - 1 alenfuncin = [] for ivsdout in range(len(vsdout)): if vsdout[ivsdout]['dnams'] == None: vsdout[ivsdout]['dnams'] == dnamsstd # vsdout[..]['refdstd']: references of data stream dimensions (vsdout[..]['dnams'] to the standard dimensions (dnamsstd) for ivsdout,evsdout in enumerate(vsdout): vsdout[ivsdout]['refdstd'] = list([]) for idim,edim in enumerate(vsdout[ivsdout]['dnams']): vsdout[ivsdout]['refdstd'].append(dnamsstd.index(edim)) # arefdfuncout: references of the function dimensions to the data output stream dimensions arefdfuncout = [] for ivsdout,evsdout in enumerate(vsdout): arefdfuncout.append([]) for idnamsel,ednamsel in enumerate(dnamsel): arefdfuncout[ivsdout].append(vsdout[ivsdout]['dnams'].index(ednamsel)) # is arefdfuncout[ivsdout][irefdfuncout] == vsdout[ivsdout]['refdstd'].index(erefdfuncstd) ??? # arefdfuncin: references of the function dimensions to the data input stream dimensions arefdfuncin = [] for ivsdin,evsdin in enumerate(vsdin): arefdfuncin.append([]) for idnamsel,ednamsel in enumerate(dnamsel): arefdfuncin[ivsdin].append(vsdin[ivsdin]['dnams'].index(ednamsel)) # to do next:::... for ivsdin,evsdin in enumerate(vsdin): for irefdfuncstd,erefdfuncstd in enumerate(refdfuncstd): adimfuncin[ivsdin,irefdfuncstd] = evsdin['dims'][vsdin[ivsdin]['refdstd'].index(erefdfuncstd)] alenfuncin.append(reduce(mul,adimfuncin[ivsdin])) # 'probe' function output dimensions dummydat = [] for ivsdin,evsdin in enumerate(vsdin): dummydat.append(np.zeros(adimfuncin[ivsdin])) ddout = func(*dummydat) if (type(ddout).__name__ == 'tuple'): ddout = list(ddout) if (type(ddout).__name__ != 'list'): ddout = list([ddout]) # obtain output data type. If not specified, we obtain it from the function output. # meanwhile, check whether the number of input dimensions are the same as the number of output dimensions. if len(ddout) != len(vsdout): raise SomeError('the amount of output variables in from '+ str(func) + ' ('+str(len(ddout))+') is not the same as specified ('+str(len(vsdout))+')') for iddout in range(len(ddout)): if type(ddout[iddout] ) != np.ndarray: ddout[iddout] = np.array(ddout[iddout]) if (len(np.array(ddout[iddout]).shape) != len(adimfuncin[iddout])): raise SomeError('The amount of input ('+str(len(adimfuncin[iddout]))+') and output dimensions ('+str(len(ddout[iddout].shape))+') of function is not the same') if vsdout[iddout]['dims'] == None: vsdout[iddout]['dims'] = dimsstd # overwrite dimensions with the function output dimensions for irefdfuncout,erefdfuncout in enumerate(arefdfuncout[iddout]): vsdout[iddout]['dims'][erefdfuncout] = ddout[iddout].shape[irefdfuncout] if vsdout[iddout]['dtype'] == None: # output netcdf variable does not exist... creating # why does this needs to be little endian???? vsdout[iddout]['dtype'] = '>'+nctypecode(ddout[iddout].dtype) # try to copy dimension from data input for idim,edim in enumerate(vsdout[iddout]['dnams']): if edim not in datout[iddout][0].dimensions: dimensionfound = False idatin = 0 # try to copy the dimension from the input data while ((not dimensionfound) & (idatin < (len(datin) ))): if edim in datin[idatin][0].dimensions: if (vsdout[iddout]['dims'][idim] == datin[idatin][0].dimensions[edim]): print datin[idatin][0],datout[iddout][0], edim nccopydimension(datin[idatin][0],datout[iddout][0], edim) dimensionfound = True idatin = idatin + 1 if dimensionfound == False: datout[iddout][0].createDimension(edim,vsdout[iddout]['dims'][idim]) datout[iddout][0].createVariable(datout[iddout][1],vsdout[iddout]['dtype'][1],tuple(vsdout[iddout]['dnams'])) # we should check this at the time the dimensions are not created if (vsdout[iddout]['dims'] != list(datout[iddout][0].variables[datout[iddout][1]].shape)): raise SomeError("dimensions of output file ( "+str(vsdout[iddout]['dims'])+"; "+ str(vsdout[iddout]['dnams'])+") do not correspond with intended output dimension "+str(datout[iddout][0].variables[datout[iddout][1]].shape)+"; "+str(datout[iddout][0].variables[datout[iddout][1]].dimensions)) for idatin,edatin in enumerate(datin): # obtain file pointer!! very nasty!! ncfn = str(datin[idatin][0])[19:(str(datin[idatin][0]).index("'",19))] vsdin[idatin]['fp'] = open(ncfn,'r') for idatout,edatout in enumerate(datout): # obtain file pointer!! very nasty!! datout[idatout][0].flush() ncfn = str(datout[idatout][0])[19:(str(datout[idatout][0]).index("'",19))] vsdout[idatout]['fp'] = open(ncfn,'r+') # in order to discover variable offsets nctemp = netcdf.netcdf_file(ncfn,'r') vsdout[idatout]['itemsize'] = nctemp.variables[datout[idatout][1]].itemsize() vsdout[idatout]['voffset'] = nctemp.variables[datout[idatout][1]]._voffset nctemp.close() # # next: check whether the output variable dimensions (if already present) are not too large, otherwise raise error. + Construct final output dimension specs # to do next:::... # adimfuncout: the dimensions of the function output adimfuncout = np.zeros((len(vsdout),len(refdfuncstd)),dtype='int32') - 1 alenfuncout = [] for ivsdout,evsdout in enumerate(vsdout): for irefdfuncstd,erefdfuncstd in enumerate(refdfuncstd): adimfuncout[ivsdout,irefdfuncstd] = evsdout['dims'][vsdout[ivsdout]['refdstd'].index(erefdfuncstd)] # # or ... # for irefdfuncout,erefdfuncout in enumerate(arefdfuncout[ivsdout]): # adimfuncout[ivsdout,irefdfuncstd] = evsdout['dims'][erefdfuncout] alenfuncout.append(reduce(mul,adimfuncout[ivsdout])) # ???arefdfuncout[ivsdout][irefdfuncout] == vsdout[ivsdout]['refdstd'].index(erefdfuncstd) # make copies of adimfunc*, alenfunc*, arefdfunc* # lennoiterstd = list(lenfuncstd) # dimnoiterstd = list(dimdfuncstd) refdnoiterstd = list(refdfuncstd) alendnoiterin = list(alenfuncin) adimnoiterin = [] arefdnoiterin = [] for ivsdin,evsdin in enumerate(vsdin): adimnoiterin.append(list(adimfuncin[ivsdin])) arefdnoiterin.append(list(arefdfuncin[ivsdin])) alendnoiterout = list(alenfuncout) adimnoiterout = [] arefdnoiterout = [] for ivsdout,evsdout in enumerate(vsdout): adimnoiterout.append(list(adimfuncout[ivsdout])) arefdnoiterout.append(list(arefdfuncout[ivsdout])) # arefsin: references of the standard dimensions to the data stream dimensions arefsin = [] for ivsdin,evsdin in enumerate(vsdin): arefsin.append([None]*len(vsdin[ivsdin]['refdstd'])) # loop over the data stream dimensions for irefdstd,erefdstd in enumerate(vsdin[ivsdin]['refdstd']): arefsin[ivsdin][erefdstd] = irefdstd # arefsout: references of the standard dimensions to the data stream dimensions arefsout = [] for ivsdout,evsdout in enumerate(vsdout): arefsout.append([None]*len(vsdout[ivsdout]['refdstd'])) # loop over the data stream dimensions for irefdstd,erefdstd in enumerate(vsdout[ivsdout]['refdstd']): arefsout[ivsdout][erefdstd] = irefdstd dnamselnoiter = list(dnamsel) # membytes: minimum total memory that will be used. We will the increase usage when possible/allowed. membytes = 0 for ivsdin,evsdin in enumerate(vsdin): membytes = membytes + alenfuncin[ivsdin] * vsdin[ivsdin]['itemsize'] for ivsdout,evsdout in enumerate(vsdout): membytes = membytes + alenfuncout[ivsdout] * vsdout[ivsdout]['itemsize'] maxmembytes = 1000000 if membytes > maxmembytes: print 'Warning, used memory ('+str(membytes)+') exceeds maximum memory ('+str(maxmembytes)+').' else: # a temporary copy of alennoiter* alendnoiterin_tmp = list(alendnoiterin) alendnoiterout_tmp = list(alendnoiterout) # we try will to read the data in even larger icecubes to reduce disk access! idnam = len(dnamsstd) - 1 cont = True while ((idnam >= 0) & (membytes <= maxmembytes) & cont): # while loop quite extensive but does what is should-> should be reduced and simplified cont = False # only continue to the next loop if idnam+1 (in previous loop) was (inserted) in refdnoiterstd if idnam not in refdnoiterstd: for ivsdin,evsdin in enumerate(vsdin): alendnoiterin_tmp[ivsdin] = alendnoiterin_tmp[ivsdin] *vsdin[ivsdin]['dims'][arefsin[ivsdin][idnam]] for ivsdout,evsdout in enumerate(vsdout): alendnoiterout_tmp[ivsdout] = alendnoiterout_tmp[ivsdout] *vsdout[ivsdout]['dims'][arefsout[ivsdout][idnam]] # recalculate the amount of bytes tmpmembytes = 0 for ivsdin,evsdin in enumerate(vsdin): tmpmembytes = tmpmembytes + alendnoiterin_tmp[ivsdin] * vsdin[ivsdin]['itemsize'] for ivsdout,evsdout in enumerate(vsdout): tmpmembytes = tmpmembytes + alendnoiterout_tmp[ivsdout] * vsdout[ivsdout]['itemsize'] print 'tmpmembytes', tmpmembytes, membytes # if used memory still below threshold, we add it to the current dimension to the icecubes if tmpmembytes <= maxmembytes: refdnoiterstd.insert(0,idnam) for ivsdin,evsdin in enumerate(vsdin): arefdnoiterin[ivsdin].insert(0, arefsin[ivsdin][idnam]) adimnoiterin[ivsdin].insert(0,vsdin[ivsdin]['dims'][arefsin[ivsdin][idnam]]) alendnoiterin[ivsdin] = alendnoiterin[ivsdin] *vsdin[ivsdin]['dims'][arefsin[ivsdin][idnam]] for ivsdout,evsdout in enumerate(vsdout): arefdnoiterout[ivsdout].insert(0, arefsout[ivsdout][idnam]) adimnoiterout[ivsdout].insert(0,vsdout[ivsdout]['dims'][arefsout[ivsdout][idnam]]) alendnoiterout[ivsdout] = alendnoiterout[ivsdout] *vsdout[ivsdout]['dims'][arefsout[ivsdout][idnam]] dnamselnoiter.insert(0,dnamsstd[idnam]) # recalculate the amount of bytes membytes = 0 for ivsdin,evsdin in enumerate(vsdin): membytes = membytes + alendnoiterin[ivsdin] * vsdin[ivsdin]['itemsize'] for ivsdout,evsdout in enumerate(vsdout): membytes = membytes + alendnoiterout[ivsdout] * vsdout[ivsdout]['itemsize'] print 'membytes',membytes cont = True # if used memory still below threshold, we add it to the current dimension to the icecubes else: cont = True idnam = idnam - 1 # adimnoiterin[ivsdin,irefdnoiterstd] = evsdin['dims'][vsdin[ivsdin]['refdstd'].index(erefdnoiterstd)] # arefdfuncin: references of the function dimensions to the data input stream dimensions # arefdnoiterin: references of the icecube dimensions to the data input stream dimensions # # vsdin[ivsdin]['refdstd']: references of data stream dimensions (vsdin[..]['dnams'] to the standard dimensions (dnamsstd) # dnamselnoiter: references # guess from residual dimensions that are not in refnoiterin refditerstd = [] dimiterstd = [] for idim,edim in enumerate(dimsstd): if idim not in refdnoiterstd: refditerstd.append(idim) dimiterstd.append(edim) # guess from residual dimensions that are not in refnoiterin arefditerin = [] adimiterin = [] for ivsdin,evsdin in enumerate(vsdin): arefditerin.append([]) adimiterin.append([]) for idim,edim in enumerate(vsdin[ivsdin]['dims']): if idim not in arefdnoiterin[ivsdin]: arefditerin[ivsdin].append(idim) adimiterin[ivsdin].append(edim) # guess from residual dimensions that are not in refnoiterin arefditerout = [] adimiterout = [] for ivsdout,evsdout in enumerate(vsdout): arefditerout.append([]) adimiterout.append([]) for idim,edim in enumerate(vsdout[ivsdout]['dims']): if idim not in arefdnoiterout[ivsdout]: arefditerout[ivsdout].append(idim) adimiterout[ivsdout].append(edim) dimitermax = [] for iref,eref in enumerate(refditerstd): dimitermax.append(1) for ivsdin,evsdin in enumerate(vsdin): dimitermax[iref] = max(dimitermax[iref],adimiterin[ivsdin][iref]) print dimitermax[iref], adimiterin[ivsdin][iref] for ivsdout,evsdout in enumerate(vsdout): dimitermax[iref] = max(dimitermax[iref],adimiterout[ivsdout][iref]) rwchunksizein = [1]*len(vsdin) for ivsdin,evsdin in enumerate(vsdin): idim = len(vsdin[ivsdin]['dims']) -1 while ((idim in arefdnoiterin[ivsdin]) & (idim >= 0)): # The inner dimensions just have to be referenced so not in correct order. We know that they will be read in the correct order in the end rwchunksizein[ivsdin] = rwchunksizein[ivsdin]*vsdin[ivsdin]['dims'][idim] idim = idim - 1 rwchunksizeout = [1]*len(vsdout) for ivsdout,evsdout in enumerate(vsdout): idim = len(vsdout[ivsdout]['dims']) -1 while ((idim in arefdnoiterout[ivsdout]) & (idim >= 0)): # The inner dimensions just have to be referenced so not in correct order. We know that they will be read in the correct order in the end rwchunksizeout[ivsdout] = rwchunksizeout[ivsdout]*vsdout[ivsdout]['dims'][idim] idim = idim - 1 adimnoapplyout = [] alennoapplyout = [] for ivsdout,evsdout in enumerate(vsdout): adimnoapplyout.append([]) alennoapplyout.append(1) for irefdnoiterout in range(len(arefdnoiterout[ivsdout])-len(arefdfuncout[ivsdout])): adimnoapplyout[ivsdout].append(adimnoiterout[ivsdout][irefdnoiterout]) alennoapplyout[ivsdout] =alennoapplyout[ivsdout]*adimnoapplyout[ivsdout][-1] if adimnoapplyout[ivsdout] == []: adimnoapplyout[ivsdout] = [1] adimnoapplyin = [] alennoapplyin = [] for ivsdin,evsdin in enumerate(vsdin): adimnoapplyin.append([]) alennoapplyin.append(1) for irefdnoiterin in range(len(arefdnoiterin[ivsdin])-len(arefdfuncin[ivsdin])): adimnoapplyin[ivsdin].append(adimnoiterin[ivsdin][irefdnoiterin]) alennoapplyin[ivsdin] =alennoapplyin[ivsdin]*adimnoapplyin[ivsdin][-1] if adimnoapplyin[ivsdin] == []: adimnoapplyin[ivsdin] = [1] dimnoapplymax = [] for iref in range(len(arefdnoiterout[ivsdout])-len(arefdfuncout[ivsdout])): dimnoapplymax.append(1) for ivsdin,evsdin in enumerate(vsdin): dimnoapplymax[iref] = max(dimnoapplymax[iref],adimnoapplyin[ivsdin][iref]) print dimnoapplymax[iref], adimnoapplyin[ivsdin][iref] for ivsdout,evsdout in enumerate(vsdout): dimnoapplymax[iref] = max(dimnoapplymax[iref],adimnoapplyout[ivsdout][iref]) lennoapplymax = reduce(mul,dimnoapplymax) testdata = np.zeros(vsdout[0]['dims']).ravel() lenitermax = reduce(mul,dimitermax) dimiterpos = [0]*len(dimitermax) print str(0)+'/'+str(lenitermax), for j in range(lenitermax): # reading icecube, rearranged in the order of dimensions specified by arefnoiterin dataicecubein = [] for ivsdin,evsdin in enumerate(vsdin): # dataicecubein.append(np.zeros((elendnoiterin,),dtype=vsdin[ilendnoiterin]['dtype'])) dataicecubein.append(np.array(readicecubeps(\ vsdin[ivsdin]['fp'],\ vsdin[ivsdin]['dims'],\ arefditerin[ivsdin],\ adimiterin[ivsdin],\ dimiterpos,\ arefdnoiterin[ivsdin],\ adimnoiterin[ivsdin],\ vsdin[ivsdin]['dtype'],\ vsdin[ivsdin]['itemsize'],\ vsdin[ivsdin]['voffset'],\ rwchunksizein[ivsdin],\ ), dtype=vsdin[ivsdin]['dtype']).ravel()) dataicecubeout = [] for ilendnoiterout,elendnoiterout in enumerate(alendnoiterout): dataicecubeout.append(np.zeros((elendnoiterout,),dtype=vsdout[ilendnoiterout]['dtype'][1])) dimnoapplypos = [0]*len(dimnoapplymax) for k in range(lennoapplymax): # actually, this is just the end of the file output already written ahunkin = [] for ivsdin, evsdin in enumerate(vsdin): pos = 0 # e.g. pos = (9)+ 20*(10) + 50*50*20*(5) for idimpos,edimpos in enumerate(dimnoapplypos): curadd = np.mod(edimpos,adimnoapplyin[ivsdin][idimpos]) #e.g. if edimpos == (5): curadd = 50*50*20*(5) if ((idimpos + 1) < len(arefdnoiterin[ivsdin])): for i in range(idimpos + 1,len(arefdnoiterin[ivsdin])) : # here, we assume that the dimensions of the chunk are already in the order considered by adimsnoiter(out) etc. (cfr. preceeded transposition in readicecubeps) curadd = curadd * adimnoiterin[ivsdin][i] # curaddout = curaddout * dimnoiteroutref[i] pos = pos + curadd ahunkin.append(dataicecubein[ivsdin][pos:(pos+alenfuncin[ivsdin])]) ahunkin[ivsdin].shape = adimfuncin[ivsdin] # apply the function ahunkout = func(*ahunkin) if (type(ahunkout).__name__ == 'tuple'): ahunkout = list(ahunkout) if (type(ahunkout).__name__ != 'list'): ahunkout = list([ahunkout]) for ihunkout in range(len(ahunkout)): ahunkout[ihunkout] = np.array(ahunkout[ihunkout]) # e.g. posout = (9)+ 20*(10) + 50*50*20*(5) posout = 0 for idimpos,edimpos in enumerate(dimnoapplypos): curadd = np.mod(edimpos,adimnoapplyout[ihunkout][idimpos]) #e.g. if edimpos == (5): curadd = 50*50*20*(5) if ((idimpos + 1) < len(arefdnoiterout[ihunkout])): for i in range(idimpos + 1,len(arefdnoiterout[ihunkout])) : # here, we assume that the idims are in the intended order (cfr. subsequent transposition in writeicecubeps) curadd = curadd * adimnoiterout[ihunkout][i] # curaddout = curaddout * dimnoiteroutref[i] posout = posout + curadd dataicecubeout[ihunkout][posout:(posout+alenfuncout[ihunkout])] = np.array(ahunkout[ihunkout].ravel(),dtype=vsdout[ihunkout]['dtype'][1]) # go to next data slice dimnoapplypos[-1] = dimnoapplypos[-1] + 1 for idimidx,edimidx in enumerate(reversed(dimnoapplypos)): # # alternative (makes 'dimiter' redundant) # if dimiterpos[idimidx] == shp[refiter[idimidx]]: if idimidx > 0: if dimnoapplypos[idimidx] == dimnoapply[idimidx]: dimnoapplypos[idimidx-1] = dimnoapplypos[idimidx-1] + 1 dimnoapplypos[idimidx] = 0 for idimsout in range(len(dataicecubeout)): dataicecubeout[idimsout].shape = adimnoiterout[idimsout] #print dataicecubeout[idimsout].shape for ivsdout in range(len(vsdout)): # print dataicecubeout[ivsdout].shape,vsdout[ivsdout] # print 'ivsdout', ivsdout writeicecubeps(\ vsdout[ivsdout]['fp'], vsdout[ivsdout]['dims'],\ arefditerout[ivsdout],\ adimiterout[ivsdout],\ dimiterpos,\ arefdnoiterout[ivsdout],\ adimnoiterout[ivsdout],\ dataicecubeout[ivsdout],\ vsdout[ivsdout]['dtype'],\ vsdout[ivsdout]['itemsize'],\ vsdout[ivsdout]['voffset'],\ rwchunksizeout[ivsdout]) # go to next data slice dimiterpos[-1] = dimiterpos[-1] + 1 for idimidx,edimidx in enumerate(reversed(dimiterpos)): # # alternative (makes 'dimiter' redundant) # if dimiterpos[idimidx] == shp[refiter[idimidx]]: if dimiterpos[idimidx] == dimitermax[idimidx]: if idimidx > 0: dimiterpos[idimidx-1] = dimiterpos[idimidx-1] + 1 dimiterpos[idimidx] = 0 sys.stdout.write ('\b'*(len(str(j)+'/'+str(lenitermax))+1)) sys.stdout.write (str(j+1)+'/'+str(lenitermax)) for ivsdin,evsdin in enumerate(vsdin): vsdin[ivsdin]['fp'].close() for ivsdout,evsdout in enumerate(vsdout): vsdout[ivsdout]['fp'].close() import pylab as pl fout.close() # fin.close() # fout = NetCDF.NetCDFFile(fnout,'r') fout = netcdf.netcdf_file(fnout,'r') fout.fp.seek(vsdout[0]['voffset']) # fpointout.seek(vsdout[0]['voffset']) test = np.fromfile(fout.fp,dtype=vsdout[0]['dtype'],count=reduce(mul,vsdout[0]['dims'])) test.shape = (40,340) fig = pl.figure() pl.imshow(test) fig.show() fig = pl.figure() testdata.shape = vsdout[0]['dims'] pl.imshow(testdata[0,:,:,0,1]) fig.show() fout.close() fout = NetCDF.NetCDFFile(fnout,'r') fig = pl.figure() pl.imshow(fout.variables['QV'][0,:,:,0,0]) fig.show() fout.close()
nthien/zulip
refs/heads/master
zilencer/models.py
126
from django.db import models import zerver.models def get_deployment_by_domain(domain): return Deployment.objects.get(realms__domain=domain) class Deployment(models.Model): realms = models.ManyToManyField(zerver.models.Realm, related_name="_deployments") is_active = models.BooleanField(default=True) # TODO: This should really become the public portion of a keypair, and # it should be settable only with an initial bearer "activation key" api_key = models.CharField(max_length=32, null=True) base_api_url = models.CharField(max_length=128) base_site_url = models.CharField(max_length=128) @property def endpoints(self): return {'base_api_url': self.base_api_url, 'base_site_url': self.base_site_url} @property def name(self): # TODO: This only does the right thing for prod because prod authenticates to # staging with the zulip.com deployment key, while staging is technically the # deployment for the zulip.com realm. # This also doesn't necessarily handle other multi-realm deployments correctly. return self.realms.order_by('pk')[0].domain
HumboldtCoin/humboldtcoin
refs/heads/master
share/qt/make_spinner.py
4415
#!/usr/bin/env python # W.J. van der Laan, 2011 # Make spinning .mng animation from a .png # Requires imagemagick 6.7+ from __future__ import division from os import path from PIL import Image from subprocess import Popen SRC='img/reload_scaled.png' DST='../../src/qt/res/movies/update_spinner.mng' TMPDIR='/tmp' TMPNAME='tmp-%03i.png' NUMFRAMES=35 FRAMERATE=10.0 CONVERT='convert' CLOCKWISE=True DSIZE=(16,16) im_src = Image.open(SRC) if CLOCKWISE: im_src = im_src.transpose(Image.FLIP_LEFT_RIGHT) def frame_to_filename(frame): return path.join(TMPDIR, TMPNAME % frame) frame_files = [] for frame in xrange(NUMFRAMES): rotation = (frame + 0.5) / NUMFRAMES * 360.0 if CLOCKWISE: rotation = -rotation im_new = im_src.rotate(rotation, Image.BICUBIC) im_new.thumbnail(DSIZE, Image.ANTIALIAS) outfile = frame_to_filename(frame) im_new.save(outfile, 'png') frame_files.append(outfile) p = Popen([CONVERT, "-delay", str(FRAMERATE), "-dispose", "2"] + frame_files + [DST]) p.communicate()
spring-week-topos/horizon-week
refs/heads/spring-week
openstack_dashboard/dashboards/admin/models.py
172
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, 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. """ Stub file to work around django bug: https://code.djangoproject.com/ticket/7198 """
encbladexp/ansible
refs/heads/devel
lib/ansible/plugins/lookup/password.py
11
# (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com> # (c) 2013, Javier Candeira <javier@candeira.com> # (c) 2013, Maykel Moya <mmoya@speedyrails.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 DOCUMENTATION = """ name: password version_added: "1.1" author: - Daniel Hokka Zakrisson (!UNKNOWN) <daniel@hozac.com> - Javier Candeira (!UNKNOWN) <javier@candeira.com> - Maykel Moya (!UNKNOWN) <mmoya@speedyrails.com> short_description: retrieve or generate a random password, stored in a file description: - Generates a random plaintext password and stores it in a file at a given filepath. - If the file exists previously, it will retrieve its contents, behaving just like with_file. - 'Usage of variables like C("{{ inventory_hostname }}") in the filepath can be used to set up random passwords per host, which simplifies password management in C("host_vars") variables.' - A special case is using /dev/null as a path. The password lookup will generate a new random password each time, but will not write it to /dev/null. This can be used when you need a password without storing it on the controller. options: _terms: description: - path to the file that stores/will store the passwords required: True encrypt: description: - Which hash scheme to encrypt the returning password, should be one hash scheme from C(passlib.hash; md5_crypt, bcrypt, sha256_crypt, sha512_crypt). - If not provided, the password will be returned in plain text. - Note that the password is always stored as plain text, only the returning password is encrypted. - Encrypt also forces saving the salt value for idempotence. - Note that before 2.6 this option was incorrectly labeled as a boolean for a long time. ident: description: - Specify version of Bcrypt algorithm to be used while using C(encrypt) as C(bcrypt). - The parameter is only available for C(bcrypt) - U(https://passlib.readthedocs.io/en/stable/lib/passlib.hash.bcrypt.html#passlib.hash.bcrypt). - Other hash types will simply ignore this parameter. - 'Valid values for this parameter are: C(2), C(2a), C(2y), C(2b).' type: string version_added: "2.12" chars: version_added: "1.4" description: - Define comma separated list of names that compose a custom character set in the generated passwords. - 'By default generated passwords contain a random mix of upper and lowercase ASCII letters, the numbers 0-9, and punctuation (". , : - _").' - "They can be either parts of Python's string module attributes or represented literally ( :, -)." - "Though string modules can vary by Python version, valid values for both major releases include: 'ascii_lowercase', 'ascii_uppercase', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation' and 'whitespace'." - Be aware that Python's 'hexdigits' includes lower and upper case versions of a-f, so it is not a good choice as it doubles the chances of those values for systems that won't distinguish case, distorting the expected entropy. - "To enter comma use two commas ',,' somewhere - preferably at the end. Quotes and double quotes are not supported." type: string length: description: The length of the generated password. default: 20 type: integer seed: version_added: "2.12" description: - A seed to initialize the random number generator. - Identical seeds will yield identical passwords. - Use this for random-but-idempotent password generation. type: str notes: - A great alternative to the password lookup plugin, if you don't need to generate random passwords on a per-host basis, would be to use Vault in playbooks. Read the documentation there and consider using it first, it will be more desirable for most applications. - If the file already exists, no data will be written to it. If the file has contents, those contents will be read in as the password. Empty files cause the password to return as an empty string. - 'As all lookups, this runs on the Ansible host as the user running the playbook, and "become" does not apply, the target file must be readable by the playbook user, or, if it does not exist, the playbook user must have sufficient privileges to create it. (So, for example, attempts to write into areas such as /etc will fail unless the entire playbook is being run as root).' """ EXAMPLES = """ - name: create a mysql user with a random password mysql_user: name: "{{ client }}" password: "{{ lookup('password', 'credentials/' + client + '/' + tier + '/' + role + '/mysqlpassword length=15') }}" priv: "{{ client }}_{{ tier }}_{{ role }}.*:ALL" - name: create a mysql user with a random password using only ascii letters mysql_user: name: "{{ client }}" password: "{{ lookup('password', '/tmp/passwordfile chars=ascii_letters') }}" priv: '{{ client }}_{{ tier }}_{{ role }}.*:ALL' - name: create a mysql user with an 8 character random password using only digits mysql_user: name: "{{ client }}" password: "{{ lookup('password', '/tmp/passwordfile length=8 chars=digits') }}" priv: "{{ client }}_{{ tier }}_{{ role }}.*:ALL" - name: create a mysql user with a random password using many different char sets mysql_user: name: "{{ client }}" password: "{{ lookup('password', '/tmp/passwordfile chars=ascii_letters,digits,punctuation') }}" priv: "{{ client }}_{{ tier }}_{{ role }}.*:ALL" - name: create lowercase 8 character name for Kubernetes pod name set_fact: random_pod_name: "web-{{ lookup('password', '/dev/null chars=ascii_lowercase,digits length=8') }}" - name: create random but idempotent password set_fact: password: "{{ lookup('password', '/dev/null', seed=inventory_hostname) }}" """ RETURN = """ _raw: description: - a password type: list elements: str """ import os import string import time import shutil import hashlib from ansible.errors import AnsibleError, AnsibleAssertionError from ansible.module_utils._text import to_bytes, to_native, to_text from ansible.parsing.splitter import parse_kv from ansible.plugins.lookup import LookupBase from ansible.utils.encrypt import BaseHash, do_encrypt, random_password, random_salt from ansible.utils.path import makedirs_safe DEFAULT_LENGTH = 20 VALID_PARAMS = frozenset(('length', 'encrypt', 'chars', 'ident', 'seed')) def _parse_parameters(term): """Hacky parsing of params See https://github.com/ansible/ansible-modules-core/issues/1968#issuecomment-136842156 and the first_found lookup For how we want to fix this later """ first_split = term.split(' ', 1) if len(first_split) <= 1: # Only a single argument given, therefore it's a path relpath = term params = dict() else: relpath = first_split[0] params = parse_kv(first_split[1]) if '_raw_params' in params: # Spaces in the path? relpath = u' '.join((relpath, params['_raw_params'])) del params['_raw_params'] # Check that we parsed the params correctly if not term.startswith(relpath): # Likely, the user had a non parameter following a parameter. # Reject this as a user typo raise AnsibleError('Unrecognized value after key=value parameters given to password lookup') # No _raw_params means we already found the complete path when # we split it initially # Check for invalid parameters. Probably a user typo invalid_params = frozenset(params.keys()).difference(VALID_PARAMS) if invalid_params: raise AnsibleError('Unrecognized parameter(s) given to password lookup: %s' % ', '.join(invalid_params)) # Set defaults params['length'] = int(params.get('length', DEFAULT_LENGTH)) params['encrypt'] = params.get('encrypt', None) params['ident'] = params.get('ident', None) params['seed'] = params.get('seed', None) params['chars'] = params.get('chars', None) if params['chars']: tmp_chars = [] if u',,' in params['chars']: tmp_chars.append(u',') tmp_chars.extend(c for c in params['chars'].replace(u',,', u',').split(u',') if c) params['chars'] = tmp_chars else: # Default chars for password params['chars'] = [u'ascii_letters', u'digits', u".,:-_"] return relpath, params def _read_password_file(b_path): """Read the contents of a password file and return it :arg b_path: A byte string containing the path to the password file :returns: a text string containing the contents of the password file or None if no password file was present. """ content = None if os.path.exists(b_path): with open(b_path, 'rb') as f: b_content = f.read().rstrip() content = to_text(b_content, errors='surrogate_or_strict') return content def _gen_candidate_chars(characters): '''Generate a string containing all valid chars as defined by ``characters`` :arg characters: A list of character specs. The character specs are shorthand names for sets of characters like 'digits', 'ascii_letters', or 'punctuation' or a string to be included verbatim. The values of each char spec can be: * a name of an attribute in the 'strings' module ('digits' for example). The value of the attribute will be added to the candidate chars. * a string of characters. If the string isn't an attribute in 'string' module, the string will be directly added to the candidate chars. For example:: characters=['digits', '?|']`` will match ``string.digits`` and add all ascii digits. ``'?|'`` will add the question mark and pipe characters directly. Return will be the string:: u'0123456789?|' ''' chars = [] for chars_spec in characters: # getattr from string expands things like "ascii_letters" and "digits" # into a set of characters. chars.append(to_text(getattr(string, to_native(chars_spec), chars_spec), errors='strict')) chars = u''.join(chars).replace(u'"', u'').replace(u"'", u'') return chars def _parse_content(content): '''parse our password data format into password and salt :arg content: The data read from the file :returns: password and salt ''' password = content salt = None salt_slug = u' salt=' try: sep = content.rindex(salt_slug) except ValueError: # No salt pass else: salt = password[sep + len(salt_slug):] password = content[:sep] return password, salt def _format_content(password, salt, encrypt=None, ident=None): """Format the password and salt for saving :arg password: the plaintext password to save :arg salt: the salt to use when encrypting a password :arg encrypt: Which method the user requests that this password is encrypted. Note that the password is saved in clear. Encrypt just tells us if we must save the salt value for idempotence. Defaults to None. :arg ident: Which version of BCrypt algorithm to be used. Valid only if value of encrypt is bcrypt. Defaults to None. :returns: a text string containing the formatted information .. warning:: Passwords are saved in clear. This is because the playbooks expect to get cleartext passwords from this lookup. """ if not encrypt and not salt: return password # At this point, the calling code should have assured us that there is a salt value. if not salt: raise AnsibleAssertionError('_format_content was called with encryption requested but no salt value') if ident: return u'%s salt=%s ident=%s' % (password, salt, ident) return u'%s salt=%s' % (password, salt) def _write_password_file(b_path, content): b_pathdir = os.path.dirname(b_path) makedirs_safe(b_pathdir, mode=0o700) with open(b_path, 'wb') as f: os.chmod(b_path, 0o600) b_content = to_bytes(content, errors='surrogate_or_strict') + b'\n' f.write(b_content) def _get_lock(b_path): """Get the lock for writing password file.""" first_process = False b_pathdir = os.path.dirname(b_path) lockfile_name = to_bytes("%s.ansible_lockfile" % hashlib.sha1(b_path).hexdigest()) lockfile = os.path.join(b_pathdir, lockfile_name) if not os.path.exists(lockfile) and b_path != to_bytes('/dev/null'): try: makedirs_safe(b_pathdir, mode=0o700) fd = os.open(lockfile, os.O_CREAT | os.O_EXCL) os.close(fd) first_process = True except OSError as e: if e.strerror != 'File exists': raise counter = 0 # if the lock is got by other process, wait until it's released while os.path.exists(lockfile) and not first_process: time.sleep(2 ** counter) if counter >= 2: raise AnsibleError("Password lookup cannot get the lock in 7 seconds, abort..." "This may caused by un-removed lockfile" "you can manually remove it from controller machine at %s and try again" % lockfile) counter += 1 return first_process, lockfile def _release_lock(lockfile): """Release the lock so other processes can read the password file.""" if os.path.exists(lockfile): os.remove(lockfile) class LookupModule(LookupBase): def run(self, terms, variables, **kwargs): ret = [] for term in terms: relpath, params = _parse_parameters(term) path = self._loader.path_dwim(relpath) b_path = to_bytes(path, errors='surrogate_or_strict') chars = _gen_candidate_chars(params['chars']) changed = None # make sure only one process finishes all the job first first_process, lockfile = _get_lock(b_path) content = _read_password_file(b_path) if content is None or b_path == to_bytes('/dev/null'): plaintext_password = random_password(params['length'], chars, params['seed']) salt = None changed = True else: plaintext_password, salt = _parse_content(content) encrypt = params['encrypt'] if encrypt and not salt: changed = True try: salt = random_salt(BaseHash.algorithms[encrypt].salt_size) except KeyError: salt = random_salt() ident = params['ident'] if encrypt and not ident: changed = True try: ident = BaseHash.algorithms[encrypt].implicit_ident except KeyError: ident = None if changed and b_path != to_bytes('/dev/null'): content = _format_content(plaintext_password, salt, encrypt=encrypt, ident=ident) _write_password_file(b_path, content) if first_process: # let other processes continue _release_lock(lockfile) if encrypt: password = do_encrypt(plaintext_password, encrypt, salt=salt, ident=ident) ret.append(password) else: ret.append(plaintext_password) return ret