repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
savoirfairelinux/django
refs/heads/master
tests/custom_methods/__init__.py
12133432
AniruddhaSAtre/dd-agent
refs/heads/master
checks.d/hdfs.py
29
# 3rd party import snakebite.client import snakebite.version # project from checks import AgentCheck # This is only available on snakebite >= 2.2.0 # but snakebite 2.x is only compatible with hadoop >= 2.2.0 # So we bundle snakebite 1.3.9 and let the possibility to upgrade to a newer version # if people want to use HA Mode try: # FIXME: Can be remove when we upgrade pylint (drop py 2.6) # pylint: disable=E0611 from snakebite.namenode import Namenode except ImportError: Namenode = None DEFAULT_PORT = 8020 class HDFSCheck(AgentCheck): """Report on free space and space used in HDFS. """ def get_client(self, instance): if 'namenode' in instance: # backward compatibility for old style configuration of that check host, port = instance['namenode'], instance.get('port', DEFAULT_PORT) return snakebite.client.Client(host, port) if type(instance['namenodes']) != list or len(instance['namenodes']) == 0: raise ValueError('"namenodes parameter should be a list of dictionaries.') for namenode in instance['namenodes']: if type(namenode) != dict: raise ValueError('"namenodes parameter should be a list of dictionaries.') if "url" not in namenode: raise ValueError('Each namenode should specify a "url" parameter.') if len(instance['namenodes']) == 1: host, port = instance['namenodes'][0]['url'], instance['namenodes'][0].get('port', DEFAULT_PORT) return snakebite.client.Client(host, port) else: # We are running on HA mode if Namenode is None: # We are running snakebite 1.x which is not compatible with the HA mode # Let's display a warning and use regular mode self.warning("HA Mode is not available with snakebite < 2.2.0" "Upgrade to the latest version of snakebiteby running: " "sudo /opt/datadog-agent/embedded/bin/pip install --upgrade snakebite") host, port = instance['namenodes'][0]['url'], instance['namenodes'][0].get('port', DEFAULT_PORT) return snakebite.client.Client(host, port) else: self.log.debug("Running in HA Mode") nodes = [] for namenode in instance['namenodes']: nodes.append(Namenode(namenode['url'], namenode.get('port', DEFAULT_PORT))) return snakebite.client.HAClient(nodes) def check(self, instance): if 'namenode' not in instance and 'namenodes' not in instance: raise ValueError('Missing key \'namenode\' in HDFSCheck config') tags = instance.get('tags', None) hdfs = self.get_client(instance) stats = hdfs.df() # {'used': 2190859321781L, # 'capacity': 76890897326080L, # 'under_replicated': 0L, # 'missing_blocks': 0L, # 'filesystem': 'hdfs://hostname:port', # 'remaining': 71186818453504L, # 'corrupt_blocks': 0L} self.gauge('hdfs.used', stats['used'], tags=tags) self.gauge('hdfs.free', stats['remaining'], tags=tags) self.gauge('hdfs.capacity', stats['capacity'], tags=tags) self.gauge('hdfs.in_use', float(stats['used']) / float(stats['capacity']), tags=tags) self.gauge('hdfs.under_replicated', stats['under_replicated'], tags=tags) self.gauge('hdfs.missing_blocks', stats['missing_blocks'], tags=tags) self.gauge('hdfs.corrupt_blocks', stats['corrupt_blocks'], tags=tags)
maciekcc/tensorflow
refs/heads/master
tensorflow/contrib/distributions/python/kernel_tests/distribution_util_test.py
9
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.distributions.python.ops import distribution_util from tensorflow.contrib.linalg.python.ops import linear_operator_diag from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops import tensorflow.python.ops.nn_grad # pylint: disable=unused-import from tensorflow.python.platform import test class ShapesFromLocAndScaleTest(test.TestCase): def test_static_loc_static_scale_non_matching_event_size_raises(self): loc = constant_op.constant(np.zeros((2, 4))) scale = linear_operator_diag.LinearOperatorDiag(np.ones((5, 1, 3))) with self.assertRaisesRegexp(ValueError, "could not be broadcast"): distribution_util.shapes_from_loc_and_scale(loc, scale) def test_static_loc_static_scale(self): loc = constant_op.constant(np.zeros((2, 3))) scale = linear_operator_diag.LinearOperatorDiag(np.ones((5, 1, 3))) batch_shape, event_shape = distribution_util.shapes_from_loc_and_scale( loc, scale) self.assertEqual(tensor_shape.TensorShape([5, 2]), batch_shape) self.assertEqual(tensor_shape.TensorShape([3]), event_shape) def test_static_loc_dynamic_scale(self): loc = constant_op.constant(np.zeros((2, 3))) diag = array_ops.placeholder(dtypes.float64) scale = linear_operator_diag.LinearOperatorDiag(diag) with self.test_session() as sess: batch_shape, event_shape = sess.run( distribution_util.shapes_from_loc_and_scale(loc, scale), feed_dict={diag: np.ones((5, 1, 3))}) self.assertAllEqual([5, 2], batch_shape) self.assertAllEqual([3], event_shape) def test_dynamic_loc_static_scale(self): loc = array_ops.placeholder(dtypes.float64) diag = constant_op.constant(np.ones((5, 2, 3))) scale = linear_operator_diag.LinearOperatorDiag(diag) with self.test_session(): batch_shape, event_shape = distribution_util.shapes_from_loc_and_scale( loc, scale) # batch_shape depends on both args, and so is dynamic. Since loc did not # have static shape, we inferred event shape entirely from scale, and this # is available statically. self.assertAllEqual( [5, 2], batch_shape.eval(feed_dict={loc: np.zeros((2, 3))})) self.assertAllEqual([3], event_shape) def test_dynamic_loc_dynamic_scale(self): loc = array_ops.placeholder(dtypes.float64) diag = array_ops.placeholder(dtypes.float64) scale = linear_operator_diag.LinearOperatorDiag(diag) with self.test_session() as sess: batch_shape, event_shape = sess.run( distribution_util.shapes_from_loc_and_scale(loc, scale), feed_dict={diag: np.ones((5, 2, 3)), loc: np.zeros((2, 3))}) self.assertAllEqual([5, 2], batch_shape) self.assertAllEqual([3], event_shape) def test_none_loc_static_scale(self): loc = None scale = linear_operator_diag.LinearOperatorDiag(np.ones((5, 1, 3))) batch_shape, event_shape = distribution_util.shapes_from_loc_and_scale( loc, scale) self.assertEqual(tensor_shape.TensorShape([5, 1]), batch_shape) self.assertEqual(tensor_shape.TensorShape([3]), event_shape) def test_none_loc_dynamic_scale(self): loc = None diag = array_ops.placeholder(dtypes.float64) scale = linear_operator_diag.LinearOperatorDiag(diag) with self.test_session() as sess: batch_shape, event_shape = sess.run( distribution_util.shapes_from_loc_and_scale(loc, scale), feed_dict={diag: np.ones((5, 1, 3))}) self.assertAllEqual([5, 1], batch_shape) self.assertAllEqual([3], event_shape) class TridiagTest(test.TestCase): def testWorksCorrectlyNoBatches(self): with self.test_session(): self.assertAllEqual( [[4., 8., 0., 0.], [1., 5., 9., 0.], [0., 2., 6., 10.], [0., 0., 3, 7.]], distribution_util.tridiag( [1., 2., 3.], [4., 5., 6., 7.], [8., 9., 10.]).eval()) def testWorksCorrectlyBatches(self): with self.test_session(): self.assertAllClose( [[[4., 8., 0., 0.], [1., 5., 9., 0.], [0., 2., 6., 10.], [0., 0., 3, 7.]], [[0.7, 0.1, 0.0, 0.0], [0.8, 0.6, 0.2, 0.0], [0.0, 0.9, 0.5, 0.3], [0.0, 0.0, 1.0, 0.4]]], distribution_util.tridiag( [[1., 2., 3.], [0.8, 0.9, 1.]], [[4., 5., 6., 7.], [0.7, 0.6, 0.5, 0.4]], [[8., 9., 10.], [0.1, 0.2, 0.3]]).eval(), rtol=1e-5, atol=0.) def testHandlesNone(self): with self.test_session(): self.assertAllClose( [[[4., 0., 0., 0.], [0., 5., 0., 0.], [0., 0., 6., 0.], [0., 0., 0, 7.]], [[0.7, 0.0, 0.0, 0.0], [0.0, 0.6, 0.0, 0.0], [0.0, 0.0, 0.5, 0.0], [0.0, 0.0, 0.0, 0.4]]], distribution_util.tridiag( diag=[[4., 5., 6., 7.], [0.7, 0.6, 0.5, 0.4]]).eval(), rtol=1e-5, atol=0.) if __name__ == "__main__": test.main()
Zenol/absynth
refs/heads/master
src/wordmap.py
1
from PIL import Image, ImageDraw, ImageFont font = None def build_text_block(w, h, msg, color=(0, 0, 0), bg_color=(255, 255, 255)): # Create a temporary image tmp = Image.new("RGB", font.getsize(msg), bg_color) # Draw msg on this image draw = ImageDraw.Draw(tmp) draw.text((0, 0), msg, color, font=font) # Resize return tmp.resize((w, h), Image.ANTIALIAS) def generate_block(iw, ih, words, lvls = 4, bg_color = (255, 255, 255), fg_color1 = (40, 200, 100), fg_color2 = (0, 50, 200), font_name = "font/DroidSansMono.ttf"): global font font = ImageFont.truetype(font_name, 120) step_size = int(ih / lvls) out = Image.new("RGB", (iw, ih), bg_color) draw = ImageDraw.Draw(out) word_id = 0 sum_h = 0 for i in range(0, lvls): w = int(iw / (2**i)) h = int(ih / 2**(i + 1)) for j in range(0, 2**i): # Compute location x = j * w y = sum_h # Compute color fb = i / lvls fa = 1.0 - fb wmean = lambda a, b: int((fa * a + fb * b) / (fa + fb)) color = tuple(map(wmean, fg_color1, fg_color2)) # Compute image block block = build_text_block(w, h, words[word_id], color=color, bg_color=bg_color) out.paste(block, (x, y , x + w, y + h)) # Switch to next word word_id += 1 sum_h += h return out if __name__ == '__main__': import sys if len(sys.argv) <= 2: print(sys.argv[0] + ' nb_levels big list of words to use...') exit(1) generate_block(600, 300, sys.argv[2:], lvls=int(sys.argv[1])).show()
mayblue9/bokeh
refs/heads/master
bokeh/models/tests/test_renderers.py
10
from __future__ import absolute_import import unittest from bokeh.models.renderers import GlyphRenderer from bokeh.plotting import ColumnDataSource, figure from bokeh.models.ranges import DataRange1d class TestGlyphRenderer(unittest.TestCase): def test_warning_about_colons_in_column_labels(self): invalid_labels = ['0', '1:0'] ds = ColumnDataSource(data={'a': invalid_labels, 'b': invalid_labels}) plot = figure() plot.rect('a', 'b', 1, 1, source=ds) renderer = plot.select({'type': GlyphRenderer})[0] errors = renderer._check_colon_in_category_label() self.assertEqual(errors, [( 1003, 'MALFORMED_CATEGORY_LABEL', 'Category labels are malformed', '[field:a] [first_value: 1:0] [field:b] [first_value: 1:0] ' '[renderer: ' 'GlyphRenderer, ViewModel:GlyphRenderer, ref _id: ' '%s]' % renderer._id )]) def test_warning_about_colons_in_column_labels_for_axis(self): invalid_labels = ['0', '1', '2:0'] plot = figure( x_range=invalid_labels, y_range=invalid_labels, plot_width=900, plot_height=400, ) errors = plot._check_colon_in_category_label() self.assertEqual(errors, [( 1003, 'MALFORMED_CATEGORY_LABEL', 'Category labels are malformed', '[range:x_range] [first_value: 2:0] ' '[range:y_range] [first_value: 2:0] ' '[renderer: Figure, ViewModel:Plot, ref _id: ' '%s]' % plot._id )]) def test_validates_colons_only_in_factorial_range(self): plot = figure( x_range=DataRange1d(start=0.0, end=2.2), y_range=['0', '1', '2:0'], plot_width=900, plot_height=400, ) errors = plot._check_colon_in_category_label() self.assertEqual(errors, [( 1003, 'MALFORMED_CATEGORY_LABEL', 'Category labels are malformed', '[range:y_range] [first_value: 2:0] ' '[renderer: Figure, ViewModel:Plot, ref _id: ' '%s]' % plot._id )]) if __name__ == '__main__': unittest.main()
davidhdz/crits
refs/heads/master
crits/actors/__init__.py
12133432
gonboy/sl4a
refs/heads/master
python/gdata/tests/gdata_tests/apps/migration/__init__.py
12133432
doismellburning/edx-platform
refs/heads/master
lms/djangoapps/dashboard/management/commands/__init__.py
12133432
patcon/open-cabinet
refs/heads/master
venv/lib/python2.7/site-packages/django/db/backends/postgresql/__init__.py
12133432
fangxingli/hue
refs/heads/master
desktop/core/ext-py/Pygments-1.3.1/pygments/lexers/text.py
56
# -*- coding: utf-8 -*- """ pygments.lexers.text ~~~~~~~~~~~~~~~~~~~~ Lexers for non-source code file types. :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from bisect import bisect from pygments.lexer import Lexer, LexerContext, RegexLexer, ExtendedRegexLexer, \ bygroups, include, using, this, do_insertions from pygments.token import Punctuation, Text, Comment, Keyword, Name, String, \ Generic, Operator, Number, Whitespace, Literal from pygments.util import get_bool_opt from pygments.lexers.other import BashLexer __all__ = ['IniLexer', 'SourcesListLexer', 'BaseMakefileLexer', 'MakefileLexer', 'DiffLexer', 'IrcLogsLexer', 'TexLexer', 'GroffLexer', 'ApacheConfLexer', 'BBCodeLexer', 'MoinWikiLexer', 'RstLexer', 'VimLexer', 'GettextLexer', 'SquidConfLexer', 'DebianControlLexer', 'DarcsPatchLexer', 'YamlLexer', 'LighttpdConfLexer', 'NginxConfLexer', 'CMakeLexer'] class IniLexer(RegexLexer): """ Lexer for configuration files in INI style. """ name = 'INI' aliases = ['ini', 'cfg'] filenames = ['*.ini', '*.cfg', '*.properties'] mimetypes = ['text/x-ini'] tokens = { 'root': [ (r'\s+', Text), (r'[;#].*?$', Comment), (r'\[.*?\]$', Keyword), (r'(.*?)([ \t]*)(=)([ \t]*)(.*?)$', bygroups(Name.Attribute, Text, Operator, Text, String)) ] } def analyse_text(text): npos = text.find('\n') if npos < 3: return False return text[0] == '[' and text[npos-1] == ']' class SourcesListLexer(RegexLexer): """ Lexer that highlights debian sources.list files. *New in Pygments 0.7.* """ name = 'Debian Sourcelist' aliases = ['sourceslist', 'sources.list'] filenames = ['sources.list'] mimetype = ['application/x-debian-sourceslist'] tokens = { 'root': [ (r'\s+', Text), (r'#.*?$', Comment), (r'^(deb(?:-src)?)(\s+)', bygroups(Keyword, Text), 'distribution') ], 'distribution': [ (r'#.*?$', Comment, '#pop'), (r'\$\(ARCH\)', Name.Variable), (r'[^\s$[]+', String), (r'\[', String.Other, 'escaped-distribution'), (r'\$', String), (r'\s+', Text, 'components') ], 'escaped-distribution': [ (r'\]', String.Other, '#pop'), (r'\$\(ARCH\)', Name.Variable), (r'[^\]$]+', String.Other), (r'\$', String.Other) ], 'components': [ (r'#.*?$', Comment, '#pop:2'), (r'$', Text, '#pop:2'), (r'\s+', Text), (r'\S+', Keyword.Pseudo), ] } def analyse_text(text): for line in text.split('\n'): line = line.strip() if not (line.startswith('#') or line.startswith('deb ') or line.startswith('deb-src ') or not line): return False return True class MakefileLexer(Lexer): """ Lexer for BSD and GNU make extensions (lenient enough to handle both in the same file even). *Rewritten in Pygments 0.10.* """ name = 'Makefile' aliases = ['make', 'makefile', 'mf', 'bsdmake'] filenames = ['*.mak', 'Makefile', 'makefile', 'Makefile.*', 'GNUmakefile'] mimetypes = ['text/x-makefile'] r_special = re.compile(r'^(?:' # BSD Make r'\.\s*(include|undef|error|warning|if|else|elif|endif|for|endfor)|' # GNU Make r'\s*(ifeq|ifneq|ifdef|ifndef|else|endif|-?include|define|endef|:))(?=\s)') r_comment = re.compile(r'^\s*@?#') def get_tokens_unprocessed(self, text): ins = [] lines = text.splitlines(True) done = '' lex = BaseMakefileLexer(**self.options) backslashflag = False for line in lines: if self.r_special.match(line) or backslashflag: ins.append((len(done), [(0, Comment.Preproc, line)])) backslashflag = line.strip().endswith('\\') elif self.r_comment.match(line): ins.append((len(done), [(0, Comment, line)])) else: done += line for item in do_insertions(ins, lex.get_tokens_unprocessed(done)): yield item class BaseMakefileLexer(RegexLexer): """ Lexer for simple Makefiles (no preprocessing). *New in Pygments 0.10.* """ name = 'Makefile' aliases = ['basemake'] filenames = [] mimetypes = [] tokens = { 'root': [ (r'^(?:[\t ]+.*\n|\n)+', using(BashLexer)), (r'\$\((?:.*\\\n|.*\n)+', using(BashLexer)), (r'\s+', Text), (r'#.*?\n', Comment), (r'(export)(\s+)(?=[a-zA-Z0-9_${}\t -]+\n)', bygroups(Keyword, Text), 'export'), (r'export\s+', Keyword), # assignment (r'([a-zA-Z0-9_${}.-]+)(\s*)([!?:+]?=)([ \t]*)((?:.*\\\n|.*\n)+)', bygroups(Name.Variable, Text, Operator, Text, using(BashLexer))), # strings (r'(?s)"(\\\\|\\.|[^"\\])*"', String.Double), (r"(?s)'(\\\\|\\.|[^'\\])*'", String.Single), # targets (r'([^\n:]+)(:+)([ \t]*)', bygroups(Name.Function, Operator, Text), 'block-header'), # TODO: add paren handling (grr) ], 'export': [ (r'[a-zA-Z0-9_${}-]+', Name.Variable), (r'\n', Text, '#pop'), (r'\s+', Text), ], 'block-header': [ (r'[^,\\\n#]+', Number), (r',', Punctuation), (r'#.*?\n', Comment), (r'\\\n', Text), # line continuation (r'\\.', Text), (r'(?:[\t ]+.*\n|\n)+', using(BashLexer), '#pop'), ], } class DiffLexer(RegexLexer): """ Lexer for unified or context-style diffs or patches. """ name = 'Diff' aliases = ['diff', 'udiff'] filenames = ['*.diff', '*.patch'] mimetypes = ['text/x-diff', 'text/x-patch'] tokens = { 'root': [ (r' .*\n', Text), (r'\+.*\n', Generic.Inserted), (r'-.*\n', Generic.Deleted), (r'!.*\n', Generic.Strong), (r'@.*\n', Generic.Subheading), (r'([Ii]ndex|diff).*\n', Generic.Heading), (r'=.*\n', Generic.Heading), (r'.*\n', Text), ] } def analyse_text(text): if text[:7] == 'Index: ': return True if text[:5] == 'diff ': return True if text[:4] == '--- ': return 0.9 DPATCH_KEYWORDS = ['hunk', 'addfile', 'adddir', 'rmfile', 'rmdir', 'move', 'replace'] class DarcsPatchLexer(RegexLexer): """ DarcsPatchLexer is a lexer for the various versions of the darcs patch format. Examples of this format are derived by commands such as ``darcs annotate --patch`` and ``darcs send``. *New in Pygments 0.10.* """ name = 'Darcs Patch' aliases = ['dpatch'] filenames = ['*.dpatch', '*.darcspatch'] tokens = { 'root': [ (r'<', Operator), (r'>', Operator), (r'{', Operator), (r'}', Operator), (r'(\[)((?:TAG )?)(.*)(\n)(.*)(\*\*)(\d+)(\s?)(\])', bygroups(Operator, Keyword, Name, Text, Name, Operator, Literal.Date, Text, Operator)), (r'(\[)((?:TAG )?)(.*)(\n)(.*)(\*\*)(\d+)(\s?)', bygroups(Operator, Keyword, Name, Text, Name, Operator, Literal.Date, Text), 'comment'), (r'New patches:', Generic.Heading), (r'Context:', Generic.Heading), (r'Patch bundle hash:', Generic.Heading), (r'(\s*)(%s)(.*\n)' % '|'.join(DPATCH_KEYWORDS), bygroups(Text, Keyword, Text)), (r'\+', Generic.Inserted, "insert"), (r'-', Generic.Deleted, "delete"), (r'.*\n', Text), ], 'comment': [ (r'[^\]].*\n', Comment), (r'\]', Operator, "#pop"), ], 'specialText': [ # darcs add [_CODE_] special operators for clarity (r'\n', Text, "#pop"), # line-based (r'\[_[^_]*_]', Operator), ], 'insert': [ include('specialText'), (r'\[', Generic.Inserted), (r'[^\n\[]*', Generic.Inserted), ], 'delete': [ include('specialText'), (r'\[', Generic.Deleted), (r'[^\n\[]*', Generic.Deleted), ], } class IrcLogsLexer(RegexLexer): """ Lexer for IRC logs in *irssi*, *xchat* or *weechat* style. """ name = 'IRC logs' aliases = ['irc'] filenames = ['*.weechatlog'] mimetypes = ['text/x-irclog'] flags = re.VERBOSE | re.MULTILINE timestamp = r""" ( # irssi / xchat and others (?: \[|\()? # Opening bracket or paren for the timestamp (?: # Timestamp (?: (?:\d{1,4} [-/]?)+ # Date as - or /-separated groups of digits [T ])? # Date/time separator: T or space (?: \d?\d [:.]?)+ # Time as :/.-separated groups of 1 or 2 digits ) (?: \]|\))?\s+ # Closing bracket or paren for the timestamp | # weechat \d{4}\s\w{3}\s\d{2}\s # Date \d{2}:\d{2}:\d{2}\s+ # Time + Whitespace | # xchat \w{3}\s\d{2}\s # Date \d{2}:\d{2}:\d{2}\s+ # Time + Whitespace )? """ tokens = { 'root': [ # log start/end (r'^\*\*\*\*(.*)\*\*\*\*$', Comment), # hack ("^" + timestamp + r'(\s*<[^>]*>\s*)$', bygroups(Comment.Preproc, Name.Tag)), # normal msgs ("^" + timestamp + r""" (\s*<.*?>\s*) # Nick """, bygroups(Comment.Preproc, Name.Tag), 'msg'), # /me msgs ("^" + timestamp + r""" (\s*[*]\s+) # Star ([^\s]+\s+.*?\n) # Nick + rest of message """, bygroups(Comment.Preproc, Keyword, Generic.Inserted)), # join/part msgs ("^" + timestamp + r""" (\s*(?:\*{3}|<?-[!@=P]?->?)\s*) # Star(s) or symbols ([^\s]+\s+) # Nick + Space (.*?\n) # Rest of message """, bygroups(Comment.Preproc, Keyword, String, Comment)), (r"^.*?\n", Text), ], 'msg': [ (r"[^\s]+:(?!//)", Name.Attribute), # Prefix (r".*\n", Text, '#pop'), ], } class BBCodeLexer(RegexLexer): """ A lexer that highlights BBCode(-like) syntax. *New in Pygments 0.6.* """ name = 'BBCode' aliases = ['bbcode'] mimetypes = ['text/x-bbcode'] tokens = { 'root': [ (r'[^[]+', Text), # tag/end tag begin (r'\[/?\w+', Keyword, 'tag'), # stray bracket (r'\[', Text), ], 'tag': [ (r'\s+', Text), # attribute with value (r'(\w+)(=)("?[^\s"\]]+"?)', bygroups(Name.Attribute, Operator, String)), # tag argument (a la [color=green]) (r'(=)("?[^\s"\]]+"?)', bygroups(Operator, String)), # tag end (r'\]', Keyword, '#pop'), ], } class TexLexer(RegexLexer): """ Lexer for the TeX and LaTeX typesetting languages. """ name = 'TeX' aliases = ['tex', 'latex'] filenames = ['*.tex', '*.aux', '*.toc'] mimetypes = ['text/x-tex', 'text/x-latex'] tokens = { 'general': [ (r'%.*?\n', Comment), (r'[{}]', Name.Builtin), (r'[&_^]', Name.Builtin), ], 'root': [ (r'\\\[', String.Backtick, 'displaymath'), (r'\\\(', String, 'inlinemath'), (r'\$\$', String.Backtick, 'displaymath'), (r'\$', String, 'inlinemath'), (r'\\([a-zA-Z]+|.)', Keyword, 'command'), include('general'), (r'[^\\$%&_^{}]+', Text), ], 'math': [ (r'\\([a-zA-Z]+|.)', Name.Variable), include('general'), (r'[0-9]+', Number), (r'[-=!+*/()\[\]]', Operator), (r'[^=!+*/()\[\]\\$%&_^{}0-9-]+', Name.Builtin), ], 'inlinemath': [ (r'\\\)', String, '#pop'), (r'\$', String, '#pop'), include('math'), ], 'displaymath': [ (r'\\\]', String, '#pop'), (r'\$\$', String, '#pop'), (r'\$', Name.Builtin), include('math'), ], 'command': [ (r'\[.*?\]', Name.Attribute), (r'\*', Keyword), (r'', Text, '#pop'), ], } def analyse_text(text): for start in ("\\documentclass", "\\input", "\\documentstyle", "\\relax"): if text[:len(start)] == start: return True class GroffLexer(RegexLexer): """ Lexer for the (g)roff typesetting language, supporting groff extensions. Mainly useful for highlighting manpage sources. *New in Pygments 0.6.* """ name = 'Groff' aliases = ['groff', 'nroff', 'man'] filenames = ['*.[1234567]', '*.man'] mimetypes = ['application/x-troff', 'text/troff'] tokens = { 'root': [ (r'(?i)(\.)(\w+)', bygroups(Text, Keyword), 'request'), (r'\.', Punctuation, 'request'), # Regular characters, slurp till we find a backslash or newline (r'[^\\\n]*', Text, 'textline'), ], 'textline': [ include('escapes'), (r'[^\\\n]+', Text), (r'\n', Text, '#pop'), ], 'escapes': [ # groff has many ways to write escapes. (r'\\"[^\n]*', Comment), (r'\\[fn]\w', String.Escape), (r'\\\(..', String.Escape), (r'\\.\[.*\]', String.Escape), (r'\\.', String.Escape), (r'\\\n', Text, 'request'), ], 'request': [ (r'\n', Text, '#pop'), include('escapes'), (r'"[^\n"]+"', String.Double), (r'\d+', Number), (r'\S+', String), (r'\s+', Text), ], } def analyse_text(text): if text[:1] != '.': return False if text[:3] == '.\\"': return True if text[:4] == '.TH ': return True if text[1:3].isalnum() and text[3].isspace(): return 0.9 class ApacheConfLexer(RegexLexer): """ Lexer for configuration files following the Apache config file format. *New in Pygments 0.6.* """ name = 'ApacheConf' aliases = ['apacheconf', 'aconf', 'apache'] filenames = ['.htaccess', 'apache.conf', 'apache2.conf'] mimetypes = ['text/x-apacheconf'] flags = re.MULTILINE | re.IGNORECASE tokens = { 'root': [ (r'\s+', Text), (r'(#.*?)$', Comment), (r'(<[^\s>]+)(?:(\s+)(.*?))?(>)', bygroups(Name.Tag, Text, String, Name.Tag)), (r'([a-zA-Z][a-zA-Z0-9]*)(\s+)', bygroups(Name.Builtin, Text), 'value'), (r'\.+', Text), ], 'value': [ (r'$', Text, '#pop'), (r'[^\S\n]+', Text), (r'\d+\.\d+\.\d+\.\d+(?:/\d+)?', Number), (r'\d+', Number), (r'/([a-zA-Z0-9][a-zA-Z0-9_./-]+)', String.Other), (r'(on|off|none|any|all|double|email|dns|min|minimal|' r'os|productonly|full|emerg|alert|crit|error|warn|' r'notice|info|debug|registry|script|inetd|standalone|' r'user|group)\b', Keyword), (r'"([^"\\]*(?:\\.[^"\\]*)*)"', String.Double), (r'[^\s"]+', Text) ] } class MoinWikiLexer(RegexLexer): """ For MoinMoin (and Trac) Wiki markup. *New in Pygments 0.7.* """ name = 'MoinMoin/Trac Wiki markup' aliases = ['trac-wiki', 'moin'] filenames = [] mimetypes = ['text/x-trac-wiki'] flags = re.MULTILINE | re.IGNORECASE tokens = { 'root': [ (r'^#.*$', Comment), (r'(!)(\S+)', bygroups(Keyword, Text)), # Ignore-next # Titles (r'^(=+)([^=]+)(=+)(\s*#.+)?$', bygroups(Generic.Heading, using(this), Generic.Heading, String)), # Literal code blocks, with optional shebang (r'({{{)(\n#!.+)?', bygroups(Name.Builtin, Name.Namespace), 'codeblock'), (r'(\'\'\'?|\|\||`|__|~~|\^|,,|::)', Comment), # Formatting # Lists (r'^( +)([.*-])( )', bygroups(Text, Name.Builtin, Text)), (r'^( +)([a-zivx]{1,5}\.)( )', bygroups(Text, Name.Builtin, Text)), # Other Formatting (r'\[\[\w+.*?\]\]', Keyword), # Macro (r'(\[[^\s\]]+)(\s+[^\]]+?)?(\])', bygroups(Keyword, String, Keyword)), # Link (r'^----+$', Keyword), # Horizontal rules (r'[^\n\'\[{!_~^,|]+', Text), (r'\n', Text), (r'.', Text), ], 'codeblock': [ (r'}}}', Name.Builtin, '#pop'), # these blocks are allowed to be nested in Trac, but not MoinMoin (r'{{{', Text, '#push'), (r'[^{}]+', Comment.Preproc), # slurp boring text (r'.', Comment.Preproc), # allow loose { or } ], } class RstLexer(RegexLexer): """ For `reStructuredText <http://docutils.sf.net/rst.html>`_ markup. *New in Pygments 0.7.* Additional options accepted: `handlecodeblocks` Highlight the contents of ``.. sourcecode:: langauge`` and ``.. code:: language`` directives with a lexer for the given language (default: ``True``). *New in Pygments 0.8.* """ name = 'reStructuredText' aliases = ['rst', 'rest', 'restructuredtext'] filenames = ['*.rst', '*.rest'] mimetypes = ["text/x-rst", "text/prs.fallenstein.rst"] flags = re.MULTILINE def _handle_sourcecode(self, match): from pygments.lexers import get_lexer_by_name from pygments.util import ClassNotFound # section header yield match.start(1), Punctuation, match.group(1) yield match.start(2), Text, match.group(2) yield match.start(3), Operator.Word, match.group(3) yield match.start(4), Punctuation, match.group(4) yield match.start(5), Text, match.group(5) yield match.start(6), Keyword, match.group(6) yield match.start(7), Text, match.group(7) # lookup lexer if wanted and existing lexer = None if self.handlecodeblocks: try: lexer = get_lexer_by_name(match.group(6).strip()) except ClassNotFound: pass indention = match.group(8) indention_size = len(indention) code = (indention + match.group(9) + match.group(10) + match.group(11)) # no lexer for this language. handle it like it was a code block if lexer is None: yield match.start(8), String, code return # highlight the lines with the lexer. ins = [] codelines = code.splitlines(True) code = '' for line in codelines: if len(line) > indention_size: ins.append((len(code), [(0, Text, line[:indention_size])])) code += line[indention_size:] else: code += line for item in do_insertions(ins, lexer.get_tokens_unprocessed(code)): yield item tokens = { 'root': [ # Heading with overline (r'^(=+|-+|`+|:+|\.+|\'+|"+|~+|\^+|_+|\*+|\++|#+)([ \t]*\n)' r'(.+)(\n)(\1)(\n)', bygroups(Generic.Heading, Text, Generic.Heading, Text, Generic.Heading, Text)), # Plain heading (r'^(\S.*)(\n)(={3,}|-{3,}|`{3,}|:{3,}|\.{3,}|\'{3,}|"{3,}|' r'~{3,}|\^{3,}|_{3,}|\*{3,}|\+{3,}|#{3,})(\n)', bygroups(Generic.Heading, Text, Generic.Heading, Text)), # Bulleted lists (r'^(\s*)([-*+])( .+\n(?:\1 .+\n)*)', bygroups(Text, Number, using(this, state='inline'))), # Numbered lists (r'^(\s*)([0-9#ivxlcmIVXLCM]+\.)( .+\n(?:\1 .+\n)*)', bygroups(Text, Number, using(this, state='inline'))), (r'^(\s*)(\(?[0-9#ivxlcmIVXLCM]+\))( .+\n(?:\1 .+\n)*)', bygroups(Text, Number, using(this, state='inline'))), # Numbered, but keep words at BOL from becoming lists (r'^(\s*)([A-Z]+\.)( .+\n(?:\1 .+\n)+)', bygroups(Text, Number, using(this, state='inline'))), (r'^(\s*)(\(?[A-Za-z]+\))( .+\n(?:\1 .+\n)+)', bygroups(Text, Number, using(this, state='inline'))), # Line blocks (r'^(\s*)(\|)( .+\n(?:\| .+\n)*)', bygroups(Text, Operator, using(this, state='inline'))), # Sourcecode directives (r'^( *\.\.)(\s*)((?:source)?code)(::)([ \t]*)([^\n]+)' r'(\n[ \t]*\n)([ \t]+)(.*)(\n)((?:(?:\8.*|)\n)+)', _handle_sourcecode), # A directive (r'^( *\.\.)(\s*)([\w:-]+?)(::)(?:([ \t]*)(.*))', bygroups(Punctuation, Text, Operator.Word, Punctuation, Text, using(this, state='inline'))), # A reference target (r'^( *\.\.)(\s*)([\w\t ]+:)(.*?)$', bygroups(Punctuation, Text, Name.Tag, using(this, state='inline'))), # A footnote target (r'^( *\.\.)(\s*)(\[.+\])(.*?)$', bygroups(Punctuation, Text, Name.Tag, using(this, state='inline'))), # A substitution def (r'^( *\.\.)(\s*)(\|.+\|)(\s*)([\w:-]+?)(::)(?:([ \t]*)(.*))', bygroups(Punctuation, Text, Name.Tag, Text, Operator.Word, Punctuation, Text, using(this, state='inline'))), # Comments (r'^ *\.\..*(\n( +.*\n|\n)+)?', Comment.Preproc), # Field list (r'^( *)(:[a-zA-Z-]+:)(\s*)$', bygroups(Text, Name.Class, Text)), (r'^( *)(:.*?:)([ \t]+)(.*?)$', bygroups(Text, Name.Class, Text, Name.Function)), # Definition list (r'^([^ ].*(?<!::)\n)((?:(?: +.*)\n)+)', bygroups(using(this, state='inline'), using(this, state='inline'))), # Code blocks (r'(::)(\n[ \t]*\n)([ \t]+)(.*)(\n)((?:(?:\3.*|)\n)+)', bygroups(String.Escape, Text, String, String, Text, String)), include('inline'), ], 'inline': [ (r'\\.', Text), # escape (r'``', String, 'literal'), # code (r'(`.+?)(<.+?>)(`__?)', # reference with inline target bygroups(String, String.Interpol, String)), (r'`.+?`__?', String), # reference (r'(`.+?`)(:[a-zA-Z0-9:-]+?:)?', bygroups(Name.Variable, Name.Attribute)), # role (r'(:[a-zA-Z0-9:-]+?:)(`.+?`)', bygroups(Name.Attribute, Name.Variable)), # role (content first) (r'\*\*.+?\*\*', Generic.Strong), # Strong emphasis (r'\*.+?\*', Generic.Emph), # Emphasis (r'\[.*?\]_', String), # Footnote or citation (r'<.+?>', Name.Tag), # Hyperlink (r'[^\\\n\[*`:]+', Text), (r'.', Text), ], 'literal': [ (r'[^`\\]+', String), (r'\\.', String), (r'``', String, '#pop'), (r'[`\\]', String), ] } def __init__(self, **options): self.handlecodeblocks = get_bool_opt(options, 'handlecodeblocks', True) RegexLexer.__init__(self, **options) def analyse_text(text): if text[:2] == '..' and text[2:3] != '.': return 0.3 p1 = text.find("\n") p2 = text.find("\n", p1 + 1) if (p2 > -1 and # has two lines p1 * 2 + 1 == p2 and # they are the same length text[p1+1] in '-=' and # the next line both starts and ends with text[p1+1] == text[p2-1]): # ...a sufficiently high header return 0.5 class VimLexer(RegexLexer): """ Lexer for VimL script files. *New in Pygments 0.8.* """ name = 'VimL' aliases = ['vim'] filenames = ['*.vim', '.vimrc'] mimetypes = ['text/x-vim'] flags = re.MULTILINE tokens = { 'root': [ # Who decided that doublequote was a good comment character?? (r'^\s*".*', Comment), (r'(?<=\s)"[^\-:.%#=*].*', Comment), (r'[ \t]+', Text), # TODO: regexes can have other delims (r'/(\\\\|\\/|[^\n/])*/', String.Regex), (r'"(\\\\|\\"|[^\n"])*"', String.Double), (r"'(\\\\|\\'|[^\n'])*'", String.Single), (r'-?\d+', Number), (r'#[0-9a-f]{6}', Number.Hex), (r'^:', Punctuation), (r'[()<>+=!|,~-]', Punctuation), # Inexact list. Looks decent. (r'\b(let|if|else|endif|elseif|fun|function|endfunction)\b', Keyword), (r'\b(NONE|bold|italic|underline|dark|light)\b', Name.Builtin), (r'\b\w+\b', Name.Other), # These are postprocessed below (r'.', Text), ], } def __init__(self, **options): from pygments.lexers._vimbuiltins import command, option, auto self._cmd = command self._opt = option self._aut = auto RegexLexer.__init__(self, **options) def is_in(self, w, mapping): r""" It's kind of difficult to decide if something might be a keyword in VimL because it allows you to abbreviate them. In fact, 'ab[breviate]' is a good example. :ab, :abbre, or :abbreviate are valid ways to call it so rather than making really awful regexps like:: \bab(?:b(?:r(?:e(?:v(?:i(?:a(?:t(?:e)?)?)?)?)?)?)?)?\b we match `\b\w+\b` and then call is_in() on those tokens. See `scripts/get_vimkw.py` for how the lists are extracted. """ p = bisect(mapping, (w,)) if p > 0: if mapping[p-1][0] == w[:len(mapping[p-1][0])] and \ mapping[p-1][1][:len(w)] == w: return True if p < len(mapping): return mapping[p][0] == w[:len(mapping[p][0])] and \ mapping[p][1][:len(w)] == w return False def get_tokens_unprocessed(self, text): # TODO: builtins are only subsequent tokens on lines # and 'keywords' only happen at the beginning except # for :au ones for index, token, value in \ RegexLexer.get_tokens_unprocessed(self, text): if token is Name.Other: if self.is_in(value, self._cmd): yield index, Keyword, value elif self.is_in(value, self._opt) or \ self.is_in(value, self._aut): yield index, Name.Builtin, value else: yield index, Text, value else: yield index, token, value class GettextLexer(RegexLexer): """ Lexer for Gettext catalog files. *New in Pygments 0.9.* """ name = 'Gettext Catalog' aliases = ['pot', 'po'] filenames = ['*.pot', '*.po'] mimetypes = ['application/x-gettext', 'text/x-gettext', 'text/gettext'] tokens = { 'root': [ (r'^#,\s.*?$', Keyword.Type), (r'^#:\s.*?$', Keyword.Declaration), #(r'^#$', Comment), (r'^(#|#\.\s|#\|\s|#~\s|#\s).*$', Comment.Single), (r'^(")([\w-]*:)(.*")$', bygroups(String, Name.Property, String)), (r'^".*"$', String), (r'^(msgid|msgid_plural|msgstr)(\s+)(".*")$', bygroups(Name.Variable, Text, String)), (r'^(msgstr\[)(\d)(\])(\s+)(".*")$', bygroups(Name.Variable, Number.Integer, Name.Variable, Text, String)), ] } class SquidConfLexer(RegexLexer): """ Lexer for `squid <http://www.squid-cache.org/>`_ configuration files. *New in Pygments 0.9.* """ name = 'SquidConf' aliases = ['squidconf', 'squid.conf', 'squid'] filenames = ['squid.conf'] mimetypes = ['text/x-squidconf'] flags = re.IGNORECASE keywords = [ "acl", "always_direct", "announce_host", "announce_period", "announce_port", "announce_to", "anonymize_headers", "append_domain", "as_whois_server", "auth_param_basic", "authenticate_children", "authenticate_program", "authenticate_ttl", "broken_posts", "buffered_logs", "cache_access_log", "cache_announce", "cache_dir", "cache_dns_program", "cache_effective_group", "cache_effective_user", "cache_host", "cache_host_acl", "cache_host_domain", "cache_log", "cache_mem", "cache_mem_high", "cache_mem_low", "cache_mgr", "cachemgr_passwd", "cache_peer", "cache_peer_access", "cahce_replacement_policy", "cache_stoplist", "cache_stoplist_pattern", "cache_store_log", "cache_swap", "cache_swap_high", "cache_swap_log", "cache_swap_low", "client_db", "client_lifetime", "client_netmask", "connect_timeout", "coredump_dir", "dead_peer_timeout", "debug_options", "delay_access", "delay_class", "delay_initial_bucket_level", "delay_parameters", "delay_pools", "deny_info", "dns_children", "dns_defnames", "dns_nameservers", "dns_testnames", "emulate_httpd_log", "err_html_text", "fake_user_agent", "firewall_ip", "forwarded_for", "forward_snmpd_port", "fqdncache_size", "ftpget_options", "ftpget_program", "ftp_list_width", "ftp_passive", "ftp_user", "half_closed_clients", "header_access", "header_replace", "hierarchy_stoplist", "high_response_time_warning", "high_page_fault_warning", "htcp_port", "http_access", "http_anonymizer", "httpd_accel", "httpd_accel_host", "httpd_accel_port", "httpd_accel_uses_host_header", "httpd_accel_with_proxy", "http_port", "http_reply_access", "icp_access", "icp_hit_stale", "icp_port", "icp_query_timeout", "ident_lookup", "ident_lookup_access", "ident_timeout", "incoming_http_average", "incoming_icp_average", "inside_firewall", "ipcache_high", "ipcache_low", "ipcache_size", "local_domain", "local_ip", "logfile_rotate", "log_fqdn", "log_icp_queries", "log_mime_hdrs", "maximum_object_size", "maximum_single_addr_tries", "mcast_groups", "mcast_icp_query_timeout", "mcast_miss_addr", "mcast_miss_encode_key", "mcast_miss_port", "memory_pools", "memory_pools_limit", "memory_replacement_policy", "mime_table", "min_http_poll_cnt", "min_icp_poll_cnt", "minimum_direct_hops", "minimum_object_size", "minimum_retry_timeout", "miss_access", "negative_dns_ttl", "negative_ttl", "neighbor_timeout", "neighbor_type_domain", "netdb_high", "netdb_low", "netdb_ping_period", "netdb_ping_rate", "never_direct", "no_cache", "passthrough_proxy", "pconn_timeout", "pid_filename", "pinger_program", "positive_dns_ttl", "prefer_direct", "proxy_auth", "proxy_auth_realm", "query_icmp", "quick_abort", "quick_abort", "quick_abort_max", "quick_abort_min", "quick_abort_pct", "range_offset_limit", "read_timeout", "redirect_children", "redirect_program", "redirect_rewrites_host_header", "reference_age", "reference_age", "refresh_pattern", "reload_into_ims", "request_body_max_size", "request_size", "request_timeout", "shutdown_lifetime", "single_parent_bypass", "siteselect_timeout", "snmp_access", "snmp_incoming_address", "snmp_port", "source_ping", "ssl_proxy", "store_avg_object_size", "store_objects_per_bucket", "strip_query_terms", "swap_level1_dirs", "swap_level2_dirs", "tcp_incoming_address", "tcp_outgoing_address", "tcp_recv_bufsize", "test_reachability", "udp_hit_obj", "udp_hit_obj_size", "udp_incoming_address", "udp_outgoing_address", "unique_hostname", "unlinkd_program", "uri_whitespace", "useragent_log", "visible_hostname", "wais_relay", "wais_relay_host", "wais_relay_port", ] opts = [ "proxy-only", "weight", "ttl", "no-query", "default", "round-robin", "multicast-responder", "on", "off", "all", "deny", "allow", "via", "parent", "no-digest", "heap", "lru", "realm", "children", "credentialsttl", "none", "disable", "offline_toggle", "diskd", "q1", "q2", ] actions = [ "shutdown", "info", "parameter", "server_list", "client_list", r'squid\.conf', ] actions_stats = [ "objects", "vm_objects", "utilization", "ipcache", "fqdncache", "dns", "redirector", "io", "reply_headers", "filedescriptors", "netdb", ] actions_log = [ "status", "enable", "disable", "clear"] acls = [ "url_regex", "urlpath_regex", "referer_regex", "port", "proto", "req_mime_type", "rep_mime_type", "method", "browser", "user", "src", "dst", "time", "dstdomain", "ident", "snmp_community", ] ip_re = r'\b(?:\d{1,3}\.){3}\d{1,3}\b' def makelistre(list): return r'\b(?:'+'|'.join(list)+r')\b' tokens = { 'root': [ (r'\s+', Text), (r'#', Comment, 'comment'), (makelistre(keywords), Keyword), (makelistre(opts), Name.Constant), # Actions (makelistre(actions), String), (r'stats/'+makelistre(actions), String), (r'log/'+makelistre(actions)+r'=', String), (makelistre(acls), Keyword), (ip_re+r'(?:/(?:'+ip_re+r')|\d+)?', Number), (r'\b\d+\b', Number), (r'\S+', Text), ], 'comment': [ (r'\s*TAG:.*', String.Escape, '#pop'), (r'.*', Comment, '#pop'), ], } class DebianControlLexer(RegexLexer): """ Lexer for Debian ``control`` files and ``apt-cache show <pkg>`` outputs. *New in Pygments 0.9.* """ name = 'Debian Control file' aliases = ['control'] filenames = ['control'] tokens = { 'root': [ (r'^(Description)', Keyword, 'description'), (r'^(Maintainer)(:\s*)', bygroups(Keyword, Text), 'maintainer'), (r'^((Build-)?Depends)', Keyword, 'depends'), (r'^((?:Python-)?Version)(:\s*)([^\s]+)$', bygroups(Keyword, Text, Number)), (r'^((?:Installed-)?Size)(:\s*)([^\s]+)$', bygroups(Keyword, Text, Number)), (r'^(MD5Sum|SHA1|SHA256)(:\s*)([^\s]+)$', bygroups(Keyword, Text, Number)), (r'^([a-zA-Z\-0-9\.]*?)(:\s*)(.*?)$', bygroups(Keyword, Whitespace, String)), ], 'maintainer': [ (r'<[^>]+>', Generic.Strong), (r'<[^>]+>$', Generic.Strong, '#pop'), (r',\n?', Text), (r'.', Text), ], 'description': [ (r'(.*)(Homepage)(: )([^\s]+)', bygroups(Text, String, Name, Name.Class)), (r':.*\n', Generic.Strong), (r' .*\n', Text), ('', Text, '#pop'), ], 'depends': [ (r':\s*', Text), (r'(\$)(\{)(\w+\s*:\s*\w+)', bygroups(Operator, Text, Name.Entity)), (r'\(', Text, 'depend_vers'), (r',', Text), (r'\|', Operator), (r'[\s]+', Text), (r'[}\)]\s*$', Text, '#pop'), (r'[}]', Text), (r'[^,]$', Name.Function, '#pop'), (r'([\+\.a-zA-Z0-9-][\s\n]*)', Name.Function), (r'\[.*?\]', Name.Entity), ], 'depend_vers': [ (r'\),', Text, '#pop'), (r'\)[^,]', Text, '#pop:2'), (r'([><=]+)(\s*)([^\)]+)', bygroups(Operator, Text, Number)) ] } class YamlLexerContext(LexerContext): """Indentation context for the YAML lexer.""" def __init__(self, *args, **kwds): super(YamlLexerContext, self).__init__(*args, **kwds) self.indent_stack = [] self.indent = -1 self.next_indent = 0 self.block_scalar_indent = None class YamlLexer(ExtendedRegexLexer): """ Lexer for `YAML <http://yaml.org/>`_, a human-friendly data serialization language. *New in Pygments 0.11.* """ name = 'YAML' aliases = ['yaml'] filenames = ['*.yaml', '*.yml'] mimetypes = ['text/x-yaml'] def something(token_class): """Do not produce empty tokens.""" def callback(lexer, match, context): text = match.group() if not text: return yield match.start(), token_class, text context.pos = match.end() return callback def reset_indent(token_class): """Reset the indentation levels.""" def callback(lexer, match, context): text = match.group() context.indent_stack = [] context.indent = -1 context.next_indent = 0 context.block_scalar_indent = None yield match.start(), token_class, text context.pos = match.end() return callback def save_indent(token_class, start=False): """Save a possible indentation level.""" def callback(lexer, match, context): text = match.group() extra = '' if start: context.next_indent = len(text) if context.next_indent < context.indent: while context.next_indent < context.indent: context.indent = context.indent_stack.pop() if context.next_indent > context.indent: extra = text[context.indent:] text = text[:context.indent] else: context.next_indent += len(text) if text: yield match.start(), token_class, text if extra: yield match.start()+len(text), token_class.Error, extra context.pos = match.end() return callback def set_indent(token_class, implicit=False): """Set the previously saved indentation level.""" def callback(lexer, match, context): text = match.group() if context.indent < context.next_indent: context.indent_stack.append(context.indent) context.indent = context.next_indent if not implicit: context.next_indent += len(text) yield match.start(), token_class, text context.pos = match.end() return callback def set_block_scalar_indent(token_class): """Set an explicit indentation level for a block scalar.""" def callback(lexer, match, context): text = match.group() context.block_scalar_indent = None if not text: return increment = match.group(1) if increment: current_indent = max(context.indent, 0) increment = int(increment) context.block_scalar_indent = current_indent + increment if text: yield match.start(), token_class, text context.pos = match.end() return callback def parse_block_scalar_empty_line(indent_token_class, content_token_class): """Process an empty line in a block scalar.""" def callback(lexer, match, context): text = match.group() if (context.block_scalar_indent is None or len(text) <= context.block_scalar_indent): if text: yield match.start(), indent_token_class, text else: indentation = text[:context.block_scalar_indent] content = text[context.block_scalar_indent:] yield match.start(), indent_token_class, indentation yield (match.start()+context.block_scalar_indent, content_token_class, content) context.pos = match.end() return callback def parse_block_scalar_indent(token_class): """Process indentation spaces in a block scalar.""" def callback(lexer, match, context): text = match.group() if context.block_scalar_indent is None: if len(text) <= max(context.indent, 0): context.stack.pop() context.stack.pop() return context.block_scalar_indent = len(text) else: if len(text) < context.block_scalar_indent: context.stack.pop() context.stack.pop() return if text: yield match.start(), token_class, text context.pos = match.end() return callback def parse_plain_scalar_indent(token_class): """Process indentation spaces in a plain scalar.""" def callback(lexer, match, context): text = match.group() if len(text) <= context.indent: context.stack.pop() context.stack.pop() return if text: yield match.start(), token_class, text context.pos = match.end() return callback tokens = { # the root rules 'root': [ # ignored whitespaces (r'[ ]+(?=#|$)', Text), # line breaks (r'\n+', Text), # a comment (r'#[^\n]*', Comment.Single), # the '%YAML' directive (r'^%YAML(?=[ ]|$)', reset_indent(Name.Tag), 'yaml-directive'), # the %TAG directive (r'^%TAG(?=[ ]|$)', reset_indent(Name.Tag), 'tag-directive'), # document start and document end indicators (r'^(?:---|\.\.\.)(?=[ ]|$)', reset_indent(Name.Namespace), 'block-line'), # indentation spaces (r'[ ]*(?![ \t\n\r\f\v]|$)', save_indent(Text, start=True), ('block-line', 'indentation')), ], # trailing whitespaces after directives or a block scalar indicator 'ignored-line': [ # ignored whitespaces (r'[ ]+(?=#|$)', Text), # a comment (r'#[^\n]*', Comment.Single), # line break (r'\n', Text, '#pop:2'), ], # the %YAML directive 'yaml-directive': [ # the version number (r'([ ]+)([0-9]+\.[0-9]+)', bygroups(Text, Number), 'ignored-line'), ], # the %YAG directive 'tag-directive': [ # a tag handle and the corresponding prefix (r'([ ]+)(!|![0-9A-Za-z_-]*!)' r'([ ]+)(!|!?[0-9A-Za-z;/?:@&=+$,_.!~*\'()\[\]%-]+)', bygroups(Text, Keyword.Type, Text, Keyword.Type), 'ignored-line'), ], # block scalar indicators and indentation spaces 'indentation': [ # trailing whitespaces are ignored (r'[ ]*$', something(Text), '#pop:2'), # whitespaces preceeding block collection indicators (r'[ ]+(?=[?:-](?:[ ]|$))', save_indent(Text)), # block collection indicators (r'[?:-](?=[ ]|$)', set_indent(Punctuation.Indicator)), # the beginning a block line (r'[ ]*', save_indent(Text), '#pop'), ], # an indented line in the block context 'block-line': [ # the line end (r'[ ]*(?=#|$)', something(Text), '#pop'), # whitespaces separating tokens (r'[ ]+', Text), # tags, anchors and aliases, include('descriptors'), # block collections and scalars include('block-nodes'), # flow collections and quoted scalars include('flow-nodes'), # a plain scalar (r'(?=[^ \t\n\r\f\v?:,\[\]{}#&*!|>\'"%@`-]|[?:-][^ \t\n\r\f\v])', something(Name.Variable), 'plain-scalar-in-block-context'), ], # tags, anchors, aliases 'descriptors' : [ # a full-form tag (r'!<[0-9A-Za-z;/?:@&=+$,_.!~*\'()\[\]%-]+>', Keyword.Type), # a tag in the form '!', '!suffix' or '!handle!suffix' (r'!(?:[0-9A-Za-z_-]+)?' r'(?:![0-9A-Za-z;/?:@&=+$,_.!~*\'()\[\]%-]+)?', Keyword.Type), # an anchor (r'&[0-9A-Za-z_-]+', Name.Label), # an alias (r'\*[0-9A-Za-z_-]+', Name.Variable), ], # block collections and scalars 'block-nodes': [ # implicit key (r':(?=[ ]|$)', set_indent(Punctuation.Indicator, implicit=True)), # literal and folded scalars (r'[|>]', Punctuation.Indicator, ('block-scalar-content', 'block-scalar-header')), ], # flow collections and quoted scalars 'flow-nodes': [ # a flow sequence (r'\[', Punctuation.Indicator, 'flow-sequence'), # a flow mapping (r'\{', Punctuation.Indicator, 'flow-mapping'), # a single-quoted scalar (r'\'', String, 'single-quoted-scalar'), # a double-quoted scalar (r'\"', String, 'double-quoted-scalar'), ], # the content of a flow collection 'flow-collection': [ # whitespaces (r'[ ]+', Text), # line breaks (r'\n+', Text), # a comment (r'#[^\n]*', Comment.Single), # simple indicators (r'[?:,]', Punctuation.Indicator), # tags, anchors and aliases include('descriptors'), # nested collections and quoted scalars include('flow-nodes'), # a plain scalar (r'(?=[^ \t\n\r\f\v?:,\[\]{}#&*!|>\'"%@`])', something(Name.Variable), 'plain-scalar-in-flow-context'), ], # a flow sequence indicated by '[' and ']' 'flow-sequence': [ # include flow collection rules include('flow-collection'), # the closing indicator (r'\]', Punctuation.Indicator, '#pop'), ], # a flow mapping indicated by '{' and '}' 'flow-mapping': [ # include flow collection rules include('flow-collection'), # the closing indicator (r'\}', Punctuation.Indicator, '#pop'), ], # block scalar lines 'block-scalar-content': [ # line break (r'\n', Text), # empty line (r'^[ ]+$', parse_block_scalar_empty_line(Text, Name.Constant)), # indentation spaces (we may leave the state here) (r'^[ ]*', parse_block_scalar_indent(Text)), # line content (r'[^\n\r\f\v]+', Name.Constant), ], # the content of a literal or folded scalar 'block-scalar-header': [ # indentation indicator followed by chomping flag (r'([1-9])?[+-]?(?=[ ]|$)', set_block_scalar_indent(Punctuation.Indicator), 'ignored-line'), # chomping flag followed by indentation indicator (r'[+-]?([1-9])?(?=[ ]|$)', set_block_scalar_indent(Punctuation.Indicator), 'ignored-line'), ], # ignored and regular whitespaces in quoted scalars 'quoted-scalar-whitespaces': [ # leading and trailing whitespaces are ignored (r'^[ ]+|[ ]+$', Text), # line breaks are ignored (r'\n+', Text), # other whitespaces are a part of the value (r'[ ]+', Name.Variable), ], # single-quoted scalars 'single-quoted-scalar': [ # include whitespace and line break rules include('quoted-scalar-whitespaces'), # escaping of the quote character (r'\'\'', String.Escape), # regular non-whitespace characters (r'[^ \t\n\r\f\v\']+', String), # the closing quote (r'\'', String, '#pop'), ], # double-quoted scalars 'double-quoted-scalar': [ # include whitespace and line break rules include('quoted-scalar-whitespaces'), # escaping of special characters (r'\\[0abt\tn\nvfre "\\N_LP]', String), # escape codes (r'\\(?:x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})', String.Escape), # regular non-whitespace characters (r'[^ \t\n\r\f\v\"\\]+', String), # the closing quote (r'"', String, '#pop'), ], # the beginning of a new line while scanning a plain scalar 'plain-scalar-in-block-context-new-line': [ # empty lines (r'^[ ]+$', Text), # line breaks (r'\n+', Text), # document start and document end indicators (r'^(?=---|\.\.\.)', something(Name.Namespace), '#pop:3'), # indentation spaces (we may leave the block line state here) (r'^[ ]*', parse_plain_scalar_indent(Text), '#pop'), ], # a plain scalar in the block context 'plain-scalar-in-block-context': [ # the scalar ends with the ':' indicator (r'[ ]*(?=:[ ]|:$)', something(Text), '#pop'), # the scalar ends with whitespaces followed by a comment (r'[ ]+(?=#)', Text, '#pop'), # trailing whitespaces are ignored (r'[ ]+$', Text), # line breaks are ignored (r'\n+', Text, 'plain-scalar-in-block-context-new-line'), # other whitespaces are a part of the value (r'[ ]+', Literal.Scalar.Plain), # regular non-whitespace characters (r'(?::(?![ \t\n\r\f\v])|[^ \t\n\r\f\v:])+', Literal.Scalar.Plain), ], # a plain scalar is the flow context 'plain-scalar-in-flow-context': [ # the scalar ends with an indicator character (r'[ ]*(?=[,:?\[\]{}])', something(Text), '#pop'), # the scalar ends with a comment (r'[ ]+(?=#)', Text, '#pop'), # leading and trailing whitespaces are ignored (r'^[ ]+|[ ]+$', Text), # line breaks are ignored (r'\n+', Text), # other whitespaces are a part of the value (r'[ ]+', Name.Variable), # regular non-whitespace characters (r'[^ \t\n\r\f\v,:?\[\]{}]+', Name.Variable), ], } def get_tokens_unprocessed(self, text=None, context=None): if context is None: context = YamlLexerContext(text, 0) return super(YamlLexer, self).get_tokens_unprocessed(text, context) class LighttpdConfLexer(RegexLexer): """ Lexer for `Lighttpd <http://lighttpd.net/>`_ configuration files. *New in Pygments 0.11.* """ name = 'Lighttpd configuration file' aliases = ['lighty', 'lighttpd'] filenames = [] mimetypes = ['text/x-lighttpd-conf'] tokens = { 'root': [ (r'#.*\n', Comment.Single), (r'/\S*', Name), # pathname (r'[a-zA-Z._-]+', Keyword), (r'\d+\.\d+\.\d+\.\d+(?:/\d+)?', Number), (r'[0-9]+', Number), (r'=>|=~|\+=|==|=|\+', Operator), (r'\$[A-Z]+', Name.Builtin), (r'[(){}\[\],]', Punctuation), (r'"([^"\\]*(?:\\.[^"\\]*)*)"', String.Double), (r'\s+', Text), ], } class NginxConfLexer(RegexLexer): """ Lexer for `Nginx <http://nginx.net/>`_ configuration files. *New in Pygments 0.11.* """ name = 'Nginx configuration file' aliases = ['nginx'] filenames = [] mimetypes = ['text/x-nginx-conf'] tokens = { 'root': [ (r'(include)(\s+)([^\s;]+)', bygroups(Keyword, Text, Name)), (r'[^\s;#]+', Keyword, 'stmt'), include('base'), ], 'block': [ (r'}', Punctuation, '#pop:2'), (r'[^\s;#]+', Keyword.Namespace, 'stmt'), include('base'), ], 'stmt': [ (r'{', Punctuation, 'block'), (r';', Punctuation, '#pop'), include('base'), ], 'base': [ (r'#.*\n', Comment.Single), (r'on|off', Name.Constant), (r'\$[^\s;#()]+', Name.Variable), (r'([a-z0-9.-]+)(:)([0-9]+)', bygroups(Name, Punctuation, Number.Integer)), (r'[a-z-]+/[a-z-+]+', String), # mimetype #(r'[a-zA-Z._-]+', Keyword), (r'[0-9]+[km]?\b', Number.Integer), (r'(~)(\s*)([^\s{]+)', bygroups(Punctuation, Text, String.Regex)), (r'[:=~]', Punctuation), (r'[^\s;#{}$]+', String), # catch all (r'/[^\s;#]*', Name), # pathname (r'\s+', Text), (r'[$;]', Text), # leftover characters ], } class CMakeLexer(RegexLexer): """ Lexer for `CMake <http://cmake.org/Wiki/CMake>`_ files. *New in Pygments 1.2.* """ name = 'CMake' aliases = ['cmake'] filenames = ['*.cmake'] mimetypes = ['text/x-cmake'] tokens = { 'root': [ #(r'(ADD_CUSTOM_COMMAND|ADD_CUSTOM_TARGET|ADD_DEFINITIONS|' # r'ADD_DEPENDENCIES|ADD_EXECUTABLE|ADD_LIBRARY|ADD_SUBDIRECTORY|' # r'ADD_TEST|AUX_SOURCE_DIRECTORY|BUILD_COMMAND|BUILD_NAME|' # r'CMAKE_MINIMUM_REQUIRED|CONFIGURE_FILE|CREATE_TEST_SOURCELIST|' # r'ELSE|ELSEIF|ENABLE_LANGUAGE|ENABLE_TESTING|ENDFOREACH|' # r'ENDFUNCTION|ENDIF|ENDMACRO|ENDWHILE|EXEC_PROGRAM|' # r'EXECUTE_PROCESS|EXPORT_LIBRARY_DEPENDENCIES|FILE|FIND_FILE|' # r'FIND_LIBRARY|FIND_PACKAGE|FIND_PATH|FIND_PROGRAM|FLTK_WRAP_UI|' # r'FOREACH|FUNCTION|GET_CMAKE_PROPERTY|GET_DIRECTORY_PROPERTY|' # r'GET_FILENAME_COMPONENT|GET_SOURCE_FILE_PROPERTY|' # r'GET_TARGET_PROPERTY|GET_TEST_PROPERTY|IF|INCLUDE|' # r'INCLUDE_DIRECTORIES|INCLUDE_EXTERNAL_MSPROJECT|' # r'INCLUDE_REGULAR_EXPRESSION|INSTALL|INSTALL_FILES|' # r'INSTALL_PROGRAMS|INSTALL_TARGETS|LINK_DIRECTORIES|' # r'LINK_LIBRARIES|LIST|LOAD_CACHE|LOAD_COMMAND|MACRO|' # r'MAKE_DIRECTORY|MARK_AS_ADVANCED|MATH|MESSAGE|OPTION|' # r'OUTPUT_REQUIRED_FILES|PROJECT|QT_WRAP_CPP|QT_WRAP_UI|REMOVE|' # r'REMOVE_DEFINITIONS|SEPARATE_ARGUMENTS|SET|' # r'SET_DIRECTORY_PROPERTIES|SET_SOURCE_FILES_PROPERTIES|' # r'SET_TARGET_PROPERTIES|SET_TESTS_PROPERTIES|SITE_NAME|' # r'SOURCE_GROUP|STRING|SUBDIR_DEPENDS|SUBDIRS|' # r'TARGET_LINK_LIBRARIES|TRY_COMPILE|TRY_RUN|UNSET|' # r'USE_MANGLED_MESA|UTILITY_SOURCE|VARIABLE_REQUIRES|' # r'VTK_MAKE_INSTANTIATOR|VTK_WRAP_JAVA|VTK_WRAP_PYTHON|' # r'VTK_WRAP_TCL|WHILE|WRITE_FILE|' # r'COUNTARGS)\b', Name.Builtin, 'args'), (r'\b([A-Za-z_]+)([ \t]*)(\()', bygroups(Name.Builtin, Text, Punctuation), 'args'), include('keywords'), include('ws') ], 'args': [ (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop'), (r'(\${)(.+?)(})', bygroups(Operator, Name.Variable, Operator)), (r'(?s)".*?"', String.Double), (r'\\\S+', String), (r'[^\)$"# \t\n]+', String), (r'\n', Text), # explicitly legal include('keywords'), include('ws') ], 'string': [ ], 'keywords': [ (r'\b(WIN32|UNIX|APPLE|CYGWIN|BORLAND|MINGW|MSVC|MSVC_IDE|MSVC60|' r'MSVC70|MSVC71|MSVC80|MSVC90)\b', Keyword), ], 'ws': [ (r'[ \t]+', Text), (r'#.+\n', Comment), ] }
ACOKing/ArcherVMPeridot
refs/heads/master
nodechip/node_modules/cordova/node_modules/cordova-lib/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py
64
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from compiler.ast import Const from compiler.ast import Dict from compiler.ast import Discard from compiler.ast import List from compiler.ast import Module from compiler.ast import Node from compiler.ast import Stmt import compiler import copy import gyp.common import multiprocessing import optparse import os.path import re import shlex import signal import subprocess import sys import threading import time from gyp.common import GypError # A list of types that are treated as linkable. linkable_types = ['executable', 'shared_library', 'loadable_module'] # A list of sections that contain links to other targets. dependency_sections = ['dependencies', 'export_dependent_settings'] # base_path_sections is a list of sections defined by GYP that contain # pathnames. The generators can provide more keys, the two lists are merged # into path_sections, but you should call IsPathSection instead of using either # list directly. base_path_sections = [ 'destination', 'files', 'include_dirs', 'inputs', 'libraries', 'outputs', 'sources', ] path_sections = [] is_path_section_charset = set('=+?!') is_path_section_match_re = re.compile('_(dir|file|path)s?$') def IsPathSection(section): # If section ends in one of these characters, it's applied to a section # without the trailing characters. '/' is notably absent from this list, # because there's no way for a regular expression to be treated as a path. while section[-1:] in is_path_section_charset: section = section[:-1] return section in path_sections or is_path_section_match_re.search(section) # base_non_configuraiton_keys is a list of key names that belong in the target # itself and should not be propagated into its configurations. It is merged # with a list that can come from the generator to # create non_configuration_keys. base_non_configuration_keys = [ # Sections that must exist inside targets and not configurations. 'actions', 'configurations', 'copies', 'default_configuration', 'dependencies', 'dependencies_original', 'link_languages', 'libraries', 'postbuilds', 'product_dir', 'product_extension', 'product_name', 'product_prefix', 'rules', 'run_as', 'sources', 'standalone_static_library', 'suppress_wildcard', 'target_name', 'toolset', 'toolsets', 'type', 'variants', # Sections that can be found inside targets or configurations, but that # should not be propagated from targets into their configurations. 'variables', ] non_configuration_keys = [] # Keys that do not belong inside a configuration dictionary. invalid_configuration_keys = [ 'actions', 'all_dependent_settings', 'configurations', 'dependencies', 'direct_dependent_settings', 'libraries', 'link_settings', 'sources', 'standalone_static_library', 'target_name', 'type', ] # Controls how the generator want the build file paths. absolute_build_file_paths = False # Controls whether or not the generator supports multiple toolsets. multiple_toolsets = False def GetIncludedBuildFiles(build_file_path, aux_data, included=None): """Return a list of all build files included into build_file_path. The returned list will contain build_file_path as well as all other files that it included, either directly or indirectly. Note that the list may contain files that were included into a conditional section that evaluated to false and was not merged into build_file_path's dict. aux_data is a dict containing a key for each build file or included build file. Those keys provide access to dicts whose "included" keys contain lists of all other files included by the build file. included should be left at its default None value by external callers. It is used for recursion. The returned list will not contain any duplicate entries. Each build file in the list will be relative to the current directory. """ if included == None: included = [] if build_file_path in included: return included included.append(build_file_path) for included_build_file in aux_data[build_file_path].get('included', []): GetIncludedBuildFiles(included_build_file, aux_data, included) return included def CheckedEval(file_contents): """Return the eval of a gyp file. The gyp file is restricted to dictionaries and lists only, and repeated keys are not allowed. Note that this is slower than eval() is. """ ast = compiler.parse(file_contents) assert isinstance(ast, Module) c1 = ast.getChildren() assert c1[0] is None assert isinstance(c1[1], Stmt) c2 = c1[1].getChildren() assert isinstance(c2[0], Discard) c3 = c2[0].getChildren() assert len(c3) == 1 return CheckNode(c3[0], []) def CheckNode(node, keypath): if isinstance(node, Dict): c = node.getChildren() dict = {} for n in range(0, len(c), 2): assert isinstance(c[n], Const) key = c[n].getChildren()[0] if key in dict: raise GypError("Key '" + key + "' repeated at level " + repr(len(keypath) + 1) + " with key path '" + '.'.join(keypath) + "'") kp = list(keypath) # Make a copy of the list for descending this node. kp.append(key) dict[key] = CheckNode(c[n + 1], kp) return dict elif isinstance(node, List): c = node.getChildren() children = [] for index, child in enumerate(c): kp = list(keypath) # Copy list. kp.append(repr(index)) children.append(CheckNode(child, kp)) return children elif isinstance(node, Const): return node.getChildren()[0] else: raise TypeError, "Unknown AST node at key path '" + '.'.join(keypath) + \ "': " + repr(node) def LoadOneBuildFile(build_file_path, data, aux_data, variables, includes, is_target, check): if build_file_path in data: return data[build_file_path] if os.path.exists(build_file_path): build_file_contents = open(build_file_path).read() else: raise GypError("%s not found (cwd: %s)" % (build_file_path, os.getcwd())) build_file_data = None try: if check: build_file_data = CheckedEval(build_file_contents) else: build_file_data = eval(build_file_contents, {'__builtins__': None}, None) except SyntaxError, e: e.filename = build_file_path raise except Exception, e: gyp.common.ExceptionAppend(e, 'while reading ' + build_file_path) raise data[build_file_path] = build_file_data aux_data[build_file_path] = {} # Scan for includes and merge them in. try: if is_target: LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data, aux_data, variables, includes, check) else: LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data, aux_data, variables, None, check) except Exception, e: gyp.common.ExceptionAppend(e, 'while reading includes of ' + build_file_path) raise return build_file_data def LoadBuildFileIncludesIntoDict(subdict, subdict_path, data, aux_data, variables, includes, check): includes_list = [] if includes != None: includes_list.extend(includes) if 'includes' in subdict: for include in subdict['includes']: # "include" is specified relative to subdict_path, so compute the real # path to include by appending the provided "include" to the directory # in which subdict_path resides. relative_include = \ os.path.normpath(os.path.join(os.path.dirname(subdict_path), include)) includes_list.append(relative_include) # Unhook the includes list, it's no longer needed. del subdict['includes'] # Merge in the included files. for include in includes_list: if not 'included' in aux_data[subdict_path]: aux_data[subdict_path]['included'] = [] aux_data[subdict_path]['included'].append(include) gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Included File: '%s'", include) MergeDicts(subdict, LoadOneBuildFile(include, data, aux_data, variables, None, False, check), subdict_path, include) # Recurse into subdictionaries. for k, v in subdict.iteritems(): if v.__class__ == dict: LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data, variables, None, check) elif v.__class__ == list: LoadBuildFileIncludesIntoList(v, subdict_path, data, aux_data, variables, check) # This recurses into lists so that it can look for dicts. def LoadBuildFileIncludesIntoList(sublist, sublist_path, data, aux_data, variables, check): for item in sublist: if item.__class__ == dict: LoadBuildFileIncludesIntoDict(item, sublist_path, data, aux_data, variables, None, check) elif item.__class__ == list: LoadBuildFileIncludesIntoList(item, sublist_path, data, aux_data, variables, check) # Processes toolsets in all the targets. This recurses into condition entries # since they can contain toolsets as well. def ProcessToolsetsInDict(data): if 'targets' in data: target_list = data['targets'] new_target_list = [] for target in target_list: # If this target already has an explicit 'toolset', and no 'toolsets' # list, don't modify it further. if 'toolset' in target and 'toolsets' not in target: new_target_list.append(target) continue if multiple_toolsets: toolsets = target.get('toolsets', ['target']) else: toolsets = ['target'] # Make sure this 'toolsets' definition is only processed once. if 'toolsets' in target: del target['toolsets'] if len(toolsets) > 0: # Optimization: only do copies if more than one toolset is specified. for build in toolsets[1:]: new_target = copy.deepcopy(target) new_target['toolset'] = build new_target_list.append(new_target) target['toolset'] = toolsets[0] new_target_list.append(target) data['targets'] = new_target_list if 'conditions' in data: for condition in data['conditions']: if isinstance(condition, list): for condition_dict in condition[1:]: ProcessToolsetsInDict(condition_dict) # TODO(mark): I don't love this name. It just means that it's going to load # a build file that contains targets and is expected to provide a targets dict # that contains the targets... def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes, depth, check, load_dependencies): # If depth is set, predefine the DEPTH variable to be a relative path from # this build file's directory to the directory identified by depth. if depth: # TODO(dglazkov) The backslash/forward-slash replacement at the end is a # temporary measure. This should really be addressed by keeping all paths # in POSIX until actual project generation. d = gyp.common.RelativePath(depth, os.path.dirname(build_file_path)) if d == '': variables['DEPTH'] = '.' else: variables['DEPTH'] = d.replace('\\', '/') # If the generator needs absolue paths, then do so. if absolute_build_file_paths: build_file_path = os.path.abspath(build_file_path) if build_file_path in data['target_build_files']: # Already loaded. return False data['target_build_files'].add(build_file_path) gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Target Build File '%s'", build_file_path) build_file_data = LoadOneBuildFile(build_file_path, data, aux_data, variables, includes, True, check) # Store DEPTH for later use in generators. build_file_data['_DEPTH'] = depth # Set up the included_files key indicating which .gyp files contributed to # this target dict. if 'included_files' in build_file_data: raise GypError(build_file_path + ' must not contain included_files key') included = GetIncludedBuildFiles(build_file_path, aux_data) build_file_data['included_files'] = [] for included_file in included: # included_file is relative to the current directory, but it needs to # be made relative to build_file_path's directory. included_relative = \ gyp.common.RelativePath(included_file, os.path.dirname(build_file_path)) build_file_data['included_files'].append(included_relative) # Do a first round of toolsets expansion so that conditions can be defined # per toolset. ProcessToolsetsInDict(build_file_data) # Apply "pre"/"early" variable expansions and condition evaluations. ProcessVariablesAndConditionsInDict( build_file_data, PHASE_EARLY, variables, build_file_path) # Since some toolsets might have been defined conditionally, perform # a second round of toolsets expansion now. ProcessToolsetsInDict(build_file_data) # Look at each project's target_defaults dict, and merge settings into # targets. if 'target_defaults' in build_file_data: if 'targets' not in build_file_data: raise GypError("Unable to find targets in build file %s" % build_file_path) index = 0 while index < len(build_file_data['targets']): # This procedure needs to give the impression that target_defaults is # used as defaults, and the individual targets inherit from that. # The individual targets need to be merged into the defaults. Make # a deep copy of the defaults for each target, merge the target dict # as found in the input file into that copy, and then hook up the # copy with the target-specific data merged into it as the replacement # target dict. old_target_dict = build_file_data['targets'][index] new_target_dict = copy.deepcopy(build_file_data['target_defaults']) MergeDicts(new_target_dict, old_target_dict, build_file_path, build_file_path) build_file_data['targets'][index] = new_target_dict index += 1 # No longer needed. del build_file_data['target_defaults'] # Look for dependencies. This means that dependency resolution occurs # after "pre" conditionals and variable expansion, but before "post" - # in other words, you can't put a "dependencies" section inside a "post" # conditional within a target. dependencies = [] if 'targets' in build_file_data: for target_dict in build_file_data['targets']: if 'dependencies' not in target_dict: continue for dependency in target_dict['dependencies']: dependencies.append( gyp.common.ResolveTarget(build_file_path, dependency, None)[0]) if load_dependencies: for dependency in dependencies: try: LoadTargetBuildFile(dependency, data, aux_data, variables, includes, depth, check, load_dependencies) except Exception, e: gyp.common.ExceptionAppend( e, 'while loading dependencies of %s' % build_file_path) raise else: return (build_file_path, dependencies) def CallLoadTargetBuildFile(global_flags, build_file_path, data, aux_data, variables, includes, depth, check): """Wrapper around LoadTargetBuildFile for parallel processing. This wrapper is used when LoadTargetBuildFile is executed in a worker process. """ try: signal.signal(signal.SIGINT, signal.SIG_IGN) # Apply globals so that the worker process behaves the same. for key, value in global_flags.iteritems(): globals()[key] = value # Save the keys so we can return data that changed. data_keys = set(data) aux_data_keys = set(aux_data) result = LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes, depth, check, False) if not result: return result (build_file_path, dependencies) = result data_out = {} for key in data: if key == 'target_build_files': continue if key not in data_keys: data_out[key] = data[key] aux_data_out = {} for key in aux_data: if key not in aux_data_keys: aux_data_out[key] = aux_data[key] # This gets serialized and sent back to the main process via a pipe. # It's handled in LoadTargetBuildFileCallback. return (build_file_path, data_out, aux_data_out, dependencies) except Exception, e: print >>sys.stderr, 'Exception: ', e return None class ParallelProcessingError(Exception): pass class ParallelState(object): """Class to keep track of state when processing input files in parallel. If build files are loaded in parallel, use this to keep track of state during farming out and processing parallel jobs. It's stored in a global so that the callback function can have access to it. """ def __init__(self): # The multiprocessing pool. self.pool = None # The condition variable used to protect this object and notify # the main loop when there might be more data to process. self.condition = None # The "data" dict that was passed to LoadTargetBuildFileParallel self.data = None # The "aux_data" dict that was passed to LoadTargetBuildFileParallel self.aux_data = None # The number of parallel calls outstanding; decremented when a response # was received. self.pending = 0 # The set of all build files that have been scheduled, so we don't # schedule the same one twice. self.scheduled = set() # A list of dependency build file paths that haven't been scheduled yet. self.dependencies = [] # Flag to indicate if there was an error in a child process. self.error = False def LoadTargetBuildFileCallback(self, result): """Handle the results of running LoadTargetBuildFile in another process. """ self.condition.acquire() if not result: self.error = True self.condition.notify() self.condition.release() return (build_file_path0, data0, aux_data0, dependencies0) = result self.data['target_build_files'].add(build_file_path0) for key in data0: self.data[key] = data0[key] for key in aux_data0: self.aux_data[key] = aux_data0[key] for new_dependency in dependencies0: if new_dependency not in self.scheduled: self.scheduled.add(new_dependency) self.dependencies.append(new_dependency) self.pending -= 1 self.condition.notify() self.condition.release() def LoadTargetBuildFileParallel(build_file_path, data, aux_data, variables, includes, depth, check): parallel_state = ParallelState() parallel_state.condition = threading.Condition() parallel_state.dependencies = [build_file_path] parallel_state.scheduled = set([build_file_path]) parallel_state.pending = 0 parallel_state.data = data parallel_state.aux_data = aux_data try: parallel_state.condition.acquire() while parallel_state.dependencies or parallel_state.pending: if parallel_state.error: print >>sys.stderr, ( '\n' 'Note: an error occurred while running gyp using multiprocessing.\n' 'For more verbose output, set GYP_PARALLEL=0 in your environment.\n' 'If the error only occurs when GYP_PARALLEL=1, ' 'please report a bug!') break if not parallel_state.dependencies: parallel_state.condition.wait() continue dependency = parallel_state.dependencies.pop() parallel_state.pending += 1 data_in = {} data_in['target_build_files'] = data['target_build_files'] aux_data_in = {} global_flags = { 'path_sections': globals()['path_sections'], 'non_configuration_keys': globals()['non_configuration_keys'], 'absolute_build_file_paths': globals()['absolute_build_file_paths'], 'multiple_toolsets': globals()['multiple_toolsets']} if not parallel_state.pool: parallel_state.pool = multiprocessing.Pool(8) parallel_state.pool.apply_async( CallLoadTargetBuildFile, args = (global_flags, dependency, data_in, aux_data_in, variables, includes, depth, check), callback = parallel_state.LoadTargetBuildFileCallback) except KeyboardInterrupt, e: parallel_state.pool.terminate() raise e parallel_state.condition.release() if parallel_state.error: sys.exit() # Look for the bracket that matches the first bracket seen in a # string, and return the start and end as a tuple. For example, if # the input is something like "<(foo <(bar)) blah", then it would # return (1, 13), indicating the entire string except for the leading # "<" and trailing " blah". LBRACKETS= set('{[(') BRACKETS = {'}': '{', ']': '[', ')': '('} def FindEnclosingBracketGroup(input_str): stack = [] start = -1 for index, char in enumerate(input_str): if char in LBRACKETS: stack.append(char) if start == -1: start = index elif char in BRACKETS: if not stack: return (-1, -1) if stack.pop() != BRACKETS[char]: return (-1, -1) if not stack: return (start, index + 1) return (-1, -1) canonical_int_re = re.compile('(0|-?[1-9][0-9]*)$') def IsStrCanonicalInt(string): """Returns True if |string| is in its canonical integer form. The canonical form is such that str(int(string)) == string. """ return isinstance(string, str) and canonical_int_re.match(string) # This matches things like "<(asdf)", "<!(cmd)", "<!@(cmd)", "<|(list)", # "<!interpreter(arguments)", "<([list])", and even "<([)" and "<(<())". # In the last case, the inner "<()" is captured in match['content']. early_variable_re = re.compile( '(?P<replace>(?P<type><(?:(?:!?@?)|\|)?)' '(?P<command_string>[-a-zA-Z0-9_.]+)?' '\((?P<is_array>\s*\[?)' '(?P<content>.*?)(\]?)\))') # This matches the same as early_variable_re, but with '>' instead of '<'. late_variable_re = re.compile( '(?P<replace>(?P<type>>(?:(?:!?@?)|\|)?)' '(?P<command_string>[-a-zA-Z0-9_.]+)?' '\((?P<is_array>\s*\[?)' '(?P<content>.*?)(\]?)\))') # This matches the same as early_variable_re, but with '^' instead of '<'. latelate_variable_re = re.compile( '(?P<replace>(?P<type>[\^](?:(?:!?@?)|\|)?)' '(?P<command_string>[-a-zA-Z0-9_.]+)?' '\((?P<is_array>\s*\[?)' '(?P<content>.*?)(\]?)\))') # Global cache of results from running commands so they don't have to be run # more then once. cached_command_results = {} def FixupPlatformCommand(cmd): if sys.platform == 'win32': if type(cmd) == list: cmd = [re.sub('^cat ', 'type ', cmd[0])] + cmd[1:] else: cmd = re.sub('^cat ', 'type ', cmd) return cmd PHASE_EARLY = 0 PHASE_LATE = 1 PHASE_LATELATE = 2 def ExpandVariables(input, phase, variables, build_file): # Look for the pattern that gets expanded into variables if phase == PHASE_EARLY: variable_re = early_variable_re expansion_symbol = '<' elif phase == PHASE_LATE: variable_re = late_variable_re expansion_symbol = '>' elif phase == PHASE_LATELATE: variable_re = latelate_variable_re expansion_symbol = '^' else: assert False input_str = str(input) if IsStrCanonicalInt(input_str): return int(input_str) # Do a quick scan to determine if an expensive regex search is warranted. if expansion_symbol not in input_str: return input_str # Get the entire list of matches as a list of MatchObject instances. # (using findall here would return strings instead of MatchObjects). matches = list(variable_re.finditer(input_str)) if not matches: return input_str output = input_str # Reverse the list of matches so that replacements are done right-to-left. # That ensures that earlier replacements won't mess up the string in a # way that causes later calls to find the earlier substituted text instead # of what's intended for replacement. matches.reverse() for match_group in matches: match = match_group.groupdict() gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Matches: %r", match) # match['replace'] is the substring to look for, match['type'] # is the character code for the replacement type (< > <! >! <| >| <@ # >@ <!@ >!@), match['is_array'] contains a '[' for command # arrays, and match['content'] is the name of the variable (< >) # or command to run (<! >!). match['command_string'] is an optional # command string. Currently, only 'pymod_do_main' is supported. # run_command is true if a ! variant is used. run_command = '!' in match['type'] command_string = match['command_string'] # file_list is true if a | variant is used. file_list = '|' in match['type'] # Capture these now so we can adjust them later. replace_start = match_group.start('replace') replace_end = match_group.end('replace') # Find the ending paren, and re-evaluate the contained string. (c_start, c_end) = FindEnclosingBracketGroup(input_str[replace_start:]) # Adjust the replacement range to match the entire command # found by FindEnclosingBracketGroup (since the variable_re # probably doesn't match the entire command if it contained # nested variables). replace_end = replace_start + c_end # Find the "real" replacement, matching the appropriate closing # paren, and adjust the replacement start and end. replacement = input_str[replace_start:replace_end] # Figure out what the contents of the variable parens are. contents_start = replace_start + c_start + 1 contents_end = replace_end - 1 contents = input_str[contents_start:contents_end] # Do filter substitution now for <|(). # Admittedly, this is different than the evaluation order in other # contexts. However, since filtration has no chance to run on <|(), # this seems like the only obvious way to give them access to filters. if file_list: processed_variables = copy.deepcopy(variables) ProcessListFiltersInDict(contents, processed_variables) # Recurse to expand variables in the contents contents = ExpandVariables(contents, phase, processed_variables, build_file) else: # Recurse to expand variables in the contents contents = ExpandVariables(contents, phase, variables, build_file) # Strip off leading/trailing whitespace so that variable matches are # simpler below (and because they are rarely needed). contents = contents.strip() # expand_to_list is true if an @ variant is used. In that case, # the expansion should result in a list. Note that the caller # is to be expecting a list in return, and not all callers do # because not all are working in list context. Also, for list # expansions, there can be no other text besides the variable # expansion in the input string. expand_to_list = '@' in match['type'] and input_str == replacement if run_command or file_list: # Find the build file's directory, so commands can be run or file lists # generated relative to it. build_file_dir = os.path.dirname(build_file) if build_file_dir == '': # If build_file is just a leaf filename indicating a file in the # current directory, build_file_dir might be an empty string. Set # it to None to signal to subprocess.Popen that it should run the # command in the current directory. build_file_dir = None # Support <|(listfile.txt ...) which generates a file # containing items from a gyp list, generated at gyp time. # This works around actions/rules which have more inputs than will # fit on the command line. if file_list: if type(contents) == list: contents_list = contents else: contents_list = contents.split(' ') replacement = contents_list[0] path = replacement if not os.path.isabs(path): path = os.path.join(build_file_dir, path) f = gyp.common.WriteOnDiff(path) for i in contents_list[1:]: f.write('%s\n' % i) f.close() elif run_command: use_shell = True if match['is_array']: contents = eval(contents) use_shell = False # Check for a cached value to avoid executing commands, or generating # file lists more than once. # TODO(http://code.google.com/p/gyp/issues/detail?id=112): It is # possible that the command being invoked depends on the current # directory. For that case the syntax needs to be extended so that the # directory is also used in cache_key (it becomes a tuple). # TODO(http://code.google.com/p/gyp/issues/detail?id=111): In theory, # someone could author a set of GYP files where each time the command # is invoked it produces different output by design. When the need # arises, the syntax should be extended to support no caching off a # command's output so it is run every time. cache_key = str(contents) cached_value = cached_command_results.get(cache_key, None) if cached_value is None: gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Executing command '%s' in directory '%s'", contents, build_file_dir) replacement = '' if command_string == 'pymod_do_main': # <!pymod_do_main(modulename param eters) loads |modulename| as a # python module and then calls that module's DoMain() function, # passing ["param", "eters"] as a single list argument. For modules # that don't load quickly, this can be faster than # <!(python modulename param eters). Do this in |build_file_dir|. oldwd = os.getcwd() # Python doesn't like os.open('.'): no fchdir. os.chdir(build_file_dir) try: parsed_contents = shlex.split(contents) try: py_module = __import__(parsed_contents[0]) except ImportError as e: raise GypError("Error importing pymod_do_main" "module (%s): %s" % (parsed_contents[0], e)) replacement = str(py_module.DoMain(parsed_contents[1:])).rstrip() finally: os.chdir(oldwd) assert replacement != None elif command_string: raise GypError("Unknown command string '%s' in '%s'." % (command_string, contents)) else: # Fix up command with platform specific workarounds. contents = FixupPlatformCommand(contents) p = subprocess.Popen(contents, shell=use_shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, cwd=build_file_dir) p_stdout, p_stderr = p.communicate('') if p.wait() != 0 or p_stderr: sys.stderr.write(p_stderr) # Simulate check_call behavior, since check_call only exists # in python 2.5 and later. raise GypError("Call to '%s' returned exit status %d." % (contents, p.returncode)) replacement = p_stdout.rstrip() cached_command_results[cache_key] = replacement else: gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Had cache value for command '%s' in directory '%s'", contents,build_file_dir) replacement = cached_value else: if not contents in variables: if contents[-1] in ['!', '/']: # In order to allow cross-compiles (nacl) to happen more naturally, # we will allow references to >(sources/) etc. to resolve to # and empty list if undefined. This allows actions to: # 'action!': [ # '>@(_sources!)', # ], # 'action/': [ # '>@(_sources/)', # ], replacement = [] else: raise GypError('Undefined variable ' + contents + ' in ' + build_file) else: replacement = variables[contents] if isinstance(replacement, list): for item in replacement: if (not contents[-1] == '/' and not isinstance(item, str) and not isinstance(item, int)): raise GypError('Variable ' + contents + ' must expand to a string or list of strings; ' + 'list contains a ' + item.__class__.__name__) # Run through the list and handle variable expansions in it. Since # the list is guaranteed not to contain dicts, this won't do anything # with conditions sections. ProcessVariablesAndConditionsInList(replacement, phase, variables, build_file) elif not isinstance(replacement, str) and \ not isinstance(replacement, int): raise GypError('Variable ' + contents + ' must expand to a string or list of strings; ' + 'found a ' + replacement.__class__.__name__) if expand_to_list: # Expanding in list context. It's guaranteed that there's only one # replacement to do in |input_str| and that it's this replacement. See # above. if isinstance(replacement, list): # If it's already a list, make a copy. output = replacement[:] else: # Split it the same way sh would split arguments. output = shlex.split(str(replacement)) else: # Expanding in string context. encoded_replacement = '' if isinstance(replacement, list): # When expanding a list into string context, turn the list items # into a string in a way that will work with a subprocess call. # # TODO(mark): This isn't completely correct. This should # call a generator-provided function that observes the # proper list-to-argument quoting rules on a specific # platform instead of just calling the POSIX encoding # routine. encoded_replacement = gyp.common.EncodePOSIXShellList(replacement) else: encoded_replacement = replacement output = output[:replace_start] + str(encoded_replacement) + \ output[replace_end:] # Prepare for the next match iteration. input_str = output # Look for more matches now that we've replaced some, to deal with # expanding local variables (variables defined in the same # variables block as this one). gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Found output %r, recursing.", output) if isinstance(output, list): if output and isinstance(output[0], list): # Leave output alone if it's a list of lists. # We don't want such lists to be stringified. pass else: new_output = [] for item in output: new_output.append( ExpandVariables(item, phase, variables, build_file)) output = new_output else: output = ExpandVariables(output, phase, variables, build_file) # Convert all strings that are canonically-represented integers into integers. if isinstance(output, list): for index in xrange(0, len(output)): if IsStrCanonicalInt(output[index]): output[index] = int(output[index]) elif IsStrCanonicalInt(output): output = int(output) return output def ProcessConditionsInDict(the_dict, phase, variables, build_file): # Process a 'conditions' or 'target_conditions' section in the_dict, # depending on phase. # early -> conditions # late -> target_conditions # latelate -> no conditions # # Each item in a conditions list consists of cond_expr, a string expression # evaluated as the condition, and true_dict, a dict that will be merged into # the_dict if cond_expr evaluates to true. Optionally, a third item, # false_dict, may be present. false_dict is merged into the_dict if # cond_expr evaluates to false. # # Any dict merged into the_dict will be recursively processed for nested # conditionals and other expansions, also according to phase, immediately # prior to being merged. if phase == PHASE_EARLY: conditions_key = 'conditions' elif phase == PHASE_LATE: conditions_key = 'target_conditions' elif phase == PHASE_LATELATE: return else: assert False if not conditions_key in the_dict: return conditions_list = the_dict[conditions_key] # Unhook the conditions list, it's no longer needed. del the_dict[conditions_key] for condition in conditions_list: if not isinstance(condition, list): raise GypError(conditions_key + ' must be a list') if len(condition) != 2 and len(condition) != 3: # It's possible that condition[0] won't work in which case this # attempt will raise its own IndexError. That's probably fine. raise GypError(conditions_key + ' ' + condition[0] + ' must be length 2 or 3, not ' + str(len(condition))) [cond_expr, true_dict] = condition[0:2] false_dict = None if len(condition) == 3: false_dict = condition[2] # Do expansions on the condition itself. Since the conditon can naturally # contain variable references without needing to resort to GYP expansion # syntax, this is of dubious value for variables, but someone might want to # use a command expansion directly inside a condition. cond_expr_expanded = ExpandVariables(cond_expr, phase, variables, build_file) if not isinstance(cond_expr_expanded, str) and \ not isinstance(cond_expr_expanded, int): raise ValueError, \ 'Variable expansion in this context permits str and int ' + \ 'only, found ' + expanded.__class__.__name__ try: ast_code = compile(cond_expr_expanded, '<string>', 'eval') if eval(ast_code, {'__builtins__': None}, variables): merge_dict = true_dict else: merge_dict = false_dict except SyntaxError, e: syntax_error = SyntaxError('%s while evaluating condition \'%s\' in %s ' 'at character %d.' % (str(e.args[0]), e.text, build_file, e.offset), e.filename, e.lineno, e.offset, e.text) raise syntax_error except NameError, e: gyp.common.ExceptionAppend(e, 'while evaluating condition \'%s\' in %s' % (cond_expr_expanded, build_file)) raise GypError(e) if merge_dict != None: # Expand variables and nested conditinals in the merge_dict before # merging it. ProcessVariablesAndConditionsInDict(merge_dict, phase, variables, build_file) MergeDicts(the_dict, merge_dict, build_file, build_file) def LoadAutomaticVariablesFromDict(variables, the_dict): # Any keys with plain string values in the_dict become automatic variables. # The variable name is the key name with a "_" character prepended. for key, value in the_dict.iteritems(): if isinstance(value, str) or isinstance(value, int) or \ isinstance(value, list): variables['_' + key] = value def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key): # Any keys in the_dict's "variables" dict, if it has one, becomes a # variable. The variable name is the key name in the "variables" dict. # Variables that end with the % character are set only if they are unset in # the variables dict. the_dict_key is the name of the key that accesses # the_dict in the_dict's parent dict. If the_dict's parent is not a dict # (it could be a list or it could be parentless because it is a root dict), # the_dict_key will be None. for key, value in the_dict.get('variables', {}).iteritems(): if not isinstance(value, str) and not isinstance(value, int) and \ not isinstance(value, list): continue if key.endswith('%'): variable_name = key[:-1] if variable_name in variables: # If the variable is already set, don't set it. continue if the_dict_key is 'variables' and variable_name in the_dict: # If the variable is set without a % in the_dict, and the_dict is a # variables dict (making |variables| a varaibles sub-dict of a # variables dict), use the_dict's definition. value = the_dict[variable_name] else: variable_name = key variables[variable_name] = value def ProcessVariablesAndConditionsInDict(the_dict, phase, variables_in, build_file, the_dict_key=None): """Handle all variable and command expansion and conditional evaluation. This function is the public entry point for all variable expansions and conditional evaluations. The variables_in dictionary will not be modified by this function. """ # Make a copy of the variables_in dict that can be modified during the # loading of automatics and the loading of the variables dict. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) if 'variables' in the_dict: # Make sure all the local variables are added to the variables # list before we process them so that you can reference one # variable from another. They will be fully expanded by recursion # in ExpandVariables. for key, value in the_dict['variables'].iteritems(): variables[key] = value # Handle the associated variables dict first, so that any variable # references within can be resolved prior to using them as variables. # Pass a copy of the variables dict to avoid having it be tainted. # Otherwise, it would have extra automatics added for everything that # should just be an ordinary variable in this scope. ProcessVariablesAndConditionsInDict(the_dict['variables'], phase, variables, build_file, 'variables') LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) for key, value in the_dict.iteritems(): # Skip "variables", which was already processed if present. if key != 'variables' and isinstance(value, str): expanded = ExpandVariables(value, phase, variables, build_file) if not isinstance(expanded, str) and not isinstance(expanded, int): raise ValueError, \ 'Variable expansion in this context permits str and int ' + \ 'only, found ' + expanded.__class__.__name__ + ' for ' + key the_dict[key] = expanded # Variable expansion may have resulted in changes to automatics. Reload. # TODO(mark): Optimization: only reload if no changes were made. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Process conditions in this dict. This is done after variable expansion # so that conditions may take advantage of expanded variables. For example, # if the_dict contains: # {'type': '<(library_type)', # 'conditions': [['_type=="static_library"', { ... }]]}, # _type, as used in the condition, will only be set to the value of # library_type if variable expansion is performed before condition # processing. However, condition processing should occur prior to recursion # so that variables (both automatic and "variables" dict type) may be # adjusted by conditions sections, merged into the_dict, and have the # intended impact on contained dicts. # # This arrangement means that a "conditions" section containing a "variables" # section will only have those variables effective in subdicts, not in # the_dict. The workaround is to put a "conditions" section within a # "variables" section. For example: # {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]], # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will not result in "IS_MAC" being appended to the "defines" list in the # current scope but would result in it being appended to the "defines" list # within "my_subdict". By comparison: # {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]}, # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will append "IS_MAC" to both "defines" lists. # Evaluate conditions sections, allowing variable expansions within them # as well as nested conditionals. This will process a 'conditions' or # 'target_conditions' section, perform appropriate merging and recursive # conditional and variable processing, and then remove the conditions section # from the_dict if it is present. ProcessConditionsInDict(the_dict, phase, variables, build_file) # Conditional processing may have resulted in changes to automatics or the # variables dict. Reload. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Recurse into child dicts, or process child lists which may result in # further recursion into descendant dicts. for key, value in the_dict.iteritems(): # Skip "variables" and string values, which were already processed if # present. if key == 'variables' or isinstance(value, str): continue if isinstance(value, dict): # Pass a copy of the variables dict so that subdicts can't influence # parents. ProcessVariablesAndConditionsInDict(value, phase, variables, build_file, key) elif isinstance(value, list): # The list itself can't influence the variables dict, and # ProcessVariablesAndConditionsInList will make copies of the variables # dict if it needs to pass it to something that can influence it. No # copy is necessary here. ProcessVariablesAndConditionsInList(value, phase, variables, build_file) elif not isinstance(value, int): raise TypeError, 'Unknown type ' + value.__class__.__name__ + \ ' for ' + key def ProcessVariablesAndConditionsInList(the_list, phase, variables, build_file): # Iterate using an index so that new values can be assigned into the_list. index = 0 while index < len(the_list): item = the_list[index] if isinstance(item, dict): # Make a copy of the variables dict so that it won't influence anything # outside of its own scope. ProcessVariablesAndConditionsInDict(item, phase, variables, build_file) elif isinstance(item, list): ProcessVariablesAndConditionsInList(item, phase, variables, build_file) elif isinstance(item, str): expanded = ExpandVariables(item, phase, variables, build_file) if isinstance(expanded, str) or isinstance(expanded, int): the_list[index] = expanded elif isinstance(expanded, list): the_list[index:index+1] = expanded index += len(expanded) # index now identifies the next item to examine. Continue right now # without falling into the index increment below. continue else: raise ValueError, \ 'Variable expansion in this context permits strings and ' + \ 'lists only, found ' + expanded.__class__.__name__ + ' at ' + \ index elif not isinstance(item, int): raise TypeError, 'Unknown type ' + item.__class__.__name__ + \ ' at index ' + index index = index + 1 def BuildTargetsDict(data): """Builds a dict mapping fully-qualified target names to their target dicts. |data| is a dict mapping loaded build files by pathname relative to the current directory. Values in |data| are build file contents. For each |data| value with a "targets" key, the value of the "targets" key is taken as a list containing target dicts. Each target's fully-qualified name is constructed from the pathname of the build file (|data| key) and its "target_name" property. These fully-qualified names are used as the keys in the returned dict. These keys provide access to the target dicts, the dicts in the "targets" lists. """ targets = {} for build_file in data['target_build_files']: for target in data[build_file].get('targets', []): target_name = gyp.common.QualifiedTarget(build_file, target['target_name'], target['toolset']) if target_name in targets: raise GypError('Duplicate target definitions for ' + target_name) targets[target_name] = target return targets def QualifyDependencies(targets): """Make dependency links fully-qualified relative to the current directory. |targets| is a dict mapping fully-qualified target names to their target dicts. For each target in this dict, keys known to contain dependency links are examined, and any dependencies referenced will be rewritten so that they are fully-qualified and relative to the current directory. All rewritten dependencies are suitable for use as keys to |targets| or a similar dict. """ all_dependency_sections = [dep + op for dep in dependency_sections for op in ('', '!', '/')] for target, target_dict in targets.iteritems(): target_build_file = gyp.common.BuildFile(target) toolset = target_dict['toolset'] for dependency_key in all_dependency_sections: dependencies = target_dict.get(dependency_key, []) for index in xrange(0, len(dependencies)): dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget( target_build_file, dependencies[index], toolset) if not multiple_toolsets: # Ignore toolset specification in the dependency if it is specified. dep_toolset = toolset dependency = gyp.common.QualifiedTarget(dep_file, dep_target, dep_toolset) dependencies[index] = dependency # Make sure anything appearing in a list other than "dependencies" also # appears in the "dependencies" list. if dependency_key != 'dependencies' and \ dependency not in target_dict['dependencies']: raise GypError('Found ' + dependency + ' in ' + dependency_key + ' of ' + target + ', but not in dependencies') def ExpandWildcardDependencies(targets, data): """Expands dependencies specified as build_file:*. For each target in |targets|, examines sections containing links to other targets. If any such section contains a link of the form build_file:*, it is taken as a wildcard link, and is expanded to list each target in build_file. The |data| dict provides access to build file dicts. Any target that does not wish to be included by wildcard can provide an optional "suppress_wildcard" key in its target dict. When present and true, a wildcard dependency link will not include such targets. All dependency names, including the keys to |targets| and the values in each dependency list, must be qualified when this function is called. """ for target, target_dict in targets.iteritems(): toolset = target_dict['toolset'] target_build_file = gyp.common.BuildFile(target) for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) # Loop this way instead of "for dependency in" or "for index in xrange" # because the dependencies list will be modified within the loop body. index = 0 while index < len(dependencies): (dependency_build_file, dependency_target, dependency_toolset) = \ gyp.common.ParseQualifiedTarget(dependencies[index]) if dependency_target != '*' and dependency_toolset != '*': # Not a wildcard. Keep it moving. index = index + 1 continue if dependency_build_file == target_build_file: # It's an error for a target to depend on all other targets in # the same file, because a target cannot depend on itself. raise GypError('Found wildcard in ' + dependency_key + ' of ' + target + ' referring to same build file') # Take the wildcard out and adjust the index so that the next # dependency in the list will be processed the next time through the # loop. del dependencies[index] index = index - 1 # Loop through the targets in the other build file, adding them to # this target's list of dependencies in place of the removed # wildcard. dependency_target_dicts = data[dependency_build_file]['targets'] for dependency_target_dict in dependency_target_dicts: if int(dependency_target_dict.get('suppress_wildcard', False)): continue dependency_target_name = dependency_target_dict['target_name'] if (dependency_target != '*' and dependency_target != dependency_target_name): continue dependency_target_toolset = dependency_target_dict['toolset'] if (dependency_toolset != '*' and dependency_toolset != dependency_target_toolset): continue dependency = gyp.common.QualifiedTarget(dependency_build_file, dependency_target_name, dependency_target_toolset) index = index + 1 dependencies.insert(index, dependency) index = index + 1 def Unify(l): """Removes duplicate elements from l, keeping the first element.""" seen = {} return [seen.setdefault(e, e) for e in l if e not in seen] def RemoveDuplicateDependencies(targets): """Makes sure every dependency appears only once in all targets's dependency lists.""" for target_name, target_dict in targets.iteritems(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: target_dict[dependency_key] = Unify(dependencies) def Filter(l, item): """Removes item from l.""" res = {} return [res.setdefault(e, e) for e in l if e != item] def RemoveSelfDependencies(targets): """Remove self dependencies from targets that have the prune_self_dependency variable set.""" for target_name, target_dict in targets.iteritems(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: for t in dependencies: if t == target_name: if targets[t].get('variables', {}).get('prune_self_dependency', 0): target_dict[dependency_key] = Filter(dependencies, target_name) class DependencyGraphNode(object): """ Attributes: ref: A reference to an object that this DependencyGraphNode represents. dependencies: List of DependencyGraphNodes on which this one depends. dependents: List of DependencyGraphNodes that depend on this one. """ class CircularException(GypError): pass def __init__(self, ref): self.ref = ref self.dependencies = [] self.dependents = [] def FlattenToList(self): # flat_list is the sorted list of dependencies - actually, the list items # are the "ref" attributes of DependencyGraphNodes. Every target will # appear in flat_list after all of its dependencies, and before all of its # dependents. flat_list = [] # in_degree_zeros is the list of DependencyGraphNodes that have no # dependencies not in flat_list. Initially, it is a copy of the children # of this node, because when the graph was built, nodes with no # dependencies were made implicit dependents of the root node. in_degree_zeros = set(self.dependents[:]) while in_degree_zeros: # Nodes in in_degree_zeros have no dependencies not in flat_list, so they # can be appended to flat_list. Take these nodes out of in_degree_zeros # as work progresses, so that the next node to process from the list can # always be accessed at a consistent position. node = in_degree_zeros.pop() flat_list.append(node.ref) # Look at dependents of the node just added to flat_list. Some of them # may now belong in in_degree_zeros. for node_dependent in node.dependents: is_in_degree_zero = True for node_dependent_dependency in node_dependent.dependencies: if not node_dependent_dependency.ref in flat_list: # The dependent one or more dependencies not in flat_list. There # will be more chances to add it to flat_list when examining # it again as a dependent of those other dependencies, provided # that there are no cycles. is_in_degree_zero = False break if is_in_degree_zero: # All of the dependent's dependencies are already in flat_list. Add # it to in_degree_zeros where it will be processed in a future # iteration of the outer loop. in_degree_zeros.add(node_dependent) return flat_list def DirectDependencies(self, dependencies=None): """Returns a list of just direct dependencies.""" if dependencies == None: dependencies = [] for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref != None and dependency.ref not in dependencies: dependencies.append(dependency.ref) return dependencies def _AddImportedDependencies(self, targets, dependencies=None): """Given a list of direct dependencies, adds indirect dependencies that other dependencies have declared to export their settings. This method does not operate on self. Rather, it operates on the list of dependencies in the |dependencies| argument. For each dependency in that list, if any declares that it exports the settings of one of its own dependencies, those dependencies whose settings are "passed through" are added to the list. As new items are added to the list, they too will be processed, so it is possible to import settings through multiple levels of dependencies. This method is not terribly useful on its own, it depends on being "primed" with a list of direct dependencies such as one provided by DirectDependencies. DirectAndImportedDependencies is intended to be the public entry point. """ if dependencies == None: dependencies = [] index = 0 while index < len(dependencies): dependency = dependencies[index] dependency_dict = targets[dependency] # Add any dependencies whose settings should be imported to the list # if not already present. Newly-added items will be checked for # their own imports when the list iteration reaches them. # Rather than simply appending new items, insert them after the # dependency that exported them. This is done to more closely match # the depth-first method used by DeepDependencies. add_index = 1 for imported_dependency in \ dependency_dict.get('export_dependent_settings', []): if imported_dependency not in dependencies: dependencies.insert(index + add_index, imported_dependency) add_index = add_index + 1 index = index + 1 return dependencies def DirectAndImportedDependencies(self, targets, dependencies=None): """Returns a list of a target's direct dependencies and all indirect dependencies that a dependency has advertised settings should be exported through the dependency for. """ dependencies = self.DirectDependencies(dependencies) return self._AddImportedDependencies(targets, dependencies) def DeepDependencies(self, dependencies=None): """Returns a list of all of a target's dependencies, recursively.""" if dependencies == None: dependencies = [] for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref != None and dependency.ref not in dependencies: dependencies.append(dependency.ref) dependency.DeepDependencies(dependencies) return dependencies def LinkDependencies(self, targets, dependencies=None, initial=True): """Returns a list of dependency targets that are linked into this target. This function has a split personality, depending on the setting of |initial|. Outside callers should always leave |initial| at its default setting. When adding a target to the list of dependencies, this function will recurse into itself with |initial| set to False, to collect dependencies that are linked into the linkable target for which the list is being built. """ if dependencies == None: dependencies = [] # Check for None, corresponding to the root node. if self.ref == None: return dependencies # It's kind of sucky that |targets| has to be passed into this function, # but that's presently the easiest way to access the target dicts so that # this function can find target types. if 'target_name' not in targets[self.ref]: raise GypError("Missing 'target_name' field in target.") if 'type' not in targets[self.ref]: raise GypError("Missing 'type' field in target %s" % targets[self.ref]['target_name']) target_type = targets[self.ref]['type'] is_linkable = target_type in linkable_types if initial and not is_linkable: # If this is the first target being examined and it's not linkable, # return an empty list of link dependencies, because the link # dependencies are intended to apply to the target itself (initial is # True) and this target won't be linked. return dependencies # Don't traverse 'none' targets if explicitly excluded. if (target_type == 'none' and not targets[self.ref].get('dependencies_traverse', True)): if self.ref not in dependencies: dependencies.append(self.ref) return dependencies # Executables and loadable modules are already fully and finally linked. # Nothing else can be a link dependency of them, there can only be # dependencies in the sense that a dependent target might run an # executable or load the loadable_module. if not initial and target_type in ('executable', 'loadable_module'): return dependencies # The target is linkable, add it to the list of link dependencies. if self.ref not in dependencies: dependencies.append(self.ref) if initial or not is_linkable: # If this is a subsequent target and it's linkable, don't look any # further for linkable dependencies, as they'll already be linked into # this target linkable. Always look at dependencies of the initial # target, and always look at dependencies of non-linkables. for dependency in self.dependencies: dependency.LinkDependencies(targets, dependencies, False) return dependencies def BuildDependencyList(targets): # Create a DependencyGraphNode for each target. Put it into a dict for easy # access. dependency_nodes = {} for target, spec in targets.iteritems(): if target not in dependency_nodes: dependency_nodes[target] = DependencyGraphNode(target) # Set up the dependency links. Targets that have no dependencies are treated # as dependent on root_node. root_node = DependencyGraphNode(None) for target, spec in targets.iteritems(): target_node = dependency_nodes[target] target_build_file = gyp.common.BuildFile(target) dependencies = spec.get('dependencies') if not dependencies: target_node.dependencies = [root_node] root_node.dependents.append(target_node) else: for dependency in dependencies: dependency_node = dependency_nodes.get(dependency) if not dependency_node: raise GypError("Dependency '%s' not found while " "trying to load target %s" % (dependency, target)) target_node.dependencies.append(dependency_node) dependency_node.dependents.append(target_node) flat_list = root_node.FlattenToList() # If there's anything left unvisited, there must be a circular dependency # (cycle). If you need to figure out what's wrong, look for elements of # targets that are not in flat_list. if len(flat_list) != len(targets): raise DependencyGraphNode.CircularException( 'Some targets not reachable, cycle in dependency graph detected: ' + ' '.join(set(flat_list) ^ set(targets))) return [dependency_nodes, flat_list] def VerifyNoGYPFileCircularDependencies(targets): # Create a DependencyGraphNode for each gyp file containing a target. Put # it into a dict for easy access. dependency_nodes = {} for target in targets.iterkeys(): build_file = gyp.common.BuildFile(target) if not build_file in dependency_nodes: dependency_nodes[build_file] = DependencyGraphNode(build_file) # Set up the dependency links. for target, spec in targets.iteritems(): build_file = gyp.common.BuildFile(target) build_file_node = dependency_nodes[build_file] target_dependencies = spec.get('dependencies', []) for dependency in target_dependencies: try: dependency_build_file = gyp.common.BuildFile(dependency) except GypError, e: gyp.common.ExceptionAppend( e, 'while computing dependencies of .gyp file %s' % build_file) raise if dependency_build_file == build_file: # A .gyp file is allowed to refer back to itself. continue dependency_node = dependency_nodes.get(dependency_build_file) if not dependency_node: raise GypError("Dependancy '%s' not found" % dependency_build_file) if dependency_node not in build_file_node.dependencies: build_file_node.dependencies.append(dependency_node) dependency_node.dependents.append(build_file_node) # Files that have no dependencies are treated as dependent on root_node. root_node = DependencyGraphNode(None) for build_file_node in dependency_nodes.itervalues(): if len(build_file_node.dependencies) == 0: build_file_node.dependencies.append(root_node) root_node.dependents.append(build_file_node) flat_list = root_node.FlattenToList() # If there's anything left unvisited, there must be a circular dependency # (cycle). if len(flat_list) != len(dependency_nodes): bad_files = [] for file in dependency_nodes.iterkeys(): if not file in flat_list: bad_files.append(file) raise DependencyGraphNode.CircularException, \ 'Some files not reachable, cycle in .gyp file dependency graph ' + \ 'detected involving some or all of: ' + \ ' '.join(bad_files) def DoDependentSettings(key, flat_list, targets, dependency_nodes): # key should be one of all_dependent_settings, direct_dependent_settings, # or link_settings. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) if key == 'all_dependent_settings': dependencies = dependency_nodes[target].DeepDependencies() elif key == 'direct_dependent_settings': dependencies = \ dependency_nodes[target].DirectAndImportedDependencies(targets) elif key == 'link_settings': dependencies = dependency_nodes[target].LinkDependencies(targets) else: raise GypError("DoDependentSettings doesn't know how to determine " 'dependencies for ' + key) for dependency in dependencies: dependency_dict = targets[dependency] if not key in dependency_dict: continue dependency_build_file = gyp.common.BuildFile(dependency) MergeDicts(target_dict, dependency_dict[key], build_file, dependency_build_file) def AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes, sort_dependencies): # Recompute target "dependencies" properties. For each static library # target, remove "dependencies" entries referring to other static libraries, # unless the dependency has the "hard_dependency" attribute set. For each # linkable target, add a "dependencies" entry referring to all of the # target's computed list of link dependencies (including static libraries # if no such entry is already present. for target in flat_list: target_dict = targets[target] target_type = target_dict['type'] if target_type == 'static_library': if not 'dependencies' in target_dict: continue target_dict['dependencies_original'] = target_dict.get( 'dependencies', [])[:] # A static library should not depend on another static library unless # the dependency relationship is "hard," which should only be done when # a dependent relies on some side effect other than just the build # product, like a rule or action output. Further, if a target has a # non-hard dependency, but that dependency exports a hard dependency, # the non-hard dependency can safely be removed, but the exported hard # dependency must be added to the target to keep the same dependency # ordering. dependencies = \ dependency_nodes[target].DirectAndImportedDependencies(targets) index = 0 while index < len(dependencies): dependency = dependencies[index] dependency_dict = targets[dependency] # Remove every non-hard static library dependency and remove every # non-static library dependency that isn't a direct dependency. if (dependency_dict['type'] == 'static_library' and \ not dependency_dict.get('hard_dependency', False)) or \ (dependency_dict['type'] != 'static_library' and \ not dependency in target_dict['dependencies']): # Take the dependency out of the list, and don't increment index # because the next dependency to analyze will shift into the index # formerly occupied by the one being removed. del dependencies[index] else: index = index + 1 # Update the dependencies. If the dependencies list is empty, it's not # needed, so unhook it. if len(dependencies) > 0: target_dict['dependencies'] = dependencies else: del target_dict['dependencies'] elif target_type in linkable_types: # Get a list of dependency targets that should be linked into this # target. Add them to the dependencies list if they're not already # present. link_dependencies = dependency_nodes[target].LinkDependencies(targets) for dependency in link_dependencies: if dependency == target: continue if not 'dependencies' in target_dict: target_dict['dependencies'] = [] if not dependency in target_dict['dependencies']: target_dict['dependencies'].append(dependency) # Sort the dependencies list in the order from dependents to dependencies. # e.g. If A and B depend on C and C depends on D, sort them in A, B, C, D. # Note: flat_list is already sorted in the order from dependencies to # dependents. if sort_dependencies and 'dependencies' in target_dict: target_dict['dependencies'] = [dep for dep in reversed(flat_list) if dep in target_dict['dependencies']] # Initialize this here to speed up MakePathRelative. exception_re = re.compile(r'''["']?[-/$<>^]''') def MakePathRelative(to_file, fro_file, item): # If item is a relative path, it's relative to the build file dict that it's # coming from. Fix it up to make it relative to the build file dict that # it's going into. # Exception: any |item| that begins with these special characters is # returned without modification. # / Used when a path is already absolute (shortcut optimization; # such paths would be returned as absolute anyway) # $ Used for build environment variables # - Used for some build environment flags (such as -lapr-1 in a # "libraries" section) # < Used for our own variable and command expansions (see ExpandVariables) # > Used for our own variable and command expansions (see ExpandVariables) # ^ Used for our own variable and command expansions (see ExpandVariables) # # "/' Used when a value is quoted. If these are present, then we # check the second character instead. # if to_file == fro_file or exception_re.match(item): return item else: # TODO(dglazkov) The backslash/forward-slash replacement at the end is a # temporary measure. This should really be addressed by keeping all paths # in POSIX until actual project generation. ret = os.path.normpath(os.path.join( gyp.common.RelativePath(os.path.dirname(fro_file), os.path.dirname(to_file)), item)).replace('\\', '/') if item[-1] == '/': ret += '/' return ret def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True): # Python documentation recommends objects which do not support hash # set this value to None. Python library objects follow this rule. is_hashable = lambda val: val.__hash__ # If x is hashable, returns whether x is in s. Else returns whether x is in l. def is_in_set_or_list(x, s, l): if is_hashable(x): return x in s return x in l prepend_index = 0 # Make membership testing of hashables in |to| (in particular, strings) # faster. hashable_to_set = set(x for x in to if is_hashable(x)) for item in fro: singleton = False if isinstance(item, str) or isinstance(item, int): # The cheap and easy case. if is_paths: to_item = MakePathRelative(to_file, fro_file, item) else: to_item = item if not isinstance(item, str) or not item.startswith('-'): # Any string that doesn't begin with a "-" is a singleton - it can # only appear once in a list, to be enforced by the list merge append # or prepend. singleton = True elif isinstance(item, dict): # Make a copy of the dictionary, continuing to look for paths to fix. # The other intelligent aspects of merge processing won't apply because # item is being merged into an empty dict. to_item = {} MergeDicts(to_item, item, to_file, fro_file) elif isinstance(item, list): # Recurse, making a copy of the list. If the list contains any # descendant dicts, path fixing will occur. Note that here, custom # values for is_paths and append are dropped; those are only to be # applied to |to| and |fro|, not sublists of |fro|. append shouldn't # matter anyway because the new |to_item| list is empty. to_item = [] MergeLists(to_item, item, to_file, fro_file) else: raise TypeError, \ 'Attempt to merge list item of unsupported type ' + \ item.__class__.__name__ if append: # If appending a singleton that's already in the list, don't append. # This ensures that the earliest occurrence of the item will stay put. if not singleton or not is_in_set_or_list(to_item, hashable_to_set, to): to.append(to_item) if is_hashable(to_item): hashable_to_set.add(to_item) else: # If prepending a singleton that's already in the list, remove the # existing instance and proceed with the prepend. This ensures that the # item appears at the earliest possible position in the list. while singleton and to_item in to: to.remove(to_item) # Don't just insert everything at index 0. That would prepend the new # items to the list in reverse order, which would be an unwelcome # surprise. to.insert(prepend_index, to_item) if is_hashable(to_item): hashable_to_set.add(to_item) prepend_index = prepend_index + 1 def MergeDicts(to, fro, to_file, fro_file): # I wanted to name the parameter "from" but it's a Python keyword... for k, v in fro.iteritems(): # It would be nice to do "if not k in to: to[k] = v" but that wouldn't give # copy semantics. Something else may want to merge from the |fro| dict # later, and having the same dict ref pointed to twice in the tree isn't # what anyone wants considering that the dicts may subsequently be # modified. if k in to: bad_merge = False if isinstance(v, str) or isinstance(v, int): if not (isinstance(to[k], str) or isinstance(to[k], int)): bad_merge = True elif v.__class__ != to[k].__class__: bad_merge = True if bad_merge: raise TypeError, \ 'Attempt to merge dict value of type ' + v.__class__.__name__ + \ ' into incompatible type ' + to[k].__class__.__name__ + \ ' for key ' + k if isinstance(v, str) or isinstance(v, int): # Overwrite the existing value, if any. Cheap and easy. is_path = IsPathSection(k) if is_path: to[k] = MakePathRelative(to_file, fro_file, v) else: to[k] = v elif isinstance(v, dict): # Recurse, guaranteeing copies will be made of objects that require it. if not k in to: to[k] = {} MergeDicts(to[k], v, to_file, fro_file) elif isinstance(v, list): # Lists in dicts can be merged with different policies, depending on # how the key in the "from" dict (k, the from-key) is written. # # If the from-key has ...the to-list will have this action # this character appended:... applied when receiving the from-list: # = replace # + prepend # ? set, only if to-list does not yet exist # (none) append # # This logic is list-specific, but since it relies on the associated # dict key, it's checked in this dict-oriented function. ext = k[-1] append = True if ext == '=': list_base = k[:-1] lists_incompatible = [list_base, list_base + '?'] to[list_base] = [] elif ext == '+': list_base = k[:-1] lists_incompatible = [list_base + '=', list_base + '?'] append = False elif ext == '?': list_base = k[:-1] lists_incompatible = [list_base, list_base + '=', list_base + '+'] else: list_base = k lists_incompatible = [list_base + '=', list_base + '?'] # Some combinations of merge policies appearing together are meaningless. # It's stupid to replace and append simultaneously, for example. Append # and prepend are the only policies that can coexist. for list_incompatible in lists_incompatible: if list_incompatible in fro: raise GypError('Incompatible list policies ' + k + ' and ' + list_incompatible) if list_base in to: if ext == '?': # If the key ends in "?", the list will only be merged if it doesn't # already exist. continue if not isinstance(to[list_base], list): # This may not have been checked above if merging in a list with an # extension character. raise TypeError, \ 'Attempt to merge dict value of type ' + v.__class__.__name__ + \ ' into incompatible type ' + to[list_base].__class__.__name__ + \ ' for key ' + list_base + '(' + k + ')' else: to[list_base] = [] # Call MergeLists, which will make copies of objects that require it. # MergeLists can recurse back into MergeDicts, although this will be # to make copies of dicts (with paths fixed), there will be no # subsequent dict "merging" once entering a list because lists are # always replaced, appended to, or prepended to. is_paths = IsPathSection(list_base) MergeLists(to[list_base], v, to_file, fro_file, is_paths, append) else: raise TypeError, \ 'Attempt to merge dict value of unsupported type ' + \ v.__class__.__name__ + ' for key ' + k def MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, configuration, visited): # Skip if previously visted. if configuration in visited: return # Look at this configuration. configuration_dict = target_dict['configurations'][configuration] # Merge in parents. for parent in configuration_dict.get('inherit_from', []): MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, parent, visited + [configuration]) # Merge it into the new config. MergeDicts(new_configuration_dict, configuration_dict, build_file, build_file) # Drop abstract. if 'abstract' in new_configuration_dict: del new_configuration_dict['abstract'] def SetUpConfigurations(target, target_dict): # key_suffixes is a list of key suffixes that might appear on key names. # These suffixes are handled in conditional evaluations (for =, +, and ?) # and rules/exclude processing (for ! and /). Keys with these suffixes # should be treated the same as keys without. key_suffixes = ['=', '+', '?', '!', '/'] build_file = gyp.common.BuildFile(target) # Provide a single configuration by default if none exists. # TODO(mark): Signal an error if default_configurations exists but # configurations does not. if not 'configurations' in target_dict: target_dict['configurations'] = {'Default': {}} if not 'default_configuration' in target_dict: concrete = [i for i in target_dict['configurations'].iterkeys() if not target_dict['configurations'][i].get('abstract')] target_dict['default_configuration'] = sorted(concrete)[0] for configuration in target_dict['configurations'].keys(): old_configuration_dict = target_dict['configurations'][configuration] # Skip abstract configurations (saves work only). if old_configuration_dict.get('abstract'): continue # Configurations inherit (most) settings from the enclosing target scope. # Get the inheritance relationship right by making a copy of the target # dict. new_configuration_dict = copy.deepcopy(target_dict) # Take out the bits that don't belong in a "configurations" section. # Since configuration setup is done before conditional, exclude, and rules # processing, be careful with handling of the suffix characters used in # those phases. delete_keys = [] for key in new_configuration_dict: key_ext = key[-1:] if key_ext in key_suffixes: key_base = key[:-1] else: key_base = key if key_base in non_configuration_keys: delete_keys.append(key) for key in delete_keys: del new_configuration_dict[key] # Merge in configuration (with all its parents first). MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, configuration, []) # Put the new result back into the target dict as a configuration. target_dict['configurations'][configuration] = new_configuration_dict # Now drop all the abstract ones. for configuration in target_dict['configurations'].keys(): old_configuration_dict = target_dict['configurations'][configuration] if old_configuration_dict.get('abstract'): del target_dict['configurations'][configuration] # Now that all of the target's configurations have been built, go through # the target dict's keys and remove everything that's been moved into a # "configurations" section. delete_keys = [] for key in target_dict: key_ext = key[-1:] if key_ext in key_suffixes: key_base = key[:-1] else: key_base = key if not key_base in non_configuration_keys: delete_keys.append(key) for key in delete_keys: del target_dict[key] # Check the configurations to see if they contain invalid keys. for configuration in target_dict['configurations'].keys(): configuration_dict = target_dict['configurations'][configuration] for key in configuration_dict.keys(): if key in invalid_configuration_keys: raise GypError('%s not allowed in the %s configuration, found in ' 'target %s' % (key, configuration, target)) def ProcessListFiltersInDict(name, the_dict): """Process regular expression and exclusion-based filters on lists. An exclusion list is in a dict key named with a trailing "!", like "sources!". Every item in such a list is removed from the associated main list, which in this example, would be "sources". Removed items are placed into a "sources_excluded" list in the dict. Regular expression (regex) filters are contained in dict keys named with a trailing "/", such as "sources/" to operate on the "sources" list. Regex filters in a dict take the form: 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'], ['include', '_mac\\.cc$'] ], The first filter says to exclude all files ending in _linux.cc, _mac.cc, and _win.cc. The second filter then includes all files ending in _mac.cc that are now or were once in the "sources" list. Items matching an "exclude" filter are subject to the same processing as would occur if they were listed by name in an exclusion list (ending in "!"). Items matching an "include" filter are brought back into the main list if previously excluded by an exclusion list or exclusion regex filter. Subsequent matching "exclude" patterns can still cause items to be excluded after matching an "include". """ # Look through the dictionary for any lists whose keys end in "!" or "/". # These are lists that will be treated as exclude lists and regular # expression-based exclude/include lists. Collect the lists that are # needed first, looking for the lists that they operate on, and assemble # then into |lists|. This is done in a separate loop up front, because # the _included and _excluded keys need to be added to the_dict, and that # can't be done while iterating through it. lists = [] del_lists = [] for key, value in the_dict.iteritems(): operation = key[-1] if operation != '!' and operation != '/': continue if not isinstance(value, list): raise ValueError, name + ' key ' + key + ' must be list, not ' + \ value.__class__.__name__ list_key = key[:-1] if list_key not in the_dict: # This happens when there's a list like "sources!" but no corresponding # "sources" list. Since there's nothing for it to operate on, queue up # the "sources!" list for deletion now. del_lists.append(key) continue if not isinstance(the_dict[list_key], list): raise ValueError, name + ' key ' + list_key + \ ' must be list, not ' + \ value.__class__.__name__ + ' when applying ' + \ {'!': 'exclusion', '/': 'regex'}[operation] if not list_key in lists: lists.append(list_key) # Delete the lists that are known to be unneeded at this point. for del_list in del_lists: del the_dict[del_list] for list_key in lists: the_list = the_dict[list_key] # Initialize the list_actions list, which is parallel to the_list. Each # item in list_actions identifies whether the corresponding item in # the_list should be excluded, unconditionally preserved (included), or # whether no exclusion or inclusion has been applied. Items for which # no exclusion or inclusion has been applied (yet) have value -1, items # excluded have value 0, and items included have value 1. Includes and # excludes override previous actions. All items in list_actions are # initialized to -1 because no excludes or includes have been processed # yet. list_actions = list((-1,) * len(the_list)) exclude_key = list_key + '!' if exclude_key in the_dict: for exclude_item in the_dict[exclude_key]: for index in xrange(0, len(the_list)): if exclude_item == the_list[index]: # This item matches the exclude_item, so set its action to 0 # (exclude). list_actions[index] = 0 # The "whatever!" list is no longer needed, dump it. del the_dict[exclude_key] regex_key = list_key + '/' if regex_key in the_dict: for regex_item in the_dict[regex_key]: [action, pattern] = regex_item pattern_re = re.compile(pattern) if action == 'exclude': # This item matches an exclude regex, so set its value to 0 (exclude). action_value = 0 elif action == 'include': # This item matches an include regex, so set its value to 1 (include). action_value = 1 else: # This is an action that doesn't make any sense. raise ValueError, 'Unrecognized action ' + action + ' in ' + name + \ ' key ' + regex_key for index in xrange(0, len(the_list)): list_item = the_list[index] if list_actions[index] == action_value: # Even if the regex matches, nothing will change so continue (regex # searches are expensive). continue if pattern_re.search(list_item): # Regular expression match. list_actions[index] = action_value # The "whatever/" list is no longer needed, dump it. del the_dict[regex_key] # Add excluded items to the excluded list. # # Note that exclude_key ("sources!") is different from excluded_key # ("sources_excluded"). The exclude_key list is input and it was already # processed and deleted; the excluded_key list is output and it's about # to be created. excluded_key = list_key + '_excluded' if excluded_key in the_dict: raise GypError(name + ' key ' + excluded_key + ' must not be present prior ' ' to applying exclusion/regex filters for ' + list_key) excluded_list = [] # Go backwards through the list_actions list so that as items are deleted, # the indices of items that haven't been seen yet don't shift. That means # that things need to be prepended to excluded_list to maintain them in the # same order that they existed in the_list. for index in xrange(len(list_actions) - 1, -1, -1): if list_actions[index] == 0: # Dump anything with action 0 (exclude). Keep anything with action 1 # (include) or -1 (no include or exclude seen for the item). excluded_list.insert(0, the_list[index]) del the_list[index] # If anything was excluded, put the excluded list into the_dict at # excluded_key. if len(excluded_list) > 0: the_dict[excluded_key] = excluded_list # Now recurse into subdicts and lists that may contain dicts. for key, value in the_dict.iteritems(): if isinstance(value, dict): ProcessListFiltersInDict(key, value) elif isinstance(value, list): ProcessListFiltersInList(key, value) def ProcessListFiltersInList(name, the_list): for item in the_list: if isinstance(item, dict): ProcessListFiltersInDict(name, item) elif isinstance(item, list): ProcessListFiltersInList(name, item) def ValidateTargetType(target, target_dict): """Ensures the 'type' field on the target is one of the known types. Arguments: target: string, name of target. target_dict: dict, target spec. Raises an exception on error. """ VALID_TARGET_TYPES = ('executable', 'loadable_module', 'static_library', 'shared_library', 'none') target_type = target_dict.get('type', None) if target_type not in VALID_TARGET_TYPES: raise GypError("Target %s has an invalid target type '%s'. " "Must be one of %s." % (target, target_type, '/'.join(VALID_TARGET_TYPES))) if (target_dict.get('standalone_static_library', 0) and not target_type == 'static_library'): raise GypError('Target %s has type %s but standalone_static_library flag is' ' only valid for static_library type.' % (target, target_type)) def ValidateSourcesInTarget(target, target_dict, build_file): # TODO: Check if MSVC allows this for loadable_module targets. if target_dict.get('type', None) not in ('static_library', 'shared_library'): return sources = target_dict.get('sources', []) basenames = {} for source in sources: name, ext = os.path.splitext(source) is_compiled_file = ext in [ '.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S'] if not is_compiled_file: continue basename = os.path.basename(name) # Don't include extension. basenames.setdefault(basename, []).append(source) error = '' for basename, files in basenames.iteritems(): if len(files) > 1: error += ' %s: %s\n' % (basename, ' '.join(files)) if error: print('static library %s has several files with the same basename:\n' % target + error + 'Some build systems, e.g. MSVC08, ' 'cannot handle that.') raise GypError('Duplicate basenames in sources section, see list above') def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules): """Ensures that the rules sections in target_dict are valid and consistent, and determines which sources they apply to. Arguments: target: string, name of target. target_dict: dict, target spec containing "rules" and "sources" lists. extra_sources_for_rules: a list of keys to scan for rule matches in addition to 'sources'. """ # Dicts to map between values found in rules' 'rule_name' and 'extension' # keys and the rule dicts themselves. rule_names = {} rule_extensions = {} rules = target_dict.get('rules', []) for rule in rules: # Make sure that there's no conflict among rule names and extensions. rule_name = rule['rule_name'] if rule_name in rule_names: raise GypError('rule %s exists in duplicate, target %s' % (rule_name, target)) rule_names[rule_name] = rule rule_extension = rule['extension'] if rule_extension in rule_extensions: raise GypError(('extension %s associated with multiple rules, ' + 'target %s rules %s and %s') % (rule_extension, target, rule_extensions[rule_extension]['rule_name'], rule_name)) rule_extensions[rule_extension] = rule # Make sure rule_sources isn't already there. It's going to be # created below if needed. if 'rule_sources' in rule: raise GypError( 'rule_sources must not exist in input, target %s rule %s' % (target, rule_name)) extension = rule['extension'] rule_sources = [] source_keys = ['sources'] source_keys.extend(extra_sources_for_rules) for source_key in source_keys: for source in target_dict.get(source_key, []): (source_root, source_extension) = os.path.splitext(source) if source_extension.startswith('.'): source_extension = source_extension[1:] if source_extension == extension: rule_sources.append(source) if len(rule_sources) > 0: rule['rule_sources'] = rule_sources def ValidateRunAsInTarget(target, target_dict, build_file): target_name = target_dict.get('target_name') run_as = target_dict.get('run_as') if not run_as: return if not isinstance(run_as, dict): raise GypError("The 'run_as' in target %s from file %s should be a " "dictionary." % (target_name, build_file)) action = run_as.get('action') if not action: raise GypError("The 'run_as' in target %s from file %s must have an " "'action' section." % (target_name, build_file)) if not isinstance(action, list): raise GypError("The 'action' for 'run_as' in target %s from file %s " "must be a list." % (target_name, build_file)) working_directory = run_as.get('working_directory') if working_directory and not isinstance(working_directory, str): raise GypError("The 'working_directory' for 'run_as' in target %s " "in file %s should be a string." % (target_name, build_file)) environment = run_as.get('environment') if environment and not isinstance(environment, dict): raise GypError("The 'environment' for 'run_as' in target %s " "in file %s should be a dictionary." % (target_name, build_file)) def ValidateActionsInTarget(target, target_dict, build_file): '''Validates the inputs to the actions in a target.''' target_name = target_dict.get('target_name') actions = target_dict.get('actions', []) for action in actions: action_name = action.get('action_name') if not action_name: raise GypError("Anonymous action in target %s. " "An action must have an 'action_name' field." % target_name) inputs = action.get('inputs', None) if inputs is None: raise GypError('Action in target %s has no inputs.' % target_name) action_command = action.get('action') if action_command and not action_command[0]: raise GypError("Empty action as command in target %s." % target_name) def TurnIntIntoStrInDict(the_dict): """Given dict the_dict, recursively converts all integers into strings. """ # Use items instead of iteritems because there's no need to try to look at # reinserted keys and their associated values. for k, v in the_dict.items(): if isinstance(v, int): v = str(v) the_dict[k] = v elif isinstance(v, dict): TurnIntIntoStrInDict(v) elif isinstance(v, list): TurnIntIntoStrInList(v) if isinstance(k, int): the_dict[str(k)] = v del the_dict[k] def TurnIntIntoStrInList(the_list): """Given list the_list, recursively converts all integers into strings. """ for index in xrange(0, len(the_list)): item = the_list[index] if isinstance(item, int): the_list[index] = str(item) elif isinstance(item, dict): TurnIntIntoStrInDict(item) elif isinstance(item, list): TurnIntIntoStrInList(item) def VerifyNoCollidingTargets(targets): """Verify that no two targets in the same directory share the same name. Arguments: targets: A list of targets in the form 'path/to/file.gyp:target_name'. """ # Keep a dict going from 'subdirectory:target_name' to 'foo.gyp'. used = {} for target in targets: # Separate out 'path/to/file.gyp, 'target_name' from # 'path/to/file.gyp:target_name'. path, name = target.rsplit(':', 1) # Separate out 'path/to', 'file.gyp' from 'path/to/file.gyp'. subdir, gyp = os.path.split(path) # Use '.' for the current directory '', so that the error messages make # more sense. if not subdir: subdir = '.' # Prepare a key like 'path/to:target_name'. key = subdir + ':' + name if key in used: # Complain if this target is already used. raise GypError('Duplicate target name "%s" in directory "%s" used both ' 'in "%s" and "%s".' % (name, subdir, gyp, used[key])) used[key] = gyp def Load(build_files, variables, includes, depth, generator_input_info, check, circular_check, parallel): # Set up path_sections and non_configuration_keys with the default data plus # the generator-specifc data. global path_sections path_sections = base_path_sections[:] path_sections.extend(generator_input_info['path_sections']) global non_configuration_keys non_configuration_keys = base_non_configuration_keys[:] non_configuration_keys.extend(generator_input_info['non_configuration_keys']) # TODO(mark) handle variants if the generator doesn't want them directly. generator_handles_variants = \ generator_input_info['generator_handles_variants'] global absolute_build_file_paths absolute_build_file_paths = \ generator_input_info['generator_wants_absolute_build_file_paths'] global multiple_toolsets multiple_toolsets = generator_input_info[ 'generator_supports_multiple_toolsets'] # A generator can have other lists (in addition to sources) be processed # for rules. extra_sources_for_rules = generator_input_info['extra_sources_for_rules'] # Load build files. This loads every target-containing build file into # the |data| dictionary such that the keys to |data| are build file names, # and the values are the entire build file contents after "early" or "pre" # processing has been done and includes have been resolved. # NOTE: data contains both "target" files (.gyp) and "includes" (.gypi), as # well as meta-data (e.g. 'included_files' key). 'target_build_files' keeps # track of the keys corresponding to "target" files. data = {'target_build_files': set()} aux_data = {} for build_file in build_files: # Normalize paths everywhere. This is important because paths will be # used as keys to the data dict and for references between input files. build_file = os.path.normpath(build_file) try: if parallel: print >>sys.stderr, 'Using parallel processing.' LoadTargetBuildFileParallel(build_file, data, aux_data, variables, includes, depth, check) else: LoadTargetBuildFile(build_file, data, aux_data, variables, includes, depth, check, True) except Exception, e: gyp.common.ExceptionAppend(e, 'while trying to load %s' % build_file) raise # Build a dict to access each target's subdict by qualified name. targets = BuildTargetsDict(data) # Fully qualify all dependency links. QualifyDependencies(targets) # Remove self-dependencies from targets that have 'prune_self_dependencies' # set to 1. RemoveSelfDependencies(targets) # Expand dependencies specified as build_file:*. ExpandWildcardDependencies(targets, data) # Apply exclude (!) and regex (/) list filters only for dependency_sections. for target_name, target_dict in targets.iteritems(): tmp_dict = {} for key_base in dependency_sections: for op in ('', '!', '/'): key = key_base + op if key in target_dict: tmp_dict[key] = target_dict[key] del target_dict[key] ProcessListFiltersInDict(target_name, tmp_dict) # Write the results back to |target_dict|. for key in tmp_dict: target_dict[key] = tmp_dict[key] # Make sure every dependency appears at most once. RemoveDuplicateDependencies(targets) if circular_check: # Make sure that any targets in a.gyp don't contain dependencies in other # .gyp files that further depend on a.gyp. VerifyNoGYPFileCircularDependencies(targets) [dependency_nodes, flat_list] = BuildDependencyList(targets) # Check that no two targets in the same directory have the same name. VerifyNoCollidingTargets(flat_list) # Handle dependent settings of various types. for settings_type in ['all_dependent_settings', 'direct_dependent_settings', 'link_settings']: DoDependentSettings(settings_type, flat_list, targets, dependency_nodes) # Take out the dependent settings now that they've been published to all # of the targets that require them. for target in flat_list: if settings_type in targets[target]: del targets[target][settings_type] # Make sure static libraries don't declare dependencies on other static # libraries, but that linkables depend on all unlinked static libraries # that they need so that their link steps will be correct. gii = generator_input_info if gii['generator_wants_static_library_dependencies_adjusted']: AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes, gii['generator_wants_sorted_dependencies']) # Apply "post"/"late"/"target" variable expansions and condition evaluations. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ProcessVariablesAndConditionsInDict( target_dict, PHASE_LATE, variables, build_file) # Move everything that can go into a "configurations" section into one. for target in flat_list: target_dict = targets[target] SetUpConfigurations(target, target_dict) # Apply exclude (!) and regex (/) list filters. for target in flat_list: target_dict = targets[target] ProcessListFiltersInDict(target, target_dict) # Apply "latelate" variable expansions and condition evaluations. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ProcessVariablesAndConditionsInDict( target_dict, PHASE_LATELATE, variables, build_file) # Make sure that the rules make sense, and build up rule_sources lists as # needed. Not all generators will need to use the rule_sources lists, but # some may, and it seems best to build the list in a common spot. # Also validate actions and run_as elements in targets. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ValidateTargetType(target, target_dict) # TODO(thakis): Get vpx_scale/arm/scalesystemdependent.c to be renamed to # scalesystemdependent_arm_additions.c or similar. if 'arm' not in variables.get('target_arch', ''): ValidateSourcesInTarget(target, target_dict, build_file) ValidateRulesInTarget(target, target_dict, extra_sources_for_rules) ValidateRunAsInTarget(target, target_dict, build_file) ValidateActionsInTarget(target, target_dict, build_file) # Generators might not expect ints. Turn them into strs. TurnIntIntoStrInDict(data) # TODO(mark): Return |data| for now because the generator needs a list of # build files that came in. In the future, maybe it should just accept # a list, and not the whole data dict. return [flat_list, targets, data]
neilhan/tensorflow
refs/heads/master
tensorflow/contrib/factorization/python/ops/gmm_test.py
22
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for ops.gmm.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf FLAGS = tf.app.flags.FLAGS class GMMTest(tf.test.TestCase): def setUp(self): np.random.seed(3) tf.set_random_seed(2) self.num_centers = 2 self.num_dims = 2 self.num_points = 4000 self.batch_size = 100 self.true_centers = self.make_random_centers(self.num_centers, self.num_dims) self.points, self.assignments, self.scores = self.make_random_points( self.true_centers, self.num_points) self.true_score = np.add.reduce(self.scores) # Use initial means from kmeans (just like scikit-learn does). clusterer = tf.contrib.factorization.KMeansClustering( num_clusters=self.num_centers) clusterer.fit(self.points, steps=30) self.initial_means = clusterer.clusters() @staticmethod def make_random_centers(num_centers, num_dims): return np.round(np.random.rand(num_centers, num_dims).astype(np.float32) * 500) @staticmethod def make_random_points(centers, num_points): num_centers, num_dims = centers.shape assignments = np.random.choice(num_centers, num_points) offsets = np.round(np.random.randn(num_points, num_dims).astype(np.float32) * 20) points = centers[assignments] + offsets means = [np.mean(points[assignments == center], axis=0) for center in xrange(num_centers)] covs = [np.cov(points[assignments == center].T) for center in xrange(num_centers)] scores = [] for r in xrange(num_points): scores.append(np.sqrt(np.dot( np.dot(points[r, :] - means[assignments[r]], np.linalg.inv(covs[assignments[r]])), points[r, :] - means[assignments[r]]))) return (points, assignments, scores) def test_clusters(self): """Tests the shape of the clusters.""" gmm = tf.contrib.factorization.GMM( self.num_centers, initial_clusters=self.initial_means, batch_size=self.batch_size, steps=40, continue_training=True, random_seed=4, config=tf.contrib.learn.RunConfig(tf_random_seed=2)) gmm.fit(x=self.points, steps=0) clusters = gmm.clusters() self.assertAllEqual(list(clusters.shape), [self.num_centers, self.num_dims]) def test_fit(self): gmm = tf.contrib.factorization.GMM( self.num_centers, initial_clusters='random', batch_size=self.batch_size, random_seed=4, config=tf.contrib.learn.RunConfig(tf_random_seed=2)) gmm.fit(x=self.points, steps=1) score1 = gmm.score(x=self.points) gmm = tf.contrib.factorization.GMM( self.num_centers, initial_clusters='random', batch_size=self.batch_size, random_seed=4, config=tf.contrib.learn.RunConfig(tf_random_seed=2)) gmm.fit(x=self.points, steps=10) score2 = gmm.score(x=self.points) self.assertGreater(score1, score2) self.assertNear(self.true_score, score2, self.true_score * 0.15) def test_infer(self): gmm = tf.contrib.factorization.GMM( self.num_centers, initial_clusters=self.initial_means, batch_size=self.batch_size, steps=40, continue_training=True, random_seed=4, config=tf.contrib.learn.RunConfig(tf_random_seed=2)) gmm.fit(x=self.points, steps=60) clusters = gmm.clusters() # Make a small test set points, true_assignments, true_offsets = ( self.make_random_points(clusters, 40)) assignments = np.ravel(gmm.predict(points)) self.assertAllEqual(true_assignments, assignments) # Test score score = gmm.score(points) self.assertNear(score, np.sum(true_offsets), 4.05) def _compare_with_sklearn(self, cov_type): # sklearn version. iterations = 40 np.random.seed(5) sklearn_assignments = np.asarray([0, 0, 1, 0, 0, 0, 1, 0, 0, 1]) sklearn_means = np.asarray([[144.83417719, 254.20130341], [274.38754816, 353.16074346]]) sklearn_covs = np.asarray([[[395.0081194, -4.50389512], [-4.50389512, 408.27543989]], [[385.17484203, -31.27834935], [-31.27834935, 391.74249925]]]) # skflow version. gmm = tf.contrib.factorization.GMM( self.num_centers, initial_clusters=self.initial_means, covariance_type=cov_type, batch_size=self.num_points, steps=iterations, continue_training=True, config=tf.contrib.learn.RunConfig(tf_random_seed=2)) gmm.fit(self.points) skflow_assignments = gmm.predict(self.points[:10, :]).astype(int) self.assertAllClose(sklearn_assignments, np.ravel(skflow_assignments)) self.assertAllClose(sklearn_means, gmm.clusters()) if cov_type == 'full': self.assertAllClose(sklearn_covs, gmm.covariances(), rtol=0.01) else: for d in [0, 1]: self.assertAllClose(np.diag(sklearn_covs[d]), gmm.covariances()[d, :], rtol=0.01) def test_compare_full(self): self._compare_with_sklearn('full') def test_compare_diag(self): self._compare_with_sklearn('diag') if __name__ == '__main__': tf.test.main()
mastak/Spirit
refs/heads/master
spirit/comment/flag/forms.py
12
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from django.db import IntegrityError from django.utils import timezone from .models import Flag, CommentFlag class FlagForm(forms.ModelForm): class Meta: model = Flag fields = ['reason', 'body'] def __init__(self, user=None, comment=None, *args, **kwargs): super(FlagForm, self).__init__(*args, **kwargs) self.user = user self.comment = comment def clean(self): cleaned_data = super(FlagForm, self).clean() flag = Flag.objects.filter(user=self.user, comment=self.comment) if flag.exists(): # Do this since some of the unique_together fields are excluded. raise forms.ValidationError(_("This flag already exists")) return cleaned_data def save(self, commit=True): if not self.instance.pk: self.instance.user = self.user self.instance.comment = self.comment try: CommentFlag.objects.update_or_create(comment=self.comment, defaults={'date': timezone.now(), }) except IntegrityError: pass return super(FlagForm, self).save(commit)
jaechoon2/FPGA-Imaging-Library
refs/heads/Publish
LocalFilter/ThresholdLocal/SoftwareSim/MeanFilter.py
8
""" Project FPGA-Imaging-Library Design MeanFilter Function Local filter - Mean filter, it always used for smoothing images. Module Software simulation. Version 1.0 Modified 2015-05-19 Copyright (C) 2015 Tianyu Dai (dtysky) <dtysky@outlook.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Homepage for this project: http://fil.dtysky.moe Sources for this project: https://github.com/dtysky/FPGA-Imaging-Library My e-mail: dtysky@outlook.com My blog: http://dtysky.moe """ def mean_filter(window): w_sum = 0 for row in window: w_sum += sum(row) if len(window) == 2: return w_sum >> 2; elif len(window) == 3: return (w_sum >> 4) + (w_sum >> 5) + (w_sum >> 6); elif len(window) == 4: return w_sum >> 4; elif len(window) == 5: return (w_sum >> 5) + (w_sum >> 7) + (w_sum >> 10); elif len(window) == 6: return (w_sum >> 6) + (w_sum >> 7) + (w_sum >> 8); elif len(window) == 7: return (w_sum >> 6) + (w_sum >> 8) + (w_sum >> 10); elif len(window) == 8: return w_sum >> 6; elif len(window) == 9: return (w_sum >> 7) + (w_sum >> 8) + (w_sum >> 11); elif len(window) == 10: return (w_sum >> 7) + (w_sum >> 9) + (w_sum >> 13); elif len(window) == 11: return (w_sum >> 7) + (w_sum >> 12) + (w_sum >> 13); elif len(window) == 12: return (w_sum >> 8) + (w_sum >> 9) + (w_sum >> 10); elif len(window) == 13: return (w_sum >> 8) + (w_sum >> 9) + (w_sum >> 14); elif len(window) == 14: return (w_sum >> 8) + (w_sum >> 10) + (w_sum >> 12); elif len(window) == 15: return (w_sum >> 8) + (w_sum >> 11);
omakk/servo
refs/heads/master
tests/wpt/web-platform-tests/fetch/api/resources/preflight.py
25
def main(request, response): headers = [("Content-Type", "text/plain")] stashed_data = {'control_request_headers': "", 'preflight': "0", 'preflight_referrer': ""} token = None if "token" in request.GET: token = request.GET.first("token") if "origin" in request.GET: for origin in request.GET['origin'].split(", "): headers.append(("Access-Control-Allow-Origin", origin)) else: headers.append(("Access-Control-Allow-Origin", "*")) if "credentials" in request.GET: headers.append(("Access-Control-Allow-Credentials", "true")) if request.method == "OPTIONS": if not "Access-Control-Request-Method" in request.headers: response.set_error(400, "No Access-Control-Request-Method header") return "ERROR: No access-control-request-method in preflight!" if "control_request_headers" in request.GET: stashed_data['control_request_headers'] = request.headers.get("Access-Control-Request-Headers", None) if "max_age" in request.GET: headers.append(("Access-Control-Max-Age", request.GET['max_age'])) if "allow_headers" in request.GET: headers.append(("Access-Control-Allow-Headers", request.GET['allow_headers'])) if "allow_methods" in request.GET: headers.append(("Access-Control-Allow-Methods", request.GET['allow_methods'])) preflight_status = 200 if "preflight_status" in request.GET: preflight_status = int(request.GET.first("preflight_status")) stashed_data['preflight'] = "1" stashed_data['preflight_referrer'] = request.headers.get("Referer", "") if token: request.server.stash.put(token, stashed_data) return preflight_status, headers, "" if token: data = request.server.stash.take(token) if data: stashed_data = data #use x-* headers for returning value to bodyless responses headers.append(("Access-Control-Expose-Headers", "x-did-preflight, x-control-request-headers, x-referrer, x-preflight-referrer, x-origin")) headers.append(("x-did-preflight", stashed_data['preflight'])) if stashed_data['control_request_headers'] != None: headers.append(("x-control-request-headers", stashed_data['control_request_headers'])) headers.append(("x-preflight-referrer", stashed_data['preflight_referrer'])) headers.append(("x-referrer", request.headers.get("Referer", "") )) headers.append(("x-origin", request.headers.get("Origin", "") )) if token: request.server.stash.put(token, stashed_data) return headers, ""
imsparsh/python-for-android
refs/heads/master
python-modules/twisted/twisted/names/test/test_dns.py
49
# test-case-name: twisted.names.test.test_dns # Copyright (c) 2001-2010 Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for twisted.names.dns. """ try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import struct from twisted.python.failure import Failure from twisted.internet import address, task from twisted.internet.error import CannotListenError, ConnectionDone from twisted.trial import unittest from twisted.names import dns from twisted.test import proto_helpers class RoundtripDNSTestCase(unittest.TestCase): """Encoding and then decoding various objects.""" names = ["example.org", "go-away.fish.tv", "23strikesback.net"] def testName(self): for n in self.names: # encode the name f = StringIO() dns.Name(n).encode(f) # decode the name f.seek(0, 0) result = dns.Name() result.decode(f) self.assertEquals(result.name, n) def testQuery(self): for n in self.names: for dnstype in range(1, 17): for dnscls in range(1, 5): # encode the query f = StringIO() dns.Query(n, dnstype, dnscls).encode(f) # decode the result f.seek(0, 0) result = dns.Query() result.decode(f) self.assertEquals(result.name.name, n) self.assertEquals(result.type, dnstype) self.assertEquals(result.cls, dnscls) def testRR(self): # encode the RR f = StringIO() dns.RRHeader("test.org", 3, 4, 17).encode(f) # decode the result f.seek(0, 0) result = dns.RRHeader() result.decode(f) self.assertEquals(str(result.name), "test.org") self.assertEquals(result.type, 3) self.assertEquals(result.cls, 4) self.assertEquals(result.ttl, 17) def testResources(self): names = ( "this.are.test.name", "will.compress.will.this.will.name.will.hopefully", "test.CASE.preSErVatIOn.YeAH", "a.s.h.o.r.t.c.a.s.e.t.o.t.e.s.t", "singleton" ) for s in names: f = StringIO() dns.SimpleRecord(s).encode(f) f.seek(0, 0) result = dns.SimpleRecord() result.decode(f) self.assertEquals(str(result.name), s) def test_hashable(self): """ Instances of all record types are hashable. """ records = [ dns.Record_NS, dns.Record_MD, dns.Record_MF, dns.Record_CNAME, dns.Record_MB, dns.Record_MG, dns.Record_MR, dns.Record_PTR, dns.Record_DNAME, dns.Record_A, dns.Record_SOA, dns.Record_NULL, dns.Record_WKS, dns.Record_SRV, dns.Record_AFSDB, dns.Record_RP, dns.Record_HINFO, dns.Record_MINFO, dns.Record_MX, dns.Record_TXT, dns.Record_AAAA, dns.Record_A6, dns.Record_NAPTR ] for k in records: k1, k2 = k(), k() hk1 = hash(k1) hk2 = hash(k2) self.assertEquals(hk1, hk2, "%s != %s (for %s)" % (hk1,hk2,k)) def test_Charstr(self): """ Test L{dns.Charstr} encode and decode. """ for n in self.names: # encode the name f = StringIO() dns.Charstr(n).encode(f) # decode the name f.seek(0, 0) result = dns.Charstr() result.decode(f) self.assertEquals(result.string, n) def test_NAPTR(self): """ Test L{dns.Record_NAPTR} encode and decode. """ naptrs = [(100, 10, "u", "sip+E2U", "!^.*$!sip:information@domain.tld!", ""), (100, 50, "s", "http+I2L+I2C+I2R", "", "_http._tcp.gatech.edu")] for (order, preference, flags, service, regexp, replacement) in naptrs: rin = dns.Record_NAPTR(order, preference, flags, service, regexp, replacement) e = StringIO() rin.encode(e) e.seek(0,0) rout = dns.Record_NAPTR() rout.decode(e) self.assertEquals(rin.order, rout.order) self.assertEquals(rin.preference, rout.preference) self.assertEquals(rin.flags, rout.flags) self.assertEquals(rin.service, rout.service) self.assertEquals(rin.regexp, rout.regexp) self.assertEquals(rin.replacement.name, rout.replacement.name) self.assertEquals(rin.ttl, rout.ttl) class MessageTestCase(unittest.TestCase): """ Tests for L{twisted.names.dns.Message}. """ def testEmptyMessage(self): """ Test that a message which has been truncated causes an EOFError to be raised when it is parsed. """ msg = dns.Message() self.assertRaises(EOFError, msg.fromStr, '') def testEmptyQuery(self): """ Test that bytes representing an empty query message can be decoded as such. """ msg = dns.Message() msg.fromStr( '\x01\x00' # Message ID '\x00' # answer bit, opCode nibble, auth bit, trunc bit, recursive bit '\x00' # recursion bit, empty bit, empty bit, empty bit, response code nibble '\x00\x00' # number of queries '\x00\x00' # number of answers '\x00\x00' # number of authorities '\x00\x00' # number of additionals ) self.assertEquals(msg.id, 256) self.failIf(msg.answer, "Message was not supposed to be an answer.") self.assertEquals(msg.opCode, dns.OP_QUERY) self.failIf(msg.auth, "Message was not supposed to be authoritative.") self.failIf(msg.trunc, "Message was not supposed to be truncated.") self.assertEquals(msg.queries, []) self.assertEquals(msg.answers, []) self.assertEquals(msg.authority, []) self.assertEquals(msg.additional, []) def testNULL(self): bytes = ''.join([chr(i) for i in range(256)]) rec = dns.Record_NULL(bytes) rr = dns.RRHeader('testname', dns.NULL, payload=rec) msg1 = dns.Message() msg1.answers.append(rr) s = StringIO() msg1.encode(s) s.seek(0, 0) msg2 = dns.Message() msg2.decode(s) self.failUnless(isinstance(msg2.answers[0].payload, dns.Record_NULL)) self.assertEquals(msg2.answers[0].payload.payload, bytes) def test_lookupRecordTypeDefault(self): """ L{Message.lookupRecordType} returns C{None} if it is called with an integer which doesn't correspond to any known record type. """ # 65280 is the first value in the range reserved for private # use, so it shouldn't ever conflict with an officially # allocated value. self.assertIdentical(dns.Message().lookupRecordType(65280), None) class TestController(object): """ Pretend to be a DNS query processor for a DNSDatagramProtocol. @ivar messages: the list of received messages. @type messages: C{list} of (msg, protocol, address) """ def __init__(self): """ Initialize the controller: create a list of messages. """ self.messages = [] def messageReceived(self, msg, proto, addr): """ Save the message so that it can be checked during the tests. """ self.messages.append((msg, proto, addr)) class DatagramProtocolTestCase(unittest.TestCase): """ Test various aspects of L{dns.DNSDatagramProtocol}. """ def setUp(self): """ Create a L{dns.DNSDatagramProtocol} with a deterministic clock. """ self.clock = task.Clock() self.controller = TestController() self.proto = dns.DNSDatagramProtocol(self.controller) transport = proto_helpers.FakeDatagramTransport() self.proto.makeConnection(transport) self.proto.callLater = self.clock.callLater def test_truncatedPacket(self): """ Test that when a short datagram is received, datagramReceived does not raise an exception while processing it. """ self.proto.datagramReceived('', address.IPv4Address('UDP', '127.0.0.1', 12345)) self.assertEquals(self.controller.messages, []) def test_simpleQuery(self): """ Test content received after a query. """ d = self.proto.query(('127.0.0.1', 21345), [dns.Query('foo')]) self.assertEquals(len(self.proto.liveMessages.keys()), 1) m = dns.Message() m.id = self.proto.liveMessages.items()[0][0] m.answers = [dns.RRHeader(payload=dns.Record_A(address='1.2.3.4'))] called = False def cb(result): self.assertEquals(result.answers[0].payload.dottedQuad(), '1.2.3.4') d.addCallback(cb) self.proto.datagramReceived(m.toStr(), ('127.0.0.1', 21345)) return d def test_queryTimeout(self): """ Test that query timeouts after some seconds. """ d = self.proto.query(('127.0.0.1', 21345), [dns.Query('foo')]) self.assertEquals(len(self.proto.liveMessages), 1) self.clock.advance(10) self.assertFailure(d, dns.DNSQueryTimeoutError) self.assertEquals(len(self.proto.liveMessages), 0) return d def test_writeError(self): """ Exceptions raised by the transport's write method should be turned into C{Failure}s passed to errbacks of the C{Deferred} returned by L{DNSDatagramProtocol.query}. """ def writeError(message, addr): raise RuntimeError("bar") self.proto.transport.write = writeError d = self.proto.query(('127.0.0.1', 21345), [dns.Query('foo')]) return self.assertFailure(d, RuntimeError) def test_listenError(self): """ Exception L{CannotListenError} raised by C{listenUDP} should be turned into a C{Failure} passed to errback of the C{Deferred} returned by L{DNSDatagramProtocol.query}. """ def startListeningError(): raise CannotListenError(None, None, None) self.proto.startListening = startListeningError # Clean up transport so that the protocol calls startListening again self.proto.transport = None d = self.proto.query(('127.0.0.1', 21345), [dns.Query('foo')]) return self.assertFailure(d, CannotListenError) class TestTCPController(TestController): """ Pretend to be a DNS query processor for a DNSProtocol. @ivar connections: A list of L{DNSProtocol} instances which have notified this controller that they are connected and have not yet notified it that their connection has been lost. """ def __init__(self): TestController.__init__(self) self.connections = [] def connectionMade(self, proto): self.connections.append(proto) def connectionLost(self, proto): self.connections.remove(proto) class DNSProtocolTestCase(unittest.TestCase): """ Test various aspects of L{dns.DNSProtocol}. """ def setUp(self): """ Create a L{dns.DNSProtocol} with a deterministic clock. """ self.clock = task.Clock() self.controller = TestTCPController() self.proto = dns.DNSProtocol(self.controller) self.proto.makeConnection(proto_helpers.StringTransport()) self.proto.callLater = self.clock.callLater def test_connectionTracking(self): """ L{dns.DNSProtocol} calls its controller's C{connectionMade} method with itself when it is connected to a transport and its controller's C{connectionLost} method when it is disconnected. """ self.assertEqual(self.controller.connections, [self.proto]) self.proto.connectionLost( Failure(ConnectionDone("Fake Connection Done"))) self.assertEqual(self.controller.connections, []) def test_queryTimeout(self): """ Test that query timeouts after some seconds. """ d = self.proto.query([dns.Query('foo')]) self.assertEquals(len(self.proto.liveMessages), 1) self.clock.advance(60) self.assertFailure(d, dns.DNSQueryTimeoutError) self.assertEquals(len(self.proto.liveMessages), 0) return d def test_simpleQuery(self): """ Test content received after a query. """ d = self.proto.query([dns.Query('foo')]) self.assertEquals(len(self.proto.liveMessages.keys()), 1) m = dns.Message() m.id = self.proto.liveMessages.items()[0][0] m.answers = [dns.RRHeader(payload=dns.Record_A(address='1.2.3.4'))] called = False def cb(result): self.assertEquals(result.answers[0].payload.dottedQuad(), '1.2.3.4') d.addCallback(cb) s = m.toStr() s = struct.pack('!H', len(s)) + s self.proto.dataReceived(s) return d def test_writeError(self): """ Exceptions raised by the transport's write method should be turned into C{Failure}s passed to errbacks of the C{Deferred} returned by L{DNSProtocol.query}. """ def writeError(message): raise RuntimeError("bar") self.proto.transport.write = writeError d = self.proto.query([dns.Query('foo')]) return self.assertFailure(d, RuntimeError) class ReprTests(unittest.TestCase): """ Tests for the C{__repr__} implementation of record classes. """ def test_ns(self): """ The repr of a L{dns.Record_NS} instance includes the name of the nameserver and the TTL of the record. """ self.assertEqual( repr(dns.Record_NS('example.com', 4321)), "<NS name=example.com ttl=4321>") def test_md(self): """ The repr of a L{dns.Record_MD} instance includes the name of the mail destination and the TTL of the record. """ self.assertEqual( repr(dns.Record_MD('example.com', 4321)), "<MD name=example.com ttl=4321>") def test_mf(self): """ The repr of a L{dns.Record_MF} instance includes the name of the mail forwarder and the TTL of the record. """ self.assertEqual( repr(dns.Record_MF('example.com', 4321)), "<MF name=example.com ttl=4321>") def test_cname(self): """ The repr of a L{dns.Record_CNAME} instance includes the name of the mail forwarder and the TTL of the record. """ self.assertEqual( repr(dns.Record_CNAME('example.com', 4321)), "<CNAME name=example.com ttl=4321>") def test_mb(self): """ The repr of a L{dns.Record_MB} instance includes the name of the mailbox and the TTL of the record. """ self.assertEqual( repr(dns.Record_MB('example.com', 4321)), "<MB name=example.com ttl=4321>") def test_mg(self): """ The repr of a L{dns.Record_MG} instance includes the name of the mail group memeber and the TTL of the record. """ self.assertEqual( repr(dns.Record_MG('example.com', 4321)), "<MG name=example.com ttl=4321>") def test_mr(self): """ The repr of a L{dns.Record_MR} instance includes the name of the mail rename domain and the TTL of the record. """ self.assertEqual( repr(dns.Record_MR('example.com', 4321)), "<MR name=example.com ttl=4321>") def test_ptr(self): """ The repr of a L{dns.Record_PTR} instance includes the name of the pointer and the TTL of the record. """ self.assertEqual( repr(dns.Record_PTR('example.com', 4321)), "<PTR name=example.com ttl=4321>") def test_dname(self): """ The repr of a L{dns.Record_DNAME} instance includes the name of the non-terminal DNS name redirection and the TTL of the record. """ self.assertEqual( repr(dns.Record_DNAME('example.com', 4321)), "<DNAME name=example.com ttl=4321>") def test_a(self): """ The repr of a L{dns.Record_A} instance includes the dotted-quad string representation of the address it is for and the TTL of the record. """ self.assertEqual( repr(dns.Record_A('1.2.3.4', 567)), '<A address=1.2.3.4 ttl=567>') def test_soa(self): """ The repr of a L{dns.Record_SOA} instance includes all of the authority fields. """ self.assertEqual( repr(dns.Record_SOA(mname='mName', rname='rName', serial=123, refresh=456, retry=789, expire=10, minimum=11, ttl=12)), "<SOA mname=mName rname=rName serial=123 refresh=456 " "retry=789 expire=10 minimum=11 ttl=12>") def test_null(self): """ The repr of a L{dns.Record_NULL} instance includes the repr of its payload and the TTL of the record. """ self.assertEqual( repr(dns.Record_NULL('abcd', 123)), "<NULL payload='abcd' ttl=123>") def test_wks(self): """ The repr of a L{dns.Record_WKS} instance includes the dotted-quad string representation of the address it is for, the IP protocol number it is for, and the TTL of the record. """ self.assertEqual( repr(dns.Record_WKS('2.3.4.5', 7, ttl=8)), "<WKS address=2.3.4.5 protocol=7 ttl=8>") def test_aaaa(self): """ The repr of a L{dns.Record_AAAA} instance includes the colon-separated hex string representation of the address it is for and the TTL of the record. """ self.assertEqual( repr(dns.Record_AAAA('8765::1234', ttl=10)), "<AAAA address=8765::1234 ttl=10>") def test_a6(self): """ The repr of a L{dns.Record_A6} instance includes the colon-separated hex string representation of the address it is for and the TTL of the record. """ self.assertEqual( repr(dns.Record_A6(0, '1234::5678', 'foo.bar', ttl=10)), "<A6 suffix=1234::5678 prefix=foo.bar ttl=10>") def test_srv(self): """ The repr of a L{dns.Record_SRV} instance includes the name and port of the target and the priority, weight, and TTL of the record. """ self.assertEqual( repr(dns.Record_SRV(1, 2, 3, 'example.org', 4)), "<SRV priority=1 weight=2 target=example.org port=3 ttl=4>") def test_naptr(self): """ The repr of a L{dns.Record_NAPTR} instance includes the order, preference, flags, service, regular expression, replacement, and TTL of the record. """ self.assertEqual( repr(dns.Record_NAPTR(5, 9, "S", "http", "/foo/bar/i", "baz", 3)), "<NAPTR order=5 preference=9 flags=S service=http " "regexp=/foo/bar/i replacement=baz ttl=3>") def test_afsdb(self): """ The repr of a L{dns.Record_AFSDB} instance includes the subtype, hostname, and TTL of the record. """ self.assertEqual( repr(dns.Record_AFSDB(3, 'example.org', 5)), "<AFSDB subtype=3 hostname=example.org ttl=5>") def test_rp(self): """ The repr of a L{dns.Record_RP} instance includes the mbox, txt, and TTL fields of the record. """ self.assertEqual( repr(dns.Record_RP('alice.example.com', 'admin.example.com', 3)), "<RP mbox=alice.example.com txt=admin.example.com ttl=3>") def test_hinfo(self): """ The repr of a L{dns.Record_HINFO} instance includes the cpu, os, and TTL fields of the record. """ self.assertEqual( repr(dns.Record_HINFO('sparc', 'minix', 12)), "<HINFO cpu='sparc' os='minix' ttl=12>") def test_minfo(self): """ The repr of a L{dns.Record_MINFO} instance includes the rmailbx, emailbx, and TTL fields of the record. """ self.assertEqual( repr(dns.Record_MINFO('alice.example.com', 'bob.example.com', 15)), "<MINFO responsibility=alice.example.com " "errors=bob.example.com ttl=15>") def test_mx(self): """ The repr of a L{dns.Record_MX} instance includes the preference, name, and TTL fields of the record. """ self.assertEqual( repr(dns.Record_MX(13, 'mx.example.com', 2)), "<MX preference=13 name=mx.example.com ttl=2>") def test_txt(self): """ The repr of a L{dns.Record_TXT} instance includes the data and ttl fields of the record. """ self.assertEqual( repr(dns.Record_TXT("foo", "bar", ttl=15)), "<TXT data=['foo', 'bar'] ttl=15>") def test_spf(self): """ The repr of a L{dns.Record_SPF} instance includes the data and ttl fields of the record, since it is structurally similar to L{dns.Record_TXT}. """ self.assertEqual( repr(dns.Record_SPF("foo", "bar", ttl=15)), "<SPF data=['foo', 'bar'] ttl=15>") class _Equal(object): """ A class the instances of which are equal to anything and everything. """ def __eq__(self, other): return True def __ne__(self, other): return False class _NotEqual(object): """ A class the instances of which are equal to nothing. """ def __eq__(self, other): return False def __ne__(self, other): return True class EqualityTests(unittest.TestCase): """ Tests for the equality and non-equality behavior of record classes. """ def _equalityTest(self, firstValueOne, secondValueOne, valueTwo): """ Assert that C{firstValueOne} is equal to C{secondValueOne} but not equal to C{valueOne} and that it defines equality cooperatively with other types it doesn't know about. """ # This doesn't use assertEqual and assertNotEqual because the exact # operator those functions use is not very well defined. The point # of these assertions is to check the results of the use of specific # operators (precisely to ensure that using different permutations # (eg "x == y" or "not (x != y)") which should yield the same results # actually does yield the same result). -exarkun self.assertTrue(firstValueOne == firstValueOne) self.assertTrue(firstValueOne == secondValueOne) self.assertFalse(firstValueOne == valueTwo) self.assertFalse(firstValueOne != firstValueOne) self.assertFalse(firstValueOne != secondValueOne) self.assertTrue(firstValueOne != valueTwo) self.assertTrue(firstValueOne == _Equal()) self.assertFalse(firstValueOne != _Equal()) self.assertFalse(firstValueOne == _NotEqual()) self.assertTrue(firstValueOne != _NotEqual()) def _simpleEqualityTest(self, cls): # Vary the TTL self._equalityTest( cls('example.com', 123), cls('example.com', 123), cls('example.com', 321)) # Vary the name self._equalityTest( cls('example.com', 123), cls('example.com', 123), cls('example.org', 123)) def test_rrheader(self): """ Two L{dns.RRHeader} instances compare equal if and only if they have the same name, type, class, time to live, payload, and authoritative bit. """ # Vary the name self._equalityTest( dns.RRHeader('example.com', payload=dns.Record_A('1.2.3.4')), dns.RRHeader('example.com', payload=dns.Record_A('1.2.3.4')), dns.RRHeader('example.org', payload=dns.Record_A('1.2.3.4'))) # Vary the payload self._equalityTest( dns.RRHeader('example.com', payload=dns.Record_A('1.2.3.4')), dns.RRHeader('example.com', payload=dns.Record_A('1.2.3.4')), dns.RRHeader('example.com', payload=dns.Record_A('1.2.3.5'))) # Vary the type. Leave the payload as None so that we don't have to # provide non-equal values. self._equalityTest( dns.RRHeader('example.com', dns.A), dns.RRHeader('example.com', dns.A), dns.RRHeader('example.com', dns.MX)) # Probably not likely to come up. Most people use the internet. self._equalityTest( dns.RRHeader('example.com', cls=dns.IN, payload=dns.Record_A('1.2.3.4')), dns.RRHeader('example.com', cls=dns.IN, payload=dns.Record_A('1.2.3.4')), dns.RRHeader('example.com', cls=dns.CS, payload=dns.Record_A('1.2.3.4'))) # Vary the ttl self._equalityTest( dns.RRHeader('example.com', ttl=60, payload=dns.Record_A('1.2.3.4')), dns.RRHeader('example.com', ttl=60, payload=dns.Record_A('1.2.3.4')), dns.RRHeader('example.com', ttl=120, payload=dns.Record_A('1.2.3.4'))) # Vary the auth bit self._equalityTest( dns.RRHeader('example.com', auth=1, payload=dns.Record_A('1.2.3.4')), dns.RRHeader('example.com', auth=1, payload=dns.Record_A('1.2.3.4')), dns.RRHeader('example.com', auth=0, payload=dns.Record_A('1.2.3.4'))) def test_ns(self): """ Two L{dns.Record_NS} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_NS) def test_md(self): """ Two L{dns.Record_MD} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_MD) def test_mf(self): """ Two L{dns.Record_MF} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_MF) def test_cname(self): """ Two L{dns.Record_CNAME} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_CNAME) def test_mb(self): """ Two L{dns.Record_MB} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_MB) def test_mg(self): """ Two L{dns.Record_MG} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_MG) def test_mr(self): """ Two L{dns.Record_MR} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_MR) def test_ptr(self): """ Two L{dns.Record_PTR} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_PTR) def test_dname(self): """ Two L{dns.Record_MD} instances compare equal if and only if they have the same name and TTL. """ self._simpleEqualityTest(dns.Record_DNAME) def test_a(self): """ Two L{dns.Record_A} instances compare equal if and only if they have the same address and TTL. """ # Vary the TTL self._equalityTest( dns.Record_A('1.2.3.4', 5), dns.Record_A('1.2.3.4', 5), dns.Record_A('1.2.3.4', 6)) # Vary the address self._equalityTest( dns.Record_A('1.2.3.4', 5), dns.Record_A('1.2.3.4', 5), dns.Record_A('1.2.3.5', 5)) def test_soa(self): """ Two L{dns.Record_SOA} instances compare equal if and only if they have the same mname, rname, serial, refresh, minimum, expire, retry, and ttl. """ # Vary the mname self._equalityTest( dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('xname', 'rname', 123, 456, 789, 10, 20, 30)) # Vary the rname self._equalityTest( dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'xname', 123, 456, 789, 10, 20, 30)) # Vary the serial self._equalityTest( dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'rname', 1, 456, 789, 10, 20, 30)) # Vary the refresh self._equalityTest( dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'rname', 123, 1, 789, 10, 20, 30)) # Vary the minimum self._equalityTest( dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'rname', 123, 456, 1, 10, 20, 30)) # Vary the expire self._equalityTest( dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'rname', 123, 456, 789, 1, 20, 30)) # Vary the retry self._equalityTest( dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 1, 30)) # Vary the ttl self._equalityTest( dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'rname', 123, 456, 789, 10, 20, 30), dns.Record_SOA('mname', 'xname', 123, 456, 789, 10, 20, 1)) def test_null(self): """ Two L{dns.Record_NULL} instances compare equal if and only if they have the same payload and ttl. """ # Vary the payload self._equalityTest( dns.Record_NULL('foo bar', 10), dns.Record_NULL('foo bar', 10), dns.Record_NULL('bar foo', 10)) # Vary the ttl self._equalityTest( dns.Record_NULL('foo bar', 10), dns.Record_NULL('foo bar', 10), dns.Record_NULL('foo bar', 100)) def test_wks(self): """ Two L{dns.Record_WKS} instances compare equal if and only if they have the same address, protocol, map, and ttl. """ # Vary the address self._equalityTest( dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('4.3.2.1', 1, 'foo', 2)) # Vary the protocol self._equalityTest( dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('1.2.3.4', 100, 'foo', 2)) # Vary the map self._equalityTest( dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('1.2.3.4', 1, 'bar', 2)) # Vary the ttl self._equalityTest( dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('1.2.3.4', 1, 'foo', 2), dns.Record_WKS('1.2.3.4', 1, 'foo', 200)) def test_aaaa(self): """ Two L{dns.Record_AAAA} instances compare equal if and only if they have the same address and ttl. """ # Vary the address self._equalityTest( dns.Record_AAAA('1::2', 1), dns.Record_AAAA('1::2', 1), dns.Record_AAAA('2::1', 1)) # Vary the ttl self._equalityTest( dns.Record_AAAA('1::2', 1), dns.Record_AAAA('1::2', 1), dns.Record_AAAA('1::2', 10)) def test_a6(self): """ Two L{dns.Record_A6} instances compare equal if and only if they have the same prefix, prefix length, suffix, and ttl. """ # Note, A6 is crazy, I'm not sure these values are actually legal. # Hopefully that doesn't matter for this test. -exarkun # Vary the prefix length self._equalityTest( dns.Record_A6(16, '::abcd', 'example.com', 10), dns.Record_A6(16, '::abcd', 'example.com', 10), dns.Record_A6(32, '::abcd', 'example.com', 10)) # Vary the suffix self._equalityTest( dns.Record_A6(16, '::abcd', 'example.com', 10), dns.Record_A6(16, '::abcd', 'example.com', 10), dns.Record_A6(16, '::abcd:0', 'example.com', 10)) # Vary the prefix self._equalityTest( dns.Record_A6(16, '::abcd', 'example.com', 10), dns.Record_A6(16, '::abcd', 'example.com', 10), dns.Record_A6(16, '::abcd', 'example.org', 10)) # Vary the ttl self._equalityTest( dns.Record_A6(16, '::abcd', 'example.com', 10), dns.Record_A6(16, '::abcd', 'example.com', 10), dns.Record_A6(16, '::abcd', 'example.com', 100)) def test_srv(self): """ Two L{dns.Record_SRV} instances compare equal if and only if they have the same priority, weight, port, target, and ttl. """ # Vary the priority self._equalityTest( dns.Record_SRV(10, 20, 30, 'example.com', 40), dns.Record_SRV(10, 20, 30, 'example.com', 40), dns.Record_SRV(100, 20, 30, 'example.com', 40)) # Vary the weight self._equalityTest( dns.Record_SRV(10, 20, 30, 'example.com', 40), dns.Record_SRV(10, 20, 30, 'example.com', 40), dns.Record_SRV(10, 200, 30, 'example.com', 40)) # Vary the port self._equalityTest( dns.Record_SRV(10, 20, 30, 'example.com', 40), dns.Record_SRV(10, 20, 30, 'example.com', 40), dns.Record_SRV(10, 20, 300, 'example.com', 40)) # Vary the target self._equalityTest( dns.Record_SRV(10, 20, 30, 'example.com', 40), dns.Record_SRV(10, 20, 30, 'example.com', 40), dns.Record_SRV(10, 20, 30, 'example.org', 40)) # Vary the ttl self._equalityTest( dns.Record_SRV(10, 20, 30, 'example.com', 40), dns.Record_SRV(10, 20, 30, 'example.com', 40), dns.Record_SRV(10, 20, 30, 'example.com', 400)) def test_naptr(self): """ Two L{dns.Record_NAPTR} instances compare equal if and only if they have the same order, preference, flags, service, regexp, replacement, and ttl. """ # Vary the order self._equalityTest( dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12), dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12), dns.Record_NAPTR(2, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12)) # Vary the preference self._equalityTest( dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12), dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12), dns.Record_NAPTR(1, 3, "u", "sip+E2U", "/foo/bar/", "baz", 12)) # Vary the flags self._equalityTest( dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12), dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12), dns.Record_NAPTR(1, 2, "p", "sip+E2U", "/foo/bar/", "baz", 12)) # Vary the service self._equalityTest( dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12), dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12), dns.Record_NAPTR(1, 2, "u", "http", "/foo/bar/", "baz", 12)) # Vary the regexp self._equalityTest( dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12), dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12), dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/bar/foo/", "baz", 12)) # Vary the replacement self._equalityTest( dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12), dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12), dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/bar/foo/", "quux", 12)) # Vary the ttl self._equalityTest( dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12), dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/foo/bar/", "baz", 12), dns.Record_NAPTR(1, 2, "u", "sip+E2U", "/bar/foo/", "baz", 5)) def test_afsdb(self): """ Two L{dns.Record_AFSDB} instances compare equal if and only if they have the same subtype, hostname, and ttl. """ # Vary the subtype self._equalityTest( dns.Record_AFSDB(1, 'example.com', 2), dns.Record_AFSDB(1, 'example.com', 2), dns.Record_AFSDB(2, 'example.com', 2)) # Vary the hostname self._equalityTest( dns.Record_AFSDB(1, 'example.com', 2), dns.Record_AFSDB(1, 'example.com', 2), dns.Record_AFSDB(1, 'example.org', 2)) # Vary the ttl self._equalityTest( dns.Record_AFSDB(1, 'example.com', 2), dns.Record_AFSDB(1, 'example.com', 2), dns.Record_AFSDB(1, 'example.com', 3)) def test_rp(self): """ Two L{Record_RP} instances compare equal if and only if they have the same mbox, txt, and ttl. """ # Vary the mbox self._equalityTest( dns.Record_RP('alice.example.com', 'alice is nice', 10), dns.Record_RP('alice.example.com', 'alice is nice', 10), dns.Record_RP('bob.example.com', 'alice is nice', 10)) # Vary the txt self._equalityTest( dns.Record_RP('alice.example.com', 'alice is nice', 10), dns.Record_RP('alice.example.com', 'alice is nice', 10), dns.Record_RP('alice.example.com', 'alice is not nice', 10)) # Vary the ttl self._equalityTest( dns.Record_RP('alice.example.com', 'alice is nice', 10), dns.Record_RP('alice.example.com', 'alice is nice', 10), dns.Record_RP('alice.example.com', 'alice is nice', 100)) def test_hinfo(self): """ Two L{dns.Record_HINFO} instances compare equal if and only if they have the same cpu, os, and ttl. """ # Vary the cpu self._equalityTest( dns.Record_HINFO('x86-64', 'plan9', 10), dns.Record_HINFO('x86-64', 'plan9', 10), dns.Record_HINFO('i386', 'plan9', 10)) # Vary the os self._equalityTest( dns.Record_HINFO('x86-64', 'plan9', 10), dns.Record_HINFO('x86-64', 'plan9', 10), dns.Record_HINFO('x86-64', 'plan11', 10)) # Vary the ttl self._equalityTest( dns.Record_HINFO('x86-64', 'plan9', 10), dns.Record_HINFO('x86-64', 'plan9', 10), dns.Record_HINFO('x86-64', 'plan9', 100)) def test_minfo(self): """ Two L{dns.Record_MINFO} instances compare equal if and only if they have the same rmailbx, emailbx, and ttl. """ # Vary the rmailbx self._equalityTest( dns.Record_MINFO('rmailbox', 'emailbox', 10), dns.Record_MINFO('rmailbox', 'emailbox', 10), dns.Record_MINFO('someplace', 'emailbox', 10)) # Vary the emailbx self._equalityTest( dns.Record_MINFO('rmailbox', 'emailbox', 10), dns.Record_MINFO('rmailbox', 'emailbox', 10), dns.Record_MINFO('rmailbox', 'something', 10)) # Vary the ttl self._equalityTest( dns.Record_MINFO('rmailbox', 'emailbox', 10), dns.Record_MINFO('rmailbox', 'emailbox', 10), dns.Record_MINFO('rmailbox', 'emailbox', 100)) def test_mx(self): """ Two L{dns.Record_MX} instances compare equal if and only if they have the same preference, name, and ttl. """ # Vary the preference self._equalityTest( dns.Record_MX(10, 'example.org', 20), dns.Record_MX(10, 'example.org', 20), dns.Record_MX(100, 'example.org', 20)) # Vary the name self._equalityTest( dns.Record_MX(10, 'example.org', 20), dns.Record_MX(10, 'example.org', 20), dns.Record_MX(10, 'example.net', 20)) # Vary the ttl self._equalityTest( dns.Record_MX(10, 'example.org', 20), dns.Record_MX(10, 'example.org', 20), dns.Record_MX(10, 'example.org', 200)) def test_txt(self): """ Two L{dns.Record_TXT} instances compare equal if and only if they have the same data and ttl. """ # Vary the length of the data self._equalityTest( dns.Record_TXT('foo', 'bar', ttl=10), dns.Record_TXT('foo', 'bar', ttl=10), dns.Record_TXT('foo', 'bar', 'baz', ttl=10)) # Vary the value of the data self._equalityTest( dns.Record_TXT('foo', 'bar', ttl=10), dns.Record_TXT('foo', 'bar', ttl=10), dns.Record_TXT('bar', 'foo', ttl=10)) # Vary the ttl self._equalityTest( dns.Record_TXT('foo', 'bar', ttl=10), dns.Record_TXT('foo', 'bar', ttl=10), dns.Record_TXT('foo', 'bar', ttl=100)) def test_spf(self): """ L{dns.Record_SPF} records are structurally similar to L{dns.Record_TXT} records, so they are equal if and only if they have the same data and ttl. """ # Vary the length of the data self._equalityTest( dns.Record_SPF('foo', 'bar', ttl=10), dns.Record_SPF('foo', 'bar', ttl=10), dns.Record_SPF('foo', 'bar', 'baz', ttl=10)) # Vary the value of the data self._equalityTest( dns.Record_SPF('foo', 'bar', ttl=10), dns.Record_SPF('foo', 'bar', ttl=10), dns.Record_SPF('bar', 'foo', ttl=10)) # Vary the ttl self._equalityTest( dns.Record_SPF('foo', 'bar', ttl=10), dns.Record_SPF('foo', 'bar', ttl=10), dns.Record_SPF('foo', 'bar', ttl=100))
markeTIC/OCB
refs/heads/8.0
openerp/addons/base/res/res_partner.py
1
# -*- 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 re import datetime from lxml import etree import math import pytz import urlparse import openerp from openerp import tools, api from openerp.osv import osv, fields from openerp.osv.expression import get_unaccent_wrapper from openerp.tools.translate import _ ADDRESS_FORMAT_LAYOUTS = { '%(city)s %(state_code)s\n%(zip)s': """ <div class="address_format"> <field name="city" placeholder="%(city)s" style="width: 50%%"/> <field name="state_id" class="oe_no_button" placeholder="%(state)s" style="width: 47%%" options='{"no_open": true}'/> <br/> <field name="zip" placeholder="%(zip)s"/> </div> """, '%(zip)s %(city)s': """ <div class="address_format"> <field name="zip" placeholder="%(zip)s" style="width: 40%%"/> <field name="city" placeholder="%(city)s" style="width: 57%%"/> <br/> <field name="state_id" class="oe_no_button" placeholder="%(state)s" options='{"no_open": true}'/> </div> """, '%(city)s\n%(state_name)s\n%(zip)s': """ <div class="address_format"> <field name="city" placeholder="%(city)s"/> <field name="state_id" class="oe_no_button" placeholder="%(state)s" options='{"no_open": true}'/> <field name="zip" placeholder="%(zip)s"/> </div> """ } class format_address(object): @api.model def fields_view_get_address(self, arch): fmt = self.env.user.company_id.country_id.address_format or '' for k, v in ADDRESS_FORMAT_LAYOUTS.items(): if k in fmt: doc = etree.fromstring(arch) for node in doc.xpath("//div[@class='address_format']"): tree = etree.fromstring(v % {'city': _('City'), 'zip': _('ZIP'), 'state': _('State')}) for child in node.xpath(".//field"): for field in tree.xpath("//field[@name='%s']" % child.attrib.get("name")): if child.attrib.get("modifiers"): field.attrib['modifiers'] = child.attrib.get('modifiers') if child.attrib.get("on_change"): field.attrib["on_change"] = child.attrib.get("on_change") node.getparent().replace(node, tree) arch = etree.tostring(doc) break return arch @api.model def _tz_get(self): # put POSIX 'Etc/*' entries at the end to avoid confusing users - see bug 1086728 return [(tz,tz) for tz in sorted(pytz.all_timezones, key=lambda tz: tz if not tz.startswith('Etc/') else '_')] class res_partner_category(osv.Model): def name_get(self, cr, uid, ids, context=None): """ Return the categories' display name, including their direct parent by default. If ``context['partner_category_display']`` is ``'short'``, the short version of the category name (without the direct parent) is used. The default is the long version. """ if not isinstance(ids, list): ids = [ids] if context is None: context = {} if context.get('partner_category_display') == 'short': return super(res_partner_category, self).name_get(cr, uid, ids, context=context) res = [] for category in self.browse(cr, uid, ids, context=context): names = [] current = category while current: names.append(current.name) current = current.parent_id res.append((category.id, ' / '.join(reversed(names)))) return res @api.model def name_search(self, name, args=None, operator='ilike', limit=100): args = args or [] if name: # Be sure name_search is symetric to name_get name = name.split(' / ')[-1] args = [('name', operator, name)] + args categories = self.search(args, limit=limit) return categories.name_get() @api.multi def _name_get_fnc(self, field_name, arg): return dict(self.name_get()) _description = 'Partner Tags' _name = 'res.partner.category' _columns = { 'name': fields.char('Category Name', required=True, translate=True), 'parent_id': fields.many2one('res.partner.category', 'Parent Category', select=True, ondelete='cascade'), 'complete_name': fields.function(_name_get_fnc, type="char", string='Full Name'), 'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Child Categories'), 'active': fields.boolean('Active', help="The active field allows you to hide the category without removing it."), 'parent_left': fields.integer('Left parent', select=True), 'parent_right': fields.integer('Right parent', select=True), 'partner_ids': fields.many2many('res.partner', id1='category_id', id2='partner_id', string='Partners'), } _constraints = [ (osv.osv._check_recursion, 'Error ! You can not create recursive categories.', ['parent_id']) ] _defaults = { 'active': 1, } _parent_store = True _parent_order = 'name' _order = 'parent_left' class res_partner_title(osv.osv): _name = 'res.partner.title' _order = 'name' _columns = { 'name': fields.char('Title', required=True, translate=True), 'shortcut': fields.char('Abbreviation', translate=True), 'domain': fields.selection([('partner', 'Partner'), ('contact', 'Contact')], 'Domain', required=True) } _defaults = { 'domain': 'contact', } @api.model def _lang_get(self): languages = self.env['res.lang'].search([]) return [(language.code, language.name) for language in languages] # fields copy if 'use_parent_address' is checked ADDRESS_FIELDS = ('street', 'street2', 'zip', 'city', 'state_id', 'country_id') class res_partner(osv.Model, format_address): _description = 'Partner' _name = "res.partner" def _address_display(self, cr, uid, ids, name, args, context=None): res = {} for partner in self.browse(cr, uid, ids, context=context): res[partner.id] = self._display_address(cr, uid, partner, context=context) return res @api.multi def _get_tz_offset(self, name, args): return dict( (p.id, datetime.datetime.now(pytz.timezone(p.tz or 'GMT')).strftime('%z')) for p in self) @api.multi def _get_image(self, name, args): return dict((p.id, tools.image_get_resized_images(p.image)) for p in self) @api.one def _set_image(self, name, value, args): return self.write({'image': tools.image_resize_image_big(value)}) @api.multi def _has_image(self, name, args): return dict((p.id, bool(p.image)) for p in self) def _commercial_partner_compute(self, cr, uid, ids, name, args, context=None): """ Returns the partner that is considered the commercial entity of this partner. The commercial entity holds the master data for all commercial fields (see :py:meth:`~_commercial_fields`) """ result = dict.fromkeys(ids, False) for partner in self.browse(cr, uid, ids, context=context): current_partner = partner while not current_partner.is_company and current_partner.parent_id: current_partner = current_partner.parent_id result[partner.id] = current_partner.id return result def _display_name_compute(self, cr, uid, ids, name, args, context=None): context = dict(context or {}) context.pop('show_address', None) context.pop('show_address_only', None) context.pop('show_email', None) return dict(self.name_get(cr, uid, ids, context=context)) # indirections to avoid passing a copy of the overridable method when declaring the function field _commercial_partner_id = lambda self, *args, **kwargs: self._commercial_partner_compute(*args, **kwargs) _display_name = lambda self, *args, **kwargs: self._display_name_compute(*args, **kwargs) _commercial_partner_store_triggers = { 'res.partner': (lambda self,cr,uid,ids,context=None: self.search(cr, uid, [('id','child_of',ids)], context=dict(active_test=False)), ['parent_id', 'is_company'], 10) } _display_name_store_triggers = { 'res.partner': (lambda self,cr,uid,ids,context=None: self.search(cr, uid, [('id','child_of',ids)], context=dict(active_test=False)), ['parent_id', 'is_company', 'name'], 10) } _order = "display_name" _columns = { 'name': fields.char('Name', required=True, select=True), 'display_name': fields.function(_display_name, type='char', string='Name', store=_display_name_store_triggers, select=True), 'date': fields.date('Date', select=1), 'title': fields.many2one('res.partner.title', 'Title'), 'parent_id': fields.many2one('res.partner', 'Related Company', select=True), 'parent_name': fields.related('parent_id', 'name', type='char', readonly=True, string='Parent name'), 'child_ids': fields.one2many('res.partner', 'parent_id', 'Contacts', domain=[('active','=',True)]), # force "active_test" domain to bypass _search() override 'ref': fields.char('Contact Reference', select=1), 'lang': fields.selection(_lang_get, 'Language', help="If the selected language is loaded in the system, all documents related to this contact will be printed in this language. If not, it will be English."), 'tz': fields.selection(_tz_get, 'Timezone', size=64, help="The partner's timezone, used to output proper date and time values inside printed reports. " "It is important to set a value for this field. You should use the same timezone " "that is otherwise used to pick and render date and time values: your computer's timezone."), 'tz_offset': fields.function(_get_tz_offset, type='char', size=5, string='Timezone offset', invisible=True), 'user_id': fields.many2one('res.users', 'Salesperson', help='The internal user that is in charge of communicating with this contact if any.'), 'vat': fields.char('TIN', help="Tax Identification Number. Check the box if this contact is subjected to taxes. Used by the some of the legal statements."), 'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'), 'website': fields.char('Website', help="Website of Partner or Company"), 'comment': fields.text('Notes'), 'category_id': fields.many2many('res.partner.category', id1='partner_id', id2='category_id', string='Tags'), 'credit_limit': fields.float(string='Credit Limit'), 'ean13': fields.char('EAN13', size=13), 'active': fields.boolean('Active'), 'customer': fields.boolean('Customer', help="Check this box if this contact is a customer."), 'supplier': fields.boolean('Supplier', help="Check this box if this contact is a supplier. If it's not checked, purchase people will not see it when encoding a purchase order."), 'employee': fields.boolean('Employee', help="Check this box if this contact is an Employee."), 'function': fields.char('Job Position'), 'type': fields.selection([('default', 'Default'), ('invoice', 'Invoice'), ('delivery', 'Shipping'), ('contact', 'Contact'), ('other', 'Other')], 'Address Type', help="Used to select automatically the right address according to the context in sales and purchases documents."), 'street': fields.char('Street'), 'street2': fields.char('Street2'), 'zip': fields.char('Zip', size=24, change_default=True), 'city': fields.char('City'), 'state_id': fields.many2one("res.country.state", 'State', ondelete='restrict'), 'country_id': fields.many2one('res.country', 'Country', ondelete='restrict'), 'email': fields.char('Email'), 'phone': fields.char('Phone'), 'fax': fields.char('Fax'), 'mobile': fields.char('Mobile'), 'birthdate': fields.char('Birthdate'), 'is_company': fields.boolean('Is a Company', help="Check if the contact is a company, otherwise it is a person"), 'use_parent_address': fields.boolean('Use Company Address', help="Select this if you want to set company's address information for this contact"), # image: all image fields are base64 encoded and PIL-supported 'image': fields.binary("Image", help="This field holds the image used as avatar for this contact, limited to 1024x1024px"), 'image_medium': fields.function(_get_image, fnct_inv=_set_image, string="Medium-sized image", type="binary", multi="_get_image", store={ 'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10), }, help="Medium-sized image of this contact. It is automatically "\ "resized as a 128x128px image, with aspect ratio preserved. "\ "Use this field in form views or some kanban views."), 'image_small': fields.function(_get_image, fnct_inv=_set_image, string="Small-sized image", type="binary", multi="_get_image", store={ 'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10), }, help="Small-sized image of this contact. It is automatically "\ "resized as a 64x64px image, with aspect ratio preserved. "\ "Use this field anywhere a small image is required."), 'has_image': fields.function(_has_image, type="boolean"), 'company_id': fields.many2one('res.company', 'Company', select=1), 'color': fields.integer('Color Index'), 'user_ids': fields.one2many('res.users', 'partner_id', 'Users'), 'contact_address': fields.function(_address_display, type='char', string='Complete Address'), # technical field used for managing commercial fields 'commercial_partner_id': fields.function(_commercial_partner_id, type='many2one', relation='res.partner', string='Commercial Entity', store=_commercial_partner_store_triggers) } @api.model def _default_category(self): category_id = self.env.context.get('category_id', False) return [category_id] if category_id else False @api.model def _get_default_image(self, is_company, colorize=False): img_path = openerp.modules.get_module_resource( 'base', 'static/src/img', 'company_image.png' if is_company else 'avatar.png') with open(img_path, 'rb') as f: image = f.read() # colorize user avatars if not is_company: image = tools.image_colorize(image) return tools.image_resize_image_big(image.encode('base64')) def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): if (not view_id) and (view_type=='form') and context and context.get('force_email', False): view_id = self.pool['ir.model.data'].get_object_reference(cr, user, 'base', 'view_partner_simple_form')[1] res = super(res_partner,self).fields_view_get(cr, user, view_id, view_type, context, toolbar=toolbar, submenu=submenu) if view_type == 'form': res['arch'] = self.fields_view_get_address(cr, user, res['arch'], context=context) return res @api.model def _default_company(self): return self.env['res.company']._company_default_get('res.partner') _defaults = { 'active': True, 'lang': api.model(lambda self: self.env.lang), 'tz': api.model(lambda self: self.env.context.get('tz', False)), 'customer': True, 'category_id': _default_category, 'company_id': _default_company, 'color': 0, 'is_company': False, 'type': 'contact', # type 'default' is wildcard and thus inappropriate 'use_parent_address': False, 'image': False, } _constraints = [ (osv.osv._check_recursion, 'You cannot create recursive Partner hierarchies.', ['parent_id']), ] @api.one def copy(self, default=None): default = dict(default or {}) default['name'] = _('%s (copy)') % self.name return super(res_partner, self).copy(default) @api.multi def onchange_type(self, is_company): value = {'title': False} if is_company: value['use_parent_address'] = False domain = {'title': [('domain', '=', 'partner')]} else: domain = {'title': [('domain', '=', 'contact')]} return {'value': value, 'domain': domain} def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None): def value_or_id(val): """ return val or val.id if val is a browse record """ return val if isinstance(val, (bool, int, long, float, basestring)) else val.id result = {} if parent_id: if ids: partner = self.browse(cr, uid, ids[0], context=context) if partner.parent_id and partner.parent_id.id != parent_id: result['warning'] = {'title': _('Warning'), 'message': _('Changing the company of a contact should only be done if it ' 'was never correctly set. If an existing contact starts working for a new ' 'company then a new contact should be created under that new ' 'company. You can use the "Discard" button to abandon this change.')} if use_parent_address: parent = self.browse(cr, uid, parent_id, context=context) address_fields = self._address_fields(cr, uid, context=context) result['value'] = dict((key, value_or_id(parent[key])) for key in address_fields) else: result['value'] = {'use_parent_address': False} return result @api.multi def onchange_state(self, state_id): if state_id: state = self.env['res.country.state'].browse(state_id) return {'value': {'country_id': state.country_id.id}} return {} def _check_ean_key(self, cr, uid, ids, context=None): for partner_o in self.pool['res.partner'].read(cr, uid, ids, ['ean13',]): thisean=partner_o['ean13'] if thisean and thisean!='': if len(thisean)!=13: return False sum=0 for i in range(12): if not (i % 2): sum+=int(thisean[i]) else: sum+=3*int(thisean[i]) if math.ceil(sum/10.0)*10-sum!=int(thisean[12]): return False return True # _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])] def _update_fields_values(self, cr, uid, partner, fields, context=None): """ Returns dict of write() values for synchronizing ``fields`` """ values = {} for fname in fields: field = self._fields[fname] if field.type == 'one2many': raise AssertionError('One2Many fields cannot be synchronized as part of `commercial_fields` or `address fields`') if field.type == 'many2one': values[fname] = partner[fname].id if partner[fname] else False elif field.type == 'many2many': values[fname] = [(6,0,[r.id for r in partner[fname] or []])] else: values[fname] = partner[fname] return values def _address_fields(self, cr, uid, context=None): """ Returns the list of address fields that are synced from the parent when the `use_parent_address` flag is set. """ return list(ADDRESS_FIELDS) def update_address(self, cr, uid, ids, vals, context=None): address_fields = self._address_fields(cr, uid, context=context) addr_vals = dict((key, vals[key]) for key in address_fields if key in vals) if addr_vals: return super(res_partner, self).write(cr, uid, ids, addr_vals, context) def _commercial_fields(self, cr, uid, context=None): """ Returns the list of fields that are managed by the commercial entity to which a partner belongs. These fields are meant to be hidden on partners that aren't `commercial entities` themselves, and will be delegated to the parent `commercial entity`. The list is meant to be extended by inheriting classes. """ return ['vat', 'credit_limit'] def _commercial_sync_from_company(self, cr, uid, partner, context=None): """ Handle sync of commercial fields when a new parent commercial entity is set, as if they were related fields """ commercial_partner = partner.commercial_partner_id if not commercial_partner: # On child partner creation of a parent partner, # the commercial_partner_id is not yet computed commercial_partner_id = self._commercial_partner_compute( cr, uid, [partner.id], 'commercial_partner_id', [], context=context)[partner.id] commercial_partner = self.browse(cr, uid, commercial_partner_id, context=context) if commercial_partner != partner: commercial_fields = self._commercial_fields(cr, uid, context=context) sync_vals = self._update_fields_values(cr, uid, commercial_partner, commercial_fields, context=context) partner.write(sync_vals) def _commercial_sync_to_children(self, cr, uid, partner, context=None): """ Handle sync of commercial fields to descendants """ commercial_fields = self._commercial_fields(cr, uid, context=context) commercial_partner = partner.commercial_partner_id if not commercial_partner: # On child partner creation of a parent partner, # the commercial_partner_id is not yet computed commercial_partner_id = self._commercial_partner_compute( cr, uid, [partner.id], 'commercial_partner_id', [], context=context)[partner.id] commercial_partner = self.browse(cr, uid, commercial_partner_id, context=context) sync_vals = self._update_fields_values(cr, uid, commercial_partner, commercial_fields, context=context) sync_children = [c for c in partner.child_ids if not c.is_company] for child in sync_children: self._commercial_sync_to_children(cr, uid, child, context=context) return self.write(cr, uid, [c.id for c in sync_children], sync_vals, context=context) def _fields_sync(self, cr, uid, partner, update_values, context=None): """ Sync commercial fields and address fields from company and to children after create/update, just as if those were all modeled as fields.related to the parent """ # 1. From UPSTREAM: sync from parent if update_values.get('parent_id') or update_values.get('use_parent_address'): # 1a. Commercial fields: sync if parent changed if update_values.get('parent_id'): self._commercial_sync_from_company(cr, uid, partner, context=context) # 1b. Address fields: sync if parent or use_parent changed *and* both are now set if partner.parent_id and partner.use_parent_address: onchange_vals = self.onchange_address(cr, uid, [partner.id], use_parent_address=partner.use_parent_address, parent_id=partner.parent_id.id, context=context).get('value', {}) partner.update_address(onchange_vals) # 2. To DOWNSTREAM: sync children if partner.child_ids: # 2a. Commercial Fields: sync if commercial entity if partner.commercial_partner_id == partner: commercial_fields = self._commercial_fields(cr, uid, context=context) if any(field in update_values for field in commercial_fields): self._commercial_sync_to_children(cr, uid, partner, context=context) # 2b. Address fields: sync if address changed address_fields = self._address_fields(cr, uid, context=context) if any(field in update_values for field in address_fields): domain_children = [('parent_id', '=', partner.id), ('use_parent_address', '=', True)] update_ids = self.search(cr, uid, domain_children, context=context) self.update_address(cr, uid, update_ids, update_values, context=context) def _handle_first_contact_creation(self, cr, uid, partner, context=None): """ On creation of first contact for a company (or root) that has no address, assume contact address was meant to be company address """ parent = partner.parent_id address_fields = self._address_fields(cr, uid, context=context) if parent and (parent.is_company or not parent.parent_id) and len(parent.child_ids) == 1 and \ any(partner[f] for f in address_fields) and not any(parent[f] for f in address_fields): addr_vals = self._update_fields_values(cr, uid, partner, address_fields, context=context) parent.update_address(addr_vals) if not parent.is_company: parent.write({'is_company': True}) def unlink(self, cr, uid, ids, context=None): orphan_contact_ids = self.search(cr, uid, [('parent_id', 'in', ids), ('id', 'not in', ids), ('use_parent_address', '=', True)], context=context) if orphan_contact_ids: # no longer have a parent address self.write(cr, uid, orphan_contact_ids, {'use_parent_address': False}, context=context) return super(res_partner, self).unlink(cr, uid, ids, context=context) def _clean_website(self, website): (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(website) if not scheme: if not netloc: netloc, path = path, '' website = urlparse.urlunparse(('http', netloc, path, params, query, fragment)) return website @api.multi def write(self, vals): # res.partner must only allow to set the company_id of a partner if it # is the same as the company of all users that inherit from this partner # (this is to allow the code from res_users to write to the partner!) or # if setting the company_id to False (this is compatible with any user # company) if vals.get('website'): vals['website'] = self._clean_website(vals['website']) if vals.get('company_id'): company = self.env['res.company'].browse(vals['company_id']) for partner in self: if partner.user_ids: companies = set(user.company_id for user in partner.user_ids) if len(companies) > 1 or company not in companies: raise osv.except_osv(_("Warning"),_("You can not change the company as the partner/user has multiple user linked with different companies.")) result = super(res_partner, self).write(vals) for partner in self: if any(u.has_group('base.group_user') for u in partner.user_ids): self.env['res.users'].check_access_rights('write') self._fields_sync(partner, vals) return result @api.model def create(self, vals): if vals.get('website'): vals['website'] = self._clean_website(vals['website']) partner = super(res_partner, self).create(vals) self._fields_sync(partner, vals) self._handle_first_contact_creation(partner) return partner def open_commercial_entity(self, cr, uid, ids, context=None): """ Utility method used to add an "Open Company" button in partner views """ partner = self.browse(cr, uid, ids[0], context=context) return {'type': 'ir.actions.act_window', 'res_model': 'res.partner', 'view_mode': 'form', 'res_id': partner.commercial_partner_id.id, 'target': 'new', 'flags': {'form': {'action_buttons': True}}} def open_parent(self, cr, uid, ids, context=None): """ Utility method used to add an "Open Parent" button in partner views """ partner = self.browse(cr, uid, ids[0], context=context) return {'type': 'ir.actions.act_window', 'res_model': 'res.partner', 'view_mode': 'form', 'res_id': partner.parent_id.id, 'target': 'new', 'flags': {'form': {'action_buttons': True}}} def name_get(self, cr, uid, ids, context=None): if context is None: context = {} if isinstance(ids, (int, long)): ids = [ids] res = [] for record in self.browse(cr, uid, ids, context=context): name = record.name if record.parent_id and not record.is_company: name = "%s, %s" % (record.parent_name, name) if context.get('show_address_only'): name = self._display_address(cr, uid, record, without_company=True, context=context) if context.get('show_address'): name = name + "\n" + self._display_address(cr, uid, record, without_company=True, context=context) name = name.replace('\n\n','\n') name = name.replace('\n\n','\n') if context.get('show_email') and record.email: name = "%s <%s>" % (name, record.email) res.append((record.id, name)) return res def _parse_partner_name(self, text, context=None): """ Supported syntax: - 'Raoul <raoul@grosbedon.fr>': will find name and email address - otherwise: default, everything is set as the name """ emails = tools.email_split(text.replace(' ',',')) if emails: email = emails[0] name = text[:text.index(email)].replace('"', '').replace('<', '').strip() else: name, email = text, '' return name, email def name_create(self, cr, uid, name, context=None): """ Override of orm's name_create method for partners. The purpose is to handle some basic formats to create partners using the name_create. If only an email address is received and that the regex cannot find a name, the name will have the email value. If 'force_email' key in context: must find the email address. """ if context is None: context = {} name, email = self._parse_partner_name(name, context=context) if context.get('force_email') and not email: raise osv.except_osv(_('Warning'), _("Couldn't create contact without email address!")) if not name and email: name = email rec_id = self.create(cr, uid, {self._rec_name: name or email, 'email': email or False}, context=context) return self.name_get(cr, uid, [rec_id], context)[0] def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None): """ Override search() to always show inactive children when searching via ``child_of`` operator. The ORM will always call search() with a simple domain of the form [('parent_id', 'in', [ids])]. """ # a special ``domain`` is set on the ``child_ids`` o2m to bypass this logic, as it uses similar domain expressions if len(args) == 1 and len(args[0]) == 3 and args[0][:2] == ('parent_id','in') \ and args[0][2] != [False]: context = dict(context or {}, active_test=False) return super(res_partner, self)._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count, access_rights_uid=access_rights_uid) def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100): if not args: args = [] if name and operator in ('=', 'ilike', '=ilike', 'like', '=like'): self.check_access_rights(cr, uid, 'read') where_query = self._where_calc(cr, uid, args, context=context) self._apply_ir_rules(cr, uid, where_query, 'read', context=context) from_clause, where_clause, where_clause_params = where_query.get_sql() where_str = where_clause and (" WHERE %s AND " % where_clause) or ' WHERE ' # search on the name of the contacts and of its company search_name = name if operator in ('ilike', 'like'): search_name = '%%%s%%' % name if operator in ('=ilike', '=like'): operator = operator[1:] unaccent = get_unaccent_wrapper(cr) query = """SELECT id FROM res_partner {where} ({email} {operator} {percent} OR {display_name} {operator} {percent}) ORDER BY {display_name} """.format(where=where_str, operator=operator, email=unaccent('email'), display_name=unaccent('display_name'), percent=unaccent('%s')) where_clause_params += [search_name, search_name] if limit: query += ' limit %s' where_clause_params.append(limit) cr.execute(query, where_clause_params) ids = map(lambda x: x[0], cr.fetchall()) if ids: return self.name_get(cr, uid, ids, context) else: return [] return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit) def find_or_create(self, cr, uid, email, context=None): """ Find a partner with the given ``email`` or use :py:method:`~.name_create` to create one :param str email: email-like string, which should contain at least one email, e.g. ``"Raoul Grosbedon <r.g@grosbedon.fr>"``""" assert email, 'an email is required for find_or_create to work' emails = tools.email_split(email) if emails: email = emails[0] ids = self.search(cr, uid, [('email','=ilike',email)], context=context) if not ids: return self.name_create(cr, uid, email, context=context)[0] return ids[0] def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None): partners = self.browse(cr, uid, ids) for partner in partners: if partner.email: tools.email_send(email_from, [partner.email], subject, body, on_error) return True def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''): while len(ids): self.pool['ir.cron'].create(cr, uid, { 'name': 'Send Partner Emails', 'user_id': uid, 'model': 'res.partner', 'function': '_email_send', 'args': repr([ids[:16], email_from, subject, body, on_error]) }) ids = ids[16:] return True def address_get(self, cr, uid, ids, adr_pref=None, context=None): """ Find contacts/addresses of the right type(s) by doing a depth-first-search through descendants within company boundaries (stop at entities flagged ``is_company``) then continuing the search at the ancestors that are within the same company boundaries. Defaults to partners of type ``'default'`` when the exact type is not found, or to the provided partner itself if no type ``'default'`` is found either. """ adr_pref = set(adr_pref or []) if 'default' not in adr_pref: adr_pref.add('default') result = {} visited = set() if isinstance(ids, (int, long)): ids = [ids] for partner in self.browse(cr, uid, filter(None, ids), context=context): current_partner = partner while current_partner: to_scan = [current_partner] # Scan descendants, DFS while to_scan: record = to_scan.pop(0) visited.add(record) if record.type in adr_pref and not result.get(record.type): result[record.type] = record.id if len(result) == len(adr_pref): return result to_scan = [c for c in record.child_ids if c not in visited if not c.is_company] + to_scan # Continue scanning at ancestor if current_partner is not a commercial entity if current_partner.is_company or not current_partner.parent_id: break current_partner = current_partner.parent_id # default to type 'default' or the partner itself default = result.get('default', ids and ids[0] or False) for adr_type in adr_pref: result[adr_type] = result.get(adr_type) or default return result def view_header_get(self, cr, uid, view_id, view_type, context): res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context) if res: return res if not context.get('category_id', False): return False return _('Partners: ')+self.pool['res.partner.category'].browse(cr, uid, context['category_id'], context).name @api.model @api.returns('self') def main_partner(self): ''' Return the main partner ''' return self.env.ref('base.main_partner') def _display_address(self, cr, uid, address, without_company=False, context=None): ''' The purpose of this function is to build and return an address formatted accordingly to the standards of the country where it belongs. :param address: browse record of the res.partner to format :returns: the address formatted in a display that fit its country habits (or the default ones if not country is specified) :rtype: string ''' # get the information that will be injected into the display format # get the address format address_format = address.country_id.address_format or \ "%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s" args = { 'state_code': address.state_id.code or '', 'state_name': address.state_id.name or '', 'country_code': address.country_id.code or '', 'country_name': address.country_id.name or '', 'company_name': address.parent_name or '', } for field in self._address_fields(cr, uid, context=context): args[field] = getattr(address, field) or '' if without_company: args['company_name'] = '' elif address.parent_id: address_format = '%(company_name)s\n' + address_format display_address = address_format % args return re.sub('\n[\s,]*\n+', '\n', display_address.strip()) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
jeffery9/mixprint_addons
refs/heads/master
project_timesheet/__init__.py
441
# -*- 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/>. # ############################################################################## import project_timesheet import report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Sinar/mapit
refs/heads/master
mapit_gb/management/__init__.py
12133432
ayesandarmoe/microblog_flask_tutorial
refs/heads/master
flask/lib/python2.7/site-packages/migrate/versioning/templates/repository/pylons/versions/__init__.py
12133432
flotre/sickbeard-vfvo
refs/heads/master
lib/tidysub/__init__.py
12133432
pathway27/servo
refs/heads/master
tests/wpt/css-tests/tools/sslutils/openssl.py
253
import functools import os import shutil import subprocess import tempfile from datetime import datetime class OpenSSL(object): def __init__(self, logger, binary, base_path, conf_path, hosts, duration, base_conf_path=None): """Context manager for interacting with OpenSSL. Creates a config file for the duration of the context. :param logger: stdlib logger or python structured logger :param binary: path to openssl binary :param base_path: path to directory for storing certificates :param conf_path: path for configuration file storing configuration data :param hosts: list of hosts to include in configuration (or None if not generating host certificates) :param duration: Certificate duration in days""" self.base_path = base_path self.binary = binary self.conf_path = conf_path self.base_conf_path = base_conf_path self.logger = logger self.proc = None self.cmd = [] self.hosts = hosts self.duration = duration def __enter__(self): with open(self.conf_path, "w") as f: f.write(get_config(self.base_path, self.hosts, self.duration)) return self def __exit__(self, *args, **kwargs): os.unlink(self.conf_path) def log(self, line): if hasattr(self.logger, "process_output"): self.logger.process_output(self.proc.pid if self.proc is not None else None, line.decode("utf8", "replace"), command=" ".join(self.cmd)) else: self.logger.debug(line) def __call__(self, cmd, *args, **kwargs): """Run a command using OpenSSL in the current context. :param cmd: The openssl subcommand to run :param *args: Additional arguments to pass to the command """ self.cmd = [self.binary, cmd] if cmd != "x509": self.cmd += ["-config", self.conf_path] self.cmd += list(args) env = os.environ.copy() if self.base_conf_path is not None: env["OPENSSL_CONF"] = self.base_conf_path.encode("utf8") self.proc = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env) stdout, stderr = self.proc.communicate() self.log(stdout) if self.proc.returncode != 0: raise subprocess.CalledProcessError(self.proc.returncode, self.cmd, output=stdout) self.cmd = [] self.proc = None return stdout def make_subject(common_name, country=None, state=None, locality=None, organization=None, organization_unit=None): args = [("country", "C"), ("state", "ST"), ("locality", "L"), ("organization", "O"), ("organization_unit", "OU"), ("common_name", "CN")] rv = [] for var, key in args: value = locals()[var] if value is not None: rv.append("/%s=%s" % (key, value.replace("/", "\\/"))) return "".join(rv) def make_alt_names(hosts): rv = [] for name in hosts: rv.append("DNS:%s" % name) return ",".join(rv) def get_config(root_dir, hosts, duration=30): if hosts is None: san_line = "" else: san_line = "subjectAltName = %s" % make_alt_names(hosts) if os.path.sep == "\\": # This seems to be needed for the Shining Light OpenSSL on # Windows, at least. root_dir = root_dir.replace("\\", "\\\\") rv = """[ ca ] default_ca = CA_default [ CA_default ] dir = %(root_dir)s certs = $dir new_certs_dir = $certs crl_dir = $dir%(sep)scrl database = $dir%(sep)sindex.txt private_key = $dir%(sep)scakey.pem certificate = $dir%(sep)scacert.pem serial = $dir%(sep)sserial crldir = $dir%(sep)scrl crlnumber = $dir%(sep)scrlnumber crl = $crldir%(sep)scrl.pem RANDFILE = $dir%(sep)sprivate%(sep)s.rand x509_extensions = usr_cert name_opt = ca_default cert_opt = ca_default default_days = %(duration)d default_crl_days = %(duration)d default_md = sha256 preserve = no policy = policy_anything copy_extensions = copy [ policy_anything ] countryName = optional stateOrProvinceName = optional localityName = optional organizationName = optional organizationalUnitName = optional commonName = supplied emailAddress = optional [ req ] default_bits = 2048 default_keyfile = privkey.pem distinguished_name = req_distinguished_name attributes = req_attributes x509_extensions = v3_ca # Passwords for private keys if not present they will be prompted for # input_password = secret # output_password = secret string_mask = utf8only req_extensions = v3_req [ req_distinguished_name ] countryName = Country Name (2 letter code) countryName_default = AU countryName_min = 2 countryName_max = 2 stateOrProvinceName = State or Province Name (full name) stateOrProvinceName_default = localityName = Locality Name (eg, city) 0.organizationName = Organization Name 0.organizationName_default = Web Platform Tests organizationalUnitName = Organizational Unit Name (eg, section) #organizationalUnitName_default = commonName = Common Name (e.g. server FQDN or YOUR name) commonName_max = 64 emailAddress = Email Address emailAddress_max = 64 [ req_attributes ] [ usr_cert ] basicConstraints=CA:false subjectKeyIdentifier=hash authorityKeyIdentifier=keyid,issuer [ v3_req ] basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment extendedKeyUsage = serverAuth %(san_line)s [ v3_ca ] basicConstraints = CA:true subjectKeyIdentifier=hash authorityKeyIdentifier=keyid:always,issuer:always keyUsage = keyCertSign """ % {"root_dir": root_dir, "san_line": san_line, "duration": duration, "sep": os.path.sep.replace("\\", "\\\\")} return rv class OpenSSLEnvironment(object): ssl_enabled = True def __init__(self, logger, openssl_binary="openssl", base_path=None, password="web-platform-tests", force_regenerate=False, duration=30, base_conf_path=None): """SSL environment that creates a local CA and host certificate using OpenSSL. By default this will look in base_path for existing certificates that are still valid and only create new certificates if there aren't any. This behaviour can be adjusted using the force_regenerate option. :param logger: a stdlib logging compatible logger or mozlog structured logger :param openssl_binary: Path to the OpenSSL binary :param base_path: Path in which certificates will be stored. If None, a temporary directory will be used and removed when the server shuts down :param password: Password to use :param force_regenerate: Always create a new certificate even if one already exists. """ self.logger = logger self.temporary = False if base_path is None: base_path = tempfile.mkdtemp() self.temporary = True self.base_path = os.path.abspath(base_path) self.password = password self.force_regenerate = force_regenerate self.duration = duration self.base_conf_path = base_conf_path self.path = None self.binary = openssl_binary self.openssl = None self._ca_cert_path = None self._ca_key_path = None self.host_certificates = {} def __enter__(self): if not os.path.exists(self.base_path): os.makedirs(self.base_path) path = functools.partial(os.path.join, self.base_path) with open(path("index.txt"), "w"): pass with open(path("serial"), "w") as f: f.write("01") self.path = path return self def __exit__(self, *args, **kwargs): if self.temporary: shutil.rmtree(self.base_path) def _config_openssl(self, hosts): conf_path = self.path("openssl.cfg") return OpenSSL(self.logger, self.binary, self.base_path, conf_path, hosts, self.duration, self.base_conf_path) def ca_cert_path(self): """Get the path to the CA certificate file, generating a new one if needed""" if self._ca_cert_path is None and not self.force_regenerate: self._load_ca_cert() if self._ca_cert_path is None: self._generate_ca() return self._ca_cert_path def _load_ca_cert(self): key_path = self.path("cakey.pem") cert_path = self.path("cacert.pem") if self.check_key_cert(key_path, cert_path, None): self.logger.info("Using existing CA cert") self._ca_key_path, self._ca_cert_path = key_path, cert_path def check_key_cert(self, key_path, cert_path, hosts): """Check that a key and cert file exist and are valid""" if not os.path.exists(key_path) or not os.path.exists(cert_path): return False with self._config_openssl(hosts) as openssl: end_date_str = openssl("x509", "-noout", "-enddate", "-in", cert_path).split("=", 1)[1].strip() # Not sure if this works in other locales end_date = datetime.strptime(end_date_str, "%b %d %H:%M:%S %Y %Z") # Should have some buffer here e.g. 1 hr if end_date < datetime.now(): return False #TODO: check the key actually signed the cert. return True def _generate_ca(self): path = self.path self.logger.info("Generating new CA in %s" % self.base_path) key_path = path("cakey.pem") req_path = path("careq.pem") cert_path = path("cacert.pem") with self._config_openssl(None) as openssl: openssl("req", "-batch", "-new", "-newkey", "rsa:2048", "-keyout", key_path, "-out", req_path, "-subj", make_subject("web-platform-tests"), "-passout", "pass:%s" % self.password) openssl("ca", "-batch", "-create_serial", "-keyfile", key_path, "-passin", "pass:%s" % self.password, "-selfsign", "-extensions", "v3_ca", "-in", req_path, "-out", cert_path) os.unlink(req_path) self._ca_key_path, self._ca_cert_path = key_path, cert_path def host_cert_path(self, hosts): """Get a tuple of (private key path, certificate path) for a host, generating new ones if necessary. hosts must be a list of all hosts to appear on the certificate, with the primary hostname first.""" hosts = tuple(hosts) if hosts not in self.host_certificates: if not self.force_regenerate: key_cert = self._load_host_cert(hosts) else: key_cert = None if key_cert is None: key, cert = self._generate_host_cert(hosts) else: key, cert = key_cert self.host_certificates[hosts] = key, cert return self.host_certificates[hosts] def _load_host_cert(self, hosts): host = hosts[0] key_path = self.path("%s.key" % host) cert_path = self.path("%s.pem" % host) # TODO: check that this cert was signed by the CA cert if self.check_key_cert(key_path, cert_path, hosts): self.logger.info("Using existing host cert") return key_path, cert_path def _generate_host_cert(self, hosts): host = hosts[0] if self._ca_key_path is None: self._generate_ca() ca_key_path = self._ca_key_path assert os.path.exists(ca_key_path) path = self.path req_path = path("wpt.req") cert_path = path("%s.pem" % host) key_path = path("%s.key" % host) self.logger.info("Generating new host cert") with self._config_openssl(hosts) as openssl: openssl("req", "-batch", "-newkey", "rsa:2048", "-keyout", key_path, "-in", ca_key_path, "-nodes", "-out", req_path) openssl("ca", "-batch", "-in", req_path, "-passin", "pass:%s" % self.password, "-subj", make_subject(host), "-out", cert_path) os.unlink(req_path) return key_path, cert_path
MaximeBiset/care4care
refs/heads/master
news/models.py
1
# -*- coding: utf-8 -*- from django.db import models from main.models import User from django.template.defaultfilters import slugify from django.utils.translation import ugettext as _ from django.utils.translation import ugettext_lazy as __ # Create your models here. class News(models.Model): """ Model descripting the news system """ titre = models.CharField(max_length=250, null=False, blank=False, verbose_name=__("Titre de l'article")) slug = models.SlugField() corps = models.TextField(__("Corps de l'article")) date_creation = models.DateTimeField(auto_now_add=True, editable=False) date_debut = models.DateTimeField(__("Date de publication désirée")) date_fin = models.DateTimeField(__("Date de fin de publication (laisser vide si aucune expiration voulue)"), blank=True, null=True) auteur = models.ForeignKey(User, blank=True, null=True) visible = models.BooleanField(default=False) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.titre) super(News, self).save(*args, **kwargs) def __str__(self): return self.titre @models.permalink def get_absolute_url(self): return ('news_read', (), { 'id' : self.id, 'slug' : self.slug,}) @models.permalink def get_absolute_modify_url(self): return ('news_modify', (), { 'id' : self.id, 'slug' : self.slug,}) class Meta: ordering = ['-date_debut']
tinkerinestudio/Tinkerine-Suite
refs/heads/master
TinkerineSuite/python/Lib/lib2to3/fixes/fix_exec.py
326
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for exec. This converts usages of the exec statement into calls to a built-in exec() function. exec code in ns1, ns2 -> exec(code, ns1, ns2) """ # Local imports from .. import pytree from .. import fixer_base from ..fixer_util import Comma, Name, Call class FixExec(fixer_base.BaseFix): BM_compatible = True PATTERN = """ exec_stmt< 'exec' a=any 'in' b=any [',' c=any] > | exec_stmt< 'exec' (not atom<'(' [any] ')'>) a=any > """ def transform(self, node, results): assert results syms = self.syms a = results["a"] b = results.get("b") c = results.get("c") args = [a.clone()] args[0].prefix = "" if b is not None: args.extend([Comma(), b.clone()]) if c is not None: args.extend([Comma(), c.clone()]) return Call(Name(u"exec"), args, prefix=node.prefix)
astrofra/amiga-memories
refs/heads/master
app/3rd_parties/marytts-5.0/doc/examples/client/maryclient-http.py
1
#!/usr/bin/env python import httplib, urllib # A basic mary client in Python, # kindly donated to the MARY TTS project # by Hugh Sasse. Thanks Hugh! # A very basic Python class for accessing # the MARY TTS system using the modern # HTTP server. # Warning, this is probably ghastly Python, # most of my time of late has been with # other languages, so I'm not up to date # with all the stylistic conventions of # modern Python. # This does seem to work OK though. class maryclient: """A basic handler for MARY-TTS HTTP clients At present, there is no checking for allowed voices, locales, and so on. Most of the useful parameters can be accessed by get_ and set_ methods. Relying on winsound, this is Windows specific. """ def __init__(self): """Set up useful defaults (for people in England, anyway)""" self.host = "127.0.0.1" self.port = 59125 self.input_type = "TEXT" self.output_type = "AUDIO" self.audio = "WAVE_FILE" self.locale = "en_GB" self.voice = "dfki-prudence-hsmm" def set_host(self, a_host): """Set the host for the TTS server.""" self.host = a_host def get_host(self): """Get the host for the TTS server.""" self.host def set_port(self, a_port): """Set the port for the TTS server.""" self.port = a_port def get_port(self): """Get the port for the TTS server.""" self.port def set_input_type(self, type): """Set the type of input being supplied to the TTS server (such as 'TEXT').""" self.input_type = type def get_input_type(self): """Get the type of input being supplied to the TTS server (such as 'TEXT').""" self.input_type def set_output_type(self, type): """Set the type of input being supplied to the TTS server (such as 'AUDIO').""" self.output_type = type def get_output_type(self): """Get the type of input being supplied to the TTS server (such as "AUDIO").""" self.output_type def set_locale(self, a_locale): """Set the locale (such as "en_GB").""" self.locale = a_locale def get_locale(self): """Get the locale (such as "en_GB").""" self.locale def set_audio(self, audio_type): """Set the audio type for playback (such as "WAVE_FILE").""" self.audio = audio_type def get_audio(self): """Get the audio type for playback (such as "WAVE_FILE").""" self.audio def set_voice(self, a_voice): """Set the voice to speak with (such as "dfki-prudence-hsmm").""" self.voice = a_voice def get_voice(self): """Get the voice to speak with (such as "dfki-prudence-hsmm").""" self.voice def generate(self, message): """Given a message in message, return a response in the appropriate format.""" raw_params = {"INPUT_TEXT": message, "INPUT_TYPE": self.input_type, "OUTPUT_TYPE": self.output_type, "LOCALE": self.locale, "AUDIO": self.audio, "VOICE": self.voice, } params = urllib.urlencode(raw_params) headers = {} # Open connection to self.host, self.port. conn = httplib.HTTPConnection(self.host, self.port) # conn.set_debuglevel(5) conn.request("POST", "/process", params, headers) response = conn.getresponse() if response.status != 200: print response.getheaders() raise RuntimeError("{0}: {1}".format(response.status, response.reason)) return response.read() # If this is invoked as a program, just give # a greeting to show it is working. # The platform specific code is moved to this # part so that this file may be imported without # bringing platform specific code in. if __name__ == "__main__": # For handling command line arguments: import sys import platform # check we are on Windows: system = platform.system().lower() if (system == "windows"): import winsound class Player: def __init__(self): pass def play(self, a_sound): winsound.PlaySound(a_sound, winsound.SND_MEMORY) #if ("cygwin" in system): else: # Not sure how to do audio on cygwin, # portably for python. So have a sound # player class that doesn't play sounds. # A null object, if you like. class Player: def __init__(self): pass def play(self, a_sound): print("Here I would play a sound if I knew how") pass # Probably want to parse arguments to # set the voice, etc., here client = maryclient() client.set_audio("WAVE_FILE") # for example player = Player() the_sound = client.generate("hello from Mary Text to Speech, with Python.") if client.output_type == "AUDIO": player.play(the_sound) # vi:set sw=4 et:
pduval/jmjproj
refs/heads/master
jmproj/views.py
1
from pyramid.response import Response from pyramid.view import view_config from pyramid.httpexceptions import HTTPMovedPermanently from sqlalchemy.exc import DBAPIError from .models import ( DBSession, CompteRendu, ) import datetime @view_config(route_name="home", renderer='jmproj:templates/all_cr.mako') def liste_comptes_rendus(request): try: compte_rendus = DBSession.query(CompteRendu).order_by("date_ecriture") projets = [row[0] for row in DBSession.query(CompteRendu).with_entities(CompteRendu.projet).distinct().all()] projet = request.params.get("projet", "") cr_prefix =request.params.get("cr_prefix","") if projet: compte_rendus = compte_rendus.filter_by(projet=projet); if cr_prefix: compte_rendus = compte_rendus.filter(CompteRendu.compte_rendu.startswith(cr_prefix.strip())) return { "comptes_rendus":compte_rendus, "total":compte_rendus.count(), "projet":projet, "cr_prefix":cr_prefix, "project":"jmproj", "projets":projets } except DBAPIError: return Response(conn_err_msg, content_type='text/plain', status_int=500) @view_config(name='add', request_method="POST", renderer='jmproj:templates/all_cr.mako') def add(request): cr = request.params.get("compte_rendu",None) projet = request.params.get("projet",None) nouveau_cr = CompteRendu(compte_rendu=cr, projet=projet,date_ecriture=datetime.datetime.utcnow()) DBSession.add(nouveau_cr) DBSession.commit() return HTTPMovedPermanently(location="/") conn_err_msg = """\ Pyramid is having a problem using your SQL database. The problem might be caused by one of the following things: 1. You may need to run the "initialize_jmproj_db" script to initialize your database tables. Check your virtual environment's "bin" directory for this script and try to run it. 2. Your database server may not be running. Check that the database server referred to by the "sqlalchemy.url" setting in your "development.ini" file is running. After you fix the problem, please restart the Pyramid application to try it again. """
ptroja/spark2014
refs/heads/master
testsuite/gnatprove/tests/TU__type_declarations_illegal/test.py
10
from test_support import * prove_all(opt=["-cargs", "-gnatf"])
paolodedios/tensorflow
refs/heads/master
tensorflow/python/ops/nccl_ops_test.py
8
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for nccl ops. See also the cc test for nccl_communicator.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from functools import partial import numpy as np from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradients from tensorflow.python.ops import nccl_ops from tensorflow.python.platform import test def _DeviceTensors(tensors, devices): res = [] for t, d in zip(tensors, devices): with ops.device(d): res.append(array_ops.identity(t)) return res def _NcclAllReduce(nccl_fun, tensors, devices): return nccl_fun(_DeviceTensors(tensors, devices)) def _NcclReduce(nccl_fun, tensors, devices): receiver = np.random.randint(0, len(devices)) with ops.device(devices[receiver]): return [nccl_fun(_DeviceTensors(tensors, devices))] def _NcclBroadcast(tensors, devices): sender = np.random.randint(0, len(devices)) with ops.device(devices[sender]): tensor = array_ops.identity(tensors[0]) broadcast = nccl_ops.broadcast(tensor) return _DeviceTensors([broadcast] * len(devices), devices) class NcclTestCase(test.TestCase): def _Test(self, nccl_reduce, numpy_fn, device_sets=(['/device:GPU:1', '/device:GPU:2', '/device:GPU:0'], ['/device:GPU:1', '/device:GPU:0'])): """Tests that nccl_reduce does the same as reduction with numpy_fn. Args: nccl_reduce: A function taking a list of tensors and a list of devices, and returns a list of reduced tensors and a list of ops to perform the reduction. numpy_fn: A function taking two tensors and returning the reduction of the two. device_sets: Tuple of virtual devices to run test on. """ for dtype in [np.float16, np.float32, np.int32, np.int64, np.float64]: # Create session inside outer loop to test use of # same communicator across multiple sessions. with self.test_session(): for devices in device_sets: shape = (3, 4) random = (np.random.random_sample(shape) - .5) * 1024 tensors = [] for _ in devices: tensors.append(random.astype(dtype)) np_ans = tensors[0] for t in tensors[1:]: np_ans = numpy_fn(np_ans, t) reduce_tensors = nccl_reduce(tensors, devices) self.assertNotEmpty(reduce_tensors) # Test shape inference. for r in reduce_tensors: self.assertEqual(shape, r.get_shape()) result_tensors = [array_ops.identity(t) for t in reduce_tensors] # Check GPU availability *after* creating session, see b/68975239. if not test.is_gpu_available(): # If no GPU is available, only test graph construction. continue # Test execution and results. for t in self.evaluate(result_tensors): self.assertAllClose(t, np_ans) def _TestGradient(self, nccl_reduce, numpy_fn): """Tests the gradient of nccl_reduce. Args: nccl_reduce: A function taking a list of tensors and a list of devices, and returns a list of reduced tensors and a list of ops to perform the reduction. numpy_fn: A function taking two tensors and returning the gradient of the reduction of the two. """ def _Gradient(tensors, devices): inputs = [array_ops.placeholder(t.dtype, t.shape) for t in tensors] reduce_tensors = nccl_reduce(inputs, devices) losses = _DeviceTensors(tensors, [t.device for t in reduce_tensors]) grads = gradients.gradients( reduce_tensors, inputs, losses, colocate_gradients_with_ops=True) return [g for g in grads if g is not None] self._Test(_Gradient, numpy_fn) class AllReduceTest(NcclTestCase): def testAllReduce(self): self._Test(partial(_NcclAllReduce, nccl_ops.all_sum), lambda x, y: x + y) self._Test(partial(_NcclAllReduce, nccl_ops.all_prod), lambda x, y: x * y) self._Test(partial(_NcclAllReduce, nccl_ops.all_min), np.minimum) self._Test(partial(_NcclAllReduce, nccl_ops.all_max), np.maximum) def testAllSumGrad(self): self._TestGradient( partial(_NcclAllReduce, nccl_ops.all_sum), lambda x, y: x + y) def testErrors(self): with self.assertRaisesRegex(ValueError, 'Device assignment required'): nccl_ops.all_sum([array_ops.identity(np.random.random_sample((3, 4)))]) with self.assertRaisesRegex(ValueError, 'Must pass >0 tensors'): nccl_ops.all_sum([]) class SingleReduceTest(NcclTestCase): def testSum(self): self._Test(partial(_NcclReduce, nccl_ops.reduce_sum), lambda x, y: x + y) def testSumGrad(self): self._TestGradient(partial(_NcclReduce, nccl_ops.reduce_sum), lambda x, y: x) class BroadcastTest(NcclTestCase): def testBroadcast(self): self._Test(_NcclBroadcast, lambda x, y: x) def testBroadcastSingleDevice(self): # Broadcasts on a single device are removed completely during rewrite. self._Test(_NcclBroadcast, lambda x, y: x, (['/device:GPU:0', '/device:GPU:0'],)) def testBroadcastToCpuError(self): try: # Broadcasts to CPU is not supported. self._Test(_NcclBroadcast, lambda x, y: x, (['/device:GPU:0', '/device:CPU:0'],)) except errors.NotFoundError as e: self.assertRegex( str(e), "No registered '_NcclBroadcastRecv' OpKernel for CPU devices") else: # Session isn't executed when no GPU is available. if test.is_gpu_available(): self.fail("Didn't raise NotFoundError trying to broadcast to CPU") class CombinedTest(NcclTestCase): """Test all-reduce vs. single-reduce plus broadcast in one session.run.""" def _Combined(self, tensors, devices): all_reduce_tensors = _NcclAllReduce(nccl_ops.all_sum, tensors, devices) single_reduce_tensors = _NcclReduce(nccl_ops.reduce_sum, tensors, devices) broadcast_tensors = _NcclBroadcast(single_reduce_tensors, devices) return all_reduce_tensors + broadcast_tensors def testCombined(self): self._Test(self._Combined, lambda x, y: x + y) if __name__ == '__main__': test.main()
kornicameister/ansible-modules-extras
refs/heads/monasca
web_infrastructure/ejabberd_user.py
42
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2013, Peter Sprygada <sprygada@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # DOCUMENTATION = ''' --- module: ejabberd_user version_added: "1.5" author: "Peter Sprygada (@privateip)" short_description: Manages users for ejabberd servers requirements: - ejabberd with mod_admin_extra description: - This module provides user management for ejabberd servers options: username: description: - the name of the user to manage required: true host: description: - the ejabberd host associated with this username required: true password: description: - the password to assign to the username required: false logging: description: - enables or disables the local syslog facility for this module required: false default: false choices: [ 'true', 'false', 'yes', 'no' ] state: description: - describe the desired state of the user to be managed required: false default: 'present' choices: [ 'present', 'absent' ] notes: - Password parameter is required for state == present only - Passwords must be stored in clear text for this release - The ejabberd configuration file must include mod_admin_extra as a module. ''' EXAMPLES = ''' Example playbook entries using the ejabberd_user module to manage users state. tasks: - name: create a user if it does not exists action: ejabberd_user username=test host=server password=password - name: delete a user if it exists action: ejabberd_user username=test host=server state=absent ''' import syslog from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils.basic import * class EjabberdUserException(Exception): """ Base exeption for EjabberdUser class object """ pass class EjabberdUser(object): """ This object represents a user resource for an ejabberd server. The object manages user creation and deletion using ejabberdctl. The following commands are currently supported: * ejabberdctl register * ejabberdctl deregister """ def __init__(self, module): self.module = module self.logging = module.params.get('logging') self.state = module.params.get('state') self.host = module.params.get('host') self.user = module.params.get('username') self.pwd = module.params.get('password') @property def changed(self): """ This method will check the current user and see if the password has changed. It will return True if the user does not match the supplied credentials and False if it does not """ try: options = [self.user, self.host, self.pwd] (rc, out, err) = self.run_command('check_password', options) except EjabberdUserException: e = get_exception() (rc, out, err) = (1, None, "required attribute(s) missing") return rc @property def exists(self): """ This method will check to see if the supplied username exists for host specified. If the user exists True is returned, otherwise False is returned """ try: options = [self.user, self.host] (rc, out, err) = self.run_command('check_account', options) except EjabberdUserException: e = get_exception() (rc, out, err) = (1, None, "required attribute(s) missing") return not bool(int(rc)) def log(self, entry): """ This method will log information to the local syslog facility """ if self.logging: syslog.openlog('ansible-%s' % self.module._name) syslog.syslog(syslog.LOG_NOTICE, entry) def run_command(self, cmd, options): """ This method will run the any command specified and return the returns using the Ansible common module """ if not all(options): raise EjabberdUserException cmd = 'ejabberdctl %s ' % cmd cmd += " ".join(options) self.log('command: %s' % cmd) return self.module.run_command(cmd.split()) def update(self): """ The update method will update the credentials for the user provided """ try: options = [self.user, self.host, self.pwd] (rc, out, err) = self.run_command('change_password', options) except EjabberdUserException: e = get_exception() (rc, out, err) = (1, None, "required attribute(s) missing") return (rc, out, err) def create(self): """ The create method will create a new user on the host with the password provided """ try: options = [self.user, self.host, self.pwd] (rc, out, err) = self.run_command('register', options) except EjabberdUserException: e = get_exception() (rc, out, err) = (1, None, "required attribute(s) missing") return (rc, out, err) def delete(self): """ The delete method will delete the user from the host """ try: options = [self.user, self.host] (rc, out, err) = self.run_command('unregister', options) except EjabberdUserException: e = get_exception() (rc, out, err) = (1, None, "required attribute(s) missing") return (rc, out, err) def main(): module = AnsibleModule( argument_spec = dict( host=dict(default=None, type='str'), username=dict(default=None, type='str'), password=dict(default=None, type='str'), state=dict(default='present', choices=['present', 'absent']), logging=dict(default=False, type='bool') ), supports_check_mode = True ) obj = EjabberdUser(module) rc = None result = dict() if obj.state == 'absent': if obj.exists: if module.check_mode: module.exit_json(changed=True) (rc, out, err) = obj.delete() if rc != 0: module.fail_json(msg=err, rc=rc) elif obj.state == 'present': if not obj.exists: if module.check_mode: module.exit_json(changed=True) (rc, out, err) = obj.create() elif obj.changed: if module.check_mode: module.exit_json(changed=True) (rc, out, err) = obj.update() if rc is not None and rc != 0: module.fail_json(msg=err, rc=rc) if rc is None: result['changed'] = False else: result['changed'] = True module.exit_json(**result) main()
memtoko/django
refs/heads/master
tests/proxy_models/__init__.py
12133432
sodafree/backend
refs/heads/master
build/lib.linux-i686-2.7/django/utils/encoding.py
37
import types import urllib import locale import datetime import codecs from decimal import Decimal from django.utils.functional import Promise class DjangoUnicodeDecodeError(UnicodeDecodeError): def __init__(self, obj, *args): self.obj = obj UnicodeDecodeError.__init__(self, *args) def __str__(self): original = UnicodeDecodeError.__str__(self) return '%s. You passed in %r (%s)' % (original, self.obj, type(self.obj)) class StrAndUnicode(object): """ A class whose __str__ returns its __unicode__ as a UTF-8 bytestring. Useful as a mix-in. """ def __str__(self): return self.__unicode__().encode('utf-8') def smart_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): """ Returns a unicode object representing 's'. Treats bytestrings using the 'encoding' codec. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, Promise): # The input is the result of a gettext_lazy() call. return s return force_unicode(s, encoding, strings_only, errors) def is_protected_type(obj): """Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_unicode(strings_only=True). """ return isinstance(obj, ( types.NoneType, int, long, datetime.datetime, datetime.date, datetime.time, float, Decimal) ) def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_unicode, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first, saves 30-40% in performance when s # is an instance of unicode. This function gets called often in that # setting. if isinstance(s, unicode): return s if strings_only and is_protected_type(s): return s try: if not isinstance(s, basestring,): if hasattr(s, '__unicode__'): s = unicode(s) else: try: s = unicode(str(s), encoding, errors) except UnicodeEncodeError: if not isinstance(s, Exception): raise # If we get to here, the caller has passed in an Exception # subclass populated with non-ASCII data without special # handling to display as a string. We need to handle this # without raising a further exception. We do an # approximation to what the Exception's standard str() # output should be. s = u' '.join([force_unicode(arg, encoding, strings_only, errors) for arg in s]) elif not isinstance(s, unicode): # Note: We use .decode() here, instead of unicode(s, encoding, # errors), so that if s is a SafeString, it ends up being a # SafeUnicode at the end. s = s.decode(encoding, errors) except UnicodeDecodeError, e: if not isinstance(s, Exception): raise DjangoUnicodeDecodeError(s, *e.args) else: # If we get to here, the caller has passed in an Exception # subclass populated with non-ASCII bytestring data without a # working unicode method. Try to handle this without raising a # further exception by individually forcing the exception args # to unicode. s = u' '.join([force_unicode(arg, encoding, strings_only, errors) for arg in s]) return s def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'): """ Returns a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. """ if strings_only and isinstance(s, (types.NoneType, int)): return s if isinstance(s, Promise): return unicode(s).encode(encoding, errors) elif not isinstance(s, basestring): try: return str(s) except UnicodeEncodeError: if isinstance(s, Exception): # An Exception subclass containing non-ASCII data that doesn't # know how to print itself properly. We shouldn't raise a # further exception. return ' '.join([smart_str(arg, encoding, strings_only, errors) for arg in s]) return unicode(s).encode(encoding, errors) elif isinstance(s, unicode): return s.encode(encoding, errors) elif s and encoding != 'utf-8': return s.decode('utf-8', errors).encode(encoding, errors) else: return s def iri_to_uri(iri): """ Convert an Internationalized Resource Identifier (IRI) portion to a URI portion that is suitable for inclusion in a URL. This is the algorithm from section 3.1 of RFC 3987. However, since we are assuming input is either UTF-8 or unicode already, we can simplify things a little from the full method. Returns an ASCII string containing the encoded result. """ # The list of safe characters here is constructed from the "reserved" and # "unreserved" characters specified in sections 2.2 and 2.3 of RFC 3986: # reserved = gen-delims / sub-delims # gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" # sub-delims = "!" / "$" / "&" / "'" / "(" / ")" # / "*" / "+" / "," / ";" / "=" # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" # Of the unreserved characters, urllib.quote already considers all but # the ~ safe. # The % character is also added to the list of safe characters here, as the # end of section 3.1 of RFC 3987 specifically mentions that % must not be # converted. if iri is None: return iri return urllib.quote(smart_str(iri), safe="/#%[]=:;$&()+,!?*@'~") def filepath_to_uri(path): """Convert an file system path to a URI portion that is suitable for inclusion in a URL. We are assuming input is either UTF-8 or unicode already. This method will encode certain chars that would normally be recognized as special chars for URIs. Note that this method does not encode the ' character, as it is a valid character within URIs. See encodeURIComponent() JavaScript function for more details. Returns an ASCII string containing the encoded result. """ if path is None: return path # I know about `os.sep` and `os.altsep` but I want to leave # some flexibility for hardcoding separators. return urllib.quote(smart_str(path).replace("\\", "/"), safe="/~!*()'") # The encoding of the default system locale but falls back to the # given fallback encoding if the encoding is unsupported by python or could # not be determined. See tickets #10335 and #5846 try: DEFAULT_LOCALE_ENCODING = locale.getdefaultlocale()[1] or 'ascii' codecs.lookup(DEFAULT_LOCALE_ENCODING) except: DEFAULT_LOCALE_ENCODING = 'ascii' # Forwards compatibility with Django 1.5 def python_2_unicode_compatible(klass): # Always use the Python 2 branch of the decorator here in Django 1.4 klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass smart_text = smart_unicode force_text = force_unicode smart_bytes = smart_str
alangwansui/mtl_ordercenter
refs/heads/master
openerp/addons/product/wizard/product_price.py
49
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ class product_price_list(osv.osv_memory): _name = 'product.price_list' _description = 'Price List' _columns = { 'price_list': fields.many2one('product.pricelist', 'PriceList', required=True), 'qty1': fields.integer('Quantity-1'), 'qty2': fields.integer('Quantity-2'), 'qty3': fields.integer('Quantity-3'), 'qty4': fields.integer('Quantity-4'), 'qty5': fields.integer('Quantity-5'), } _defaults = { 'qty1': 1, 'qty2': 5, 'qty3': 10, 'qty4': 0, 'qty5': 0, } def print_report(self, cr, uid, ids, context=None): """ To get the date and print the report @return : return report """ if context is None: context = {} datas = {'ids': context.get('active_ids', [])} res = self.read(cr, uid, ids, ['price_list','qty1', 'qty2','qty3','qty4','qty5'], context=context) res = res and res[0] or {} res['price_list'] = res['price_list'][0] datas['form'] = res return { 'type': 'ir.actions.report.xml', 'report_name': 'product.pricelist', 'datas': datas, } product_price_list() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
cmidt-veasna/SwiftFlatbuffer
refs/heads/master
flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.py
28
# automatically generated by the FlatBuffers compiler, do not modify # namespace: NamespaceA import flatbuffers class SecondTableInA(object): __slots__ = ['_tab'] @classmethod def GetRootAsSecondTableInA(cls, buf, offset): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = SecondTableInA() x.Init(buf, n + offset) return x # SecondTableInA def Init(self, buf, pos): self._tab = flatbuffers.table.Table(buf, pos) # SecondTableInA def ReferToC(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) if o != 0: x = self._tab.Indirect(o + self._tab.Pos) from .TableInC import TableInC obj = TableInC() obj.Init(self._tab.Bytes, x) return obj return None def SecondTableInAStart(builder): builder.StartObject(1) def SecondTableInAAddReferToC(builder, referToC): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(referToC), 0) def SecondTableInAEnd(builder): return builder.EndObject()
gdesmott/politube
refs/heads/master
videos_tools/forms.py
236
from django import forms # place form definition here
kawamon/hue
refs/heads/master
desktop/core/ext-py/ply-3.11/test/yacc_error6.py
10
# ----------------------------------------------------------------------------- # yacc_error6.py # # Panic mode recovery test # ----------------------------------------------------------------------------- import sys if ".." not in sys.path: sys.path.insert(0,"..") import ply.yacc as yacc from calclex import tokens # Parsing rules precedence = ( ('left','PLUS','MINUS'), ('left','TIMES','DIVIDE'), ('right','UMINUS'), ) def p_statements(t): 'statements : statements statement' pass def p_statements_1(t): 'statements : statement' pass def p_statement_assign(p): 'statement : LPAREN NAME EQUALS expression RPAREN' print("%s=%s" % (p[2],p[4])) def p_statement_expr(t): 'statement : LPAREN expression RPAREN' print(t[1]) def p_expression_binop(t): '''expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression''' if t[2] == '+' : t[0] = t[1] + t[3] elif t[2] == '-': t[0] = t[1] - t[3] elif t[2] == '*': t[0] = t[1] * t[3] elif t[2] == '/': t[0] = t[1] / t[3] def p_expression_uminus(t): 'expression : MINUS expression %prec UMINUS' t[0] = -t[2] def p_expression_number(t): 'expression : NUMBER' t[0] = t[1] def p_error(p): if p: print("Line %d: Syntax error at '%s'" % (p.lineno, p.value)) # Scan ahead looking for a name token while True: tok = parser.token() if not tok or tok.type == 'RPAREN': break if tok: parser.restart() return None parser = yacc.yacc() import calclex calclex.lexer.lineno=1 parser.parse(""" (a = 3 + 4) (b = 4 + * 5 - 6 + *) (c = 10 + 11) """)
nvoron23/socialite
refs/heads/master
jython/Lib/test/crashers/recursion_limit_too_high.py
87
# The following example may crash or not depending on the platform. # E.g. on 32-bit Intel Linux in a "standard" configuration it seems to # crash on Python 2.5 (but not 2.4 nor 2.3). On Windows the import # eventually fails to find the module, possibly because we run out of # file handles. # The point of this example is to show that sys.setrecursionlimit() is a # hack, and not a robust solution. This example simply exercices a path # where it takes many C-level recursions, consuming a lot of stack # space, for each Python-level recursion. So 1000 times this amount of # stack space may be too much for standard platforms already. import sys if 'recursion_limit_too_high' in sys.modules: del sys.modules['recursion_limit_too_high'] import recursion_limit_too_high
alvarofe/sdb
refs/heads/master
bindings/benchmark/python.py
4
#!/usr/bin/python import json str = """ {"glossary":{"title":"example glossary","page":1,"GlossDiv":{"title":"First gloss title","GlossList":{"GlossEntry":{"ID":"SGML","SortAs":"SGML","GlossTerm":"Standard Generalized Markup Language","Acronym":"SGML","Abbrev":"ISO 8879:1986","GlossDef":{"para":"A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso":["OK","GML","XML"]},"GlossSee":"markup"}}}}} """ obj = { "str": str } for i in range (1, 199999): js = json.loads (obj['str']) food = js['glossary']['title']
MasonM/hssonline-conference
refs/heads/master
django_conference/templatetags/money_format.py
1
from decimal import Decimal from django import template register = template.Library() @register.filter def money_format(value): """ Display float in money-style format with specified decimal places and comma-grouped thousands. Adapted from https://docs.python.org/2/library/decimal.html#recipes """ q = Decimal(10) ** -2 # 2 places --> '0.01' _, digits, exp = Decimal(str(value)).quantize(q).as_tuple() result = [] digits = map(str, digits) build, next = result.append, digits.pop for i in range(2): build(next() if digits else '0') build('.') if not digits: build('0') i = 0 while digits: build(next()) i += 1 if i == 3 and digits: i = 0 build(',') build('$') return ''.join(reversed(result))
krieger-od/nwjs_chromium.src
refs/heads/master
chrome/third_party/chromevox/third_party/closure-library/closure/bin/build/source.py
166
# Copyright 2009 The Closure Library Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Scans a source JS file for its provided and required namespaces. Simple class to scan a JavaScript file and express its dependencies. """ __author__ = 'nnaze@google.com' import re _BASE_REGEX_STRING = '^\s*goog\.%s\(\s*[\'"](.+)[\'"]\s*\)' _PROVIDE_REGEX = re.compile(_BASE_REGEX_STRING % 'provide') _REQUIRES_REGEX = re.compile(_BASE_REGEX_STRING % 'require') class Source(object): """Scans a JavaScript source for its provided and required namespaces.""" # Matches a "/* ... */" comment. # Note: We can't definitively distinguish a "/*" in a string literal without a # state machine tokenizer. We'll assume that a line starting with whitespace # and "/*" is a comment. _COMMENT_REGEX = re.compile( r""" ^\s* # Start of a new line and whitespace /\* # Opening "/*" .*? # Non greedy match of any characters (including newlines) \*/ # Closing "*/""", re.MULTILINE | re.DOTALL | re.VERBOSE) def __init__(self, source): """Initialize a source. Args: source: str, The JavaScript source. """ self.provides = set() self.requires = set() self._source = source self._ScanSource() def GetSource(self): """Get the source as a string.""" return self._source @classmethod def _StripComments(cls, source): return cls._COMMENT_REGEX.sub('', source) @classmethod def _HasProvideGoogFlag(cls, source): """Determines whether the @provideGoog flag is in a comment.""" for comment_content in cls._COMMENT_REGEX.findall(source): if '@provideGoog' in comment_content: return True return False def _ScanSource(self): """Fill in provides and requires by scanning the source.""" stripped_source = self._StripComments(self.GetSource()) source_lines = stripped_source.splitlines() for line in source_lines: match = _PROVIDE_REGEX.match(line) if match: self.provides.add(match.group(1)) match = _REQUIRES_REGEX.match(line) if match: self.requires.add(match.group(1)) # Closure's base file implicitly provides 'goog'. # This is indicated with the @provideGoog flag. if self._HasProvideGoogFlag(self.GetSource()): if len(self.provides) or len(self.requires): raise Exception( 'Base file should not provide or require namespaces.') self.provides.add('goog') def GetFileContents(path): """Get a file's contents as a string. Args: path: str, Path to file. Returns: str, Contents of file. Raises: IOError: An error occurred opening or reading the file. """ fileobj = open(path) try: return fileobj.read() finally: fileobj.close()
coreos/depot_tools
refs/heads/master
third_party/colorama/ansitowin32.py
287
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. import re import sys from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style from .winterm import WinTerm, WinColor, WinStyle from .win32 import windll if windll is not None: winterm = WinTerm() def is_a_tty(stream): return hasattr(stream, 'isatty') and stream.isatty() class StreamWrapper(object): ''' Wraps a stream (such as stdout), acting as a transparent proxy for all attribute access apart from method 'write()', which is delegated to our Converter instance. ''' def __init__(self, wrapped, converter): # double-underscore everything to prevent clashes with names of # attributes on the wrapped stream object. self.__wrapped = wrapped self.__convertor = converter def __getattr__(self, name): return getattr(self.__wrapped, name) def write(self, text): self.__convertor.write(text) class AnsiToWin32(object): ''' Implements a 'write()' method which, on Windows, will strip ANSI character sequences from the text, and if outputting to a tty, will convert them into win32 function calls. ''' ANSI_RE = re.compile('\033\[((?:\d|;)*)([a-zA-Z])') def __init__(self, wrapped, convert=None, strip=None, autoreset=False): # The wrapped stream (normally sys.stdout or sys.stderr) self.wrapped = wrapped # should we reset colors to defaults after every .write() self.autoreset = autoreset # create the proxy wrapping our output stream self.stream = StreamWrapper(wrapped, self) on_windows = sys.platform.startswith('win') # should we strip ANSI sequences from our output? if strip is None: strip = on_windows self.strip = strip # should we should convert ANSI sequences into win32 calls? if convert is None: convert = on_windows and is_a_tty(wrapped) self.convert = convert # dict of ansi codes to win32 functions and parameters self.win32_calls = self.get_win32_calls() # are we wrapping stderr? self.on_stderr = self.wrapped is sys.stderr def should_wrap(self): ''' True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionality like autoreset has been requested using kwargs to init() ''' return self.convert or self.strip or self.autoreset def get_win32_calls(self): if self.convert and winterm: return { AnsiStyle.RESET_ALL: (winterm.reset_all, ), AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT), AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL), AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL), AnsiFore.BLACK: (winterm.fore, WinColor.BLACK), AnsiFore.RED: (winterm.fore, WinColor.RED), AnsiFore.GREEN: (winterm.fore, WinColor.GREEN), AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW), AnsiFore.BLUE: (winterm.fore, WinColor.BLUE), AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA), AnsiFore.CYAN: (winterm.fore, WinColor.CYAN), AnsiFore.WHITE: (winterm.fore, WinColor.GREY), AnsiFore.RESET: (winterm.fore, ), AnsiBack.BLACK: (winterm.back, WinColor.BLACK), AnsiBack.RED: (winterm.back, WinColor.RED), AnsiBack.GREEN: (winterm.back, WinColor.GREEN), AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW), AnsiBack.BLUE: (winterm.back, WinColor.BLUE), AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA), AnsiBack.CYAN: (winterm.back, WinColor.CYAN), AnsiBack.WHITE: (winterm.back, WinColor.GREY), AnsiBack.RESET: (winterm.back, ), } def write(self, text): if self.strip or self.convert: self.write_and_convert(text) else: self.wrapped.write(text) self.wrapped.flush() if self.autoreset: self.reset_all() def reset_all(self): if self.convert: self.call_win32('m', (0,)) elif is_a_tty(self.wrapped): self.wrapped.write(Style.RESET_ALL) def write_and_convert(self, text): ''' Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls. ''' cursor = 0 for match in self.ANSI_RE.finditer(text): start, end = match.span() self.write_plain_text(text, cursor, start) self.convert_ansi(*match.groups()) cursor = end self.write_plain_text(text, cursor, len(text)) def write_plain_text(self, text, start, end): if start < end: self.wrapped.write(text[start:end]) self.wrapped.flush() def convert_ansi(self, paramstring, command): if self.convert: params = self.extract_params(paramstring) self.call_win32(command, params) def extract_params(self, paramstring): def split(paramstring): for p in paramstring.split(';'): if p != '': yield int(p) return tuple(split(paramstring)) def call_win32(self, command, params): if params == []: params = [0] if command == 'm': for param in params: if param in self.win32_calls: func_args = self.win32_calls[param] func = func_args[0] args = func_args[1:] kwargs = dict(on_stderr=self.on_stderr) func(*args, **kwargs) elif command in ('H', 'f'): # set cursor position func = winterm.set_cursor_position func(params, on_stderr=self.on_stderr) elif command in ('J'): func = winterm.erase_data func(params, on_stderr=self.on_stderr) elif command == 'A': if params == () or params == None: num_rows = 1 else: num_rows = params[0] func = winterm.cursor_up func(num_rows, on_stderr=self.on_stderr)
akretion/stock-logistics-workflow
refs/heads/8.0
stock_picking_package_preparation/__init__.py
17
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2015 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import model
akazakov/ansible-modules-core
refs/heads/devel
web_infrastructure/django_manage.py
55
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Scott Anderson <scottanderson42@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # DOCUMENTATION = ''' --- module: django_manage short_description: Manages a Django application. description: - Manages a Django application using the I(manage.py) application frontend to I(django-admin). With the I(virtualenv) parameter, all management commands will be executed by the given I(virtualenv) installation. version_added: "1.1" options: command: choices: [ 'cleanup', 'collectstatic', 'flush', 'loaddata', 'migrate', 'runfcgi', 'syncdb', 'test', 'validate', ] description: - The name of the Django management command to run. Built in commands are cleanup, collectstatic, flush, loaddata, migrate, runfcgi, syncdb, test, and validate. - Other commands can be entered, but will fail if they're unknown to Django. Other commands that may prompt for user input should be run with the I(--noinput) flag. required: true app_path: description: - The path to the root of the Django application where B(manage.py) lives. required: true settings: description: - The Python path to the application's settings module, such as 'myapp.settings'. required: false pythonpath: description: - A directory to add to the Python path. Typically used to include the settings module if it is located external to the application directory. required: false virtualenv: description: - An optional path to a I(virtualenv) installation to use while running the manage application. required: false apps: description: - A list of space-delimited apps to target. Used by the 'test' command. required: false cache_table: description: - The name of the table used for database-backed caching. Used by the 'createcachetable' command. required: false database: description: - The database to target. Used by the 'createcachetable', 'flush', 'loaddata', and 'syncdb' commands. required: false failfast: description: - Fail the command immediately if a test fails. Used by the 'test' command. required: false default: "no" choices: [ "yes", "no" ] fixtures: description: - A space-delimited list of fixture file names to load in the database. B(Required) by the 'loaddata' command. required: false skip: description: - Will skip over out-of-order missing migrations, you can only use this parameter with I(migrate) required: false version_added: "1.3" merge: description: - Will run out-of-order or missing migrations as they are not rollback migrations, you can only use this parameter with 'migrate' command required: false version_added: "1.3" link: description: - Will create links to the files instead of copying them, you can only use this parameter with 'collectstatic' command required: false version_added: "1.3" notes: - I(virtualenv) (U(http://www.virtualenv.org)) must be installed on the remote host if the virtualenv parameter is specified. - This module will create a virtualenv if the virtualenv parameter is specified and a virtualenv does not already exist at the given location. - This module assumes English error messages for the 'createcachetable' command to detect table existence, unfortunately. - To be able to use the migrate command with django versions < 1.7, you must have south installed and added as an app in your settings - To be able to use the collectstatic command, you must have enabled staticfiles in your settings requirements: [ "virtualenv", "django" ] author: "Scott Anderson (@tastychutney)" ''' EXAMPLES = """ # Run cleanup on the application installed in 'django_dir'. - django_manage: command=cleanup app_path={{ django_dir }} # Load the initial_data fixture into the application - django_manage: command=loaddata app_path={{ django_dir }} fixtures={{ initial_data }} # Run syncdb on the application - django_manage: > command=syncdb app_path={{ django_dir }} settings={{ settings_app_name }} pythonpath={{ settings_dir }} virtualenv={{ virtualenv_dir }} # Run the SmokeTest test case from the main app. Useful for testing deploys. - django_manage: command=test app_path={{ django_dir }} apps=main.SmokeTest # Create an initial superuser. - django_manage: command="createsuperuser --noinput --username=admin --email=admin@example.com" app_path={{ django_dir }} """ import os def _fail(module, cmd, out, err, **kwargs): msg = '' if out: msg += "stdout: %s" % (out, ) if err: msg += "\n:stderr: %s" % (err, ) module.fail_json(cmd=cmd, msg=msg, **kwargs) def _ensure_virtualenv(module): venv_param = module.params['virtualenv'] if venv_param is None: return vbin = os.path.join(os.path.expanduser(venv_param), 'bin') activate = os.path.join(vbin, 'activate') if not os.path.exists(activate): virtualenv = module.get_bin_path('virtualenv', True) vcmd = '%s %s' % (virtualenv, venv_param) vcmd = [virtualenv, venv_param] rc, out_venv, err_venv = module.run_command(vcmd) if rc != 0: _fail(module, vcmd, out_venv, err_venv) os.environ["PATH"] = "%s:%s" % (vbin, os.environ["PATH"]) os.environ["VIRTUAL_ENV"] = venv_param def createcachetable_filter_output(line): return "Already exists" not in line def flush_filter_output(line): return "Installed" in line and "Installed 0 object" not in line def loaddata_filter_output(line): return "Installed" in line and "Installed 0 object" not in line def syncdb_filter_output(line): return ("Creating table " in line) or ("Installed" in line and "Installed 0 object" not in line) def migrate_filter_output(line): return ("Migrating forwards " in line) or ("Installed" in line and "Installed 0 object" not in line) or ("Applying" in line) def collectstatic_filter_output(line): return "0 static files" not in line def main(): command_allowed_param_map = dict( cleanup=(), createcachetable=('cache_table', 'database', ), flush=('database', ), loaddata=('database', 'fixtures', ), syncdb=('database', ), test=('failfast', 'testrunner', 'liveserver', 'apps', ), validate=(), migrate=('apps', 'skip', 'merge', 'database',), collectstatic=('clear', 'link', ), ) command_required_param_map = dict( loaddata=('fixtures', ), createcachetable=('cache_table', ), ) # forces --noinput on every command that needs it noinput_commands = ( 'flush', 'syncdb', 'migrate', 'test', 'collectstatic', ) # These params are allowed for certain commands only specific_params = ('apps', 'clear', 'database', 'failfast', 'fixtures', 'liveserver', 'testrunner') # These params are automatically added to the command if present general_params = ('settings', 'pythonpath', 'database',) specific_boolean_params = ('clear', 'failfast', 'skip', 'merge', 'link') end_of_command_params = ('apps', 'cache_table', 'fixtures') module = AnsibleModule( argument_spec=dict( command = dict(default=None, required=True), app_path = dict(default=None, required=True), settings = dict(default=None, required=False), pythonpath = dict(default=None, required=False, aliases=['python_path']), virtualenv = dict(default=None, required=False, aliases=['virtual_env']), apps = dict(default=None, required=False), cache_table = dict(default=None, required=False), clear = dict(default=None, required=False, type='bool'), database = dict(default=None, required=False), failfast = dict(default='no', required=False, type='bool', aliases=['fail_fast']), fixtures = dict(default=None, required=False), liveserver = dict(default=None, required=False, aliases=['live_server']), testrunner = dict(default=None, required=False, aliases=['test_runner']), skip = dict(default=None, required=False, type='bool'), merge = dict(default=None, required=False, type='bool'), link = dict(default=None, required=False, type='bool'), ), ) command = module.params['command'] app_path = os.path.expanduser(module.params['app_path']) virtualenv = module.params['virtualenv'] for param in specific_params: value = module.params[param] if param in specific_boolean_params: value = module.boolean(value) if value and param not in command_allowed_param_map[command]: module.fail_json(msg='%s param is incompatible with command=%s' % (param, command)) for param in command_required_param_map.get(command, ()): if not module.params[param]: module.fail_json(msg='%s param is required for command=%s' % (param, command)) _ensure_virtualenv(module) cmd = "./manage.py %s" % (command, ) if command in noinput_commands: cmd = '%s --noinput' % cmd for param in general_params: if module.params[param]: cmd = '%s --%s=%s' % (cmd, param, module.params[param]) for param in specific_boolean_params: if module.boolean(module.params[param]): cmd = '%s --%s' % (cmd, param) # these params always get tacked on the end of the command for param in end_of_command_params: if module.params[param]: cmd = '%s %s' % (cmd, module.params[param]) rc, out, err = module.run_command(cmd, cwd=os.path.expanduser(app_path)) if rc != 0: if command == 'createcachetable' and 'table' in err and 'already exists' in err: out = 'Already exists.' else: if "Unknown command:" in err: _fail(module, cmd, err, "Unknown django command: %s" % command) _fail(module, cmd, out, err, path=os.environ["PATH"], syspath=sys.path) changed = False lines = out.split('\n') filt = globals().get(command + "_filter_output", None) if filt: filtered_output = filter(filt, out.split('\n')) if len(filtered_output): changed = filtered_output module.exit_json(changed=changed, out=out, cmd=cmd, app_path=app_path, virtualenv=virtualenv, settings=module.params['settings'], pythonpath=module.params['pythonpath']) # import module snippets from ansible.module_utils.basic import * main()
jeezybrick/django
refs/heads/master
tests/migrations/test_migrations_squashed_complex_multi_apps/app1/4_auto.py
385
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("app1", "3_auto")] operations = [ migrations.RunPython(migrations.RunPython.noop) ]
sirchristian/v8DOM.NET
refs/heads/master
v8-read-only/tools/presubmit.py
1
#!/usr/bin/env python # # Copyright 2011 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. try: import hashlib md5er = hashlib.md5 except ImportError, e: import md5 md5er = md5.new import optparse import os from os.path import abspath, join, dirname, basename, exists import pickle import re import sys import subprocess from subprocess import PIPE # Disabled LINT rules and reason. # build/include_what_you_use: Started giving false positives for variables # named "string" and "map" assuming that you needed to include STL headers. ENABLED_LINT_RULES = """ build/class build/deprecated build/endif_comment build/forward_decl build/include_order build/printf_format build/storage_class legal/copyright readability/boost readability/braces readability/casting readability/check readability/constructors readability/fn_size readability/function readability/multiline_comment readability/multiline_string readability/streams readability/todo readability/utf8 runtime/arrays runtime/casting runtime/deprecated_fn runtime/explicit runtime/int runtime/memset runtime/mutex runtime/nonconf runtime/printf runtime/printf_format runtime/references runtime/rtti runtime/sizeof runtime/string runtime/virtual runtime/vlog whitespace/blank_line whitespace/braces whitespace/comma whitespace/comments whitespace/ending_newline whitespace/indent whitespace/labels whitespace/line_length whitespace/newline whitespace/operators whitespace/parens whitespace/tab whitespace/todo """.split() class FileContentsCache(object): def __init__(self, sums_file_name): self.sums = {} self.sums_file_name = sums_file_name def Load(self): try: sums_file = None try: sums_file = open(self.sums_file_name, 'r') self.sums = pickle.load(sums_file) except IOError: # File might not exist, this is OK. pass finally: if sums_file: sums_file.close() def Save(self): try: sums_file = open(self.sums_file_name, 'w') pickle.dump(self.sums, sums_file) finally: sums_file.close() def FilterUnchangedFiles(self, files): changed_or_new = [] for file in files: try: handle = open(file, "r") file_sum = md5er(handle.read()).digest() if not file in self.sums or self.sums[file] != file_sum: changed_or_new.append(file) self.sums[file] = file_sum finally: handle.close() return changed_or_new def RemoveFile(self, file): if file in self.sums: self.sums.pop(file) class SourceFileProcessor(object): """ Utility class that can run through a directory structure, find all relevant files and invoke a custom check on the files. """ def Run(self, path): all_files = [] for file in self.GetPathsToSearch(): all_files += self.FindFilesIn(join(path, file)) if not self.ProcessFiles(all_files, path): return False return True def IgnoreDir(self, name): return name.startswith('.') or name == 'data' or name == 'sputniktests' def IgnoreFile(self, name): return name.startswith('.') def FindFilesIn(self, path): result = [] for (root, dirs, files) in os.walk(path): for ignored in [x for x in dirs if self.IgnoreDir(x)]: dirs.remove(ignored) for file in files: if not self.IgnoreFile(file) and self.IsRelevant(file): result.append(join(root, file)) return result class CppLintProcessor(SourceFileProcessor): """ Lint files to check that they follow the google code style. """ def IsRelevant(self, name): return name.endswith('.cc') or name.endswith('.h') def IgnoreDir(self, name): return (super(CppLintProcessor, self).IgnoreDir(name) or (name == 'third_party')) IGNORE_LINT = ['flag-definitions.h'] def IgnoreFile(self, name): return (super(CppLintProcessor, self).IgnoreFile(name) or (name in CppLintProcessor.IGNORE_LINT)) def GetPathsToSearch(self): return ['src', 'preparser', 'include', 'samples', join('test', 'cctest')] def ProcessFiles(self, files, path): good_files_cache = FileContentsCache('.cpplint-cache') good_files_cache.Load() files = good_files_cache.FilterUnchangedFiles(files) if len(files) == 0: print 'No changes in files detected. Skipping cpplint check.' return True filt = '-,' + ",".join(['+' + n for n in ENABLED_LINT_RULES]) command = ['cpplint.py', '--filter', filt] + join(files) local_cpplint = join(path, "tools", "cpplint.py") if exists(local_cpplint): command = ['python', local_cpplint, '--filter', filt] + join(files) try: process = subprocess.Popen(command, stderr=subprocess.PIPE) except: print('Error running cpplint.py. Please make sure you have depot_tools' + ' in your $PATH. Lint check skipped.') return True LINT_ERROR_PATTERN = re.compile(r'^(.+)[:(]\d+[:)]') while True: out_line = process.stderr.readline() if out_line == '' and process.poll() != None: break sys.stderr.write(out_line) m = LINT_ERROR_PATTERN.match(out_line) if m: good_files_cache.RemoveFile(m.group(1)) good_files_cache.Save() return process.returncode == 0 COPYRIGHT_HEADER_PATTERN = re.compile( r'Copyright [\d-]*20[0-1][0-9] the V8 project authors. All rights reserved.') class SourceProcessor(SourceFileProcessor): """ Check that all files include a copyright notice and no trailing whitespaces. """ RELEVANT_EXTENSIONS = ['.js', '.cc', '.h', '.py', '.c', 'SConscript', 'SConstruct', '.status', '.gyp', '.gypi'] # Overwriting the one in the parent class. def FindFilesIn(self, path): if os.path.exists(path+'/.git'): output = subprocess.Popen('git ls-files --full-name', stdout=PIPE, cwd=path, shell=True) result = [] for file in output.stdout.read().split(): for dir_part in os.path.dirname(file).split(os.sep): if self.IgnoreDir(dir_part): break else: if self.IsRelevant(file) and not self.IgnoreFile(file): result.append(join(path, file)) if output.wait() == 0: return result return super(SourceProcessor, self).FindFilesIn(path) def IsRelevant(self, name): for ext in SourceProcessor.RELEVANT_EXTENSIONS: if name.endswith(ext): return True return False def GetPathsToSearch(self): return ['.'] def IgnoreDir(self, name): return (super(SourceProcessor, self).IgnoreDir(name) or (name == 'third_party') or (name == 'gyp') or (name == 'out') or (name == 'obj')) IGNORE_COPYRIGHTS = ['cpplint.py', 'earley-boyer.js', 'raytrace.js', 'crypto.js', 'libraries.cc', 'libraries-empty.cc', 'jsmin.py', 'regexp-pcre.js'] IGNORE_TABS = IGNORE_COPYRIGHTS + ['unicode-test.js', 'html-comments.js'] def ProcessContents(self, name, contents): result = True base = basename(name) if not base in SourceProcessor.IGNORE_TABS: if '\t' in contents: print "%s contains tabs" % name result = False if not base in SourceProcessor.IGNORE_COPYRIGHTS: if not COPYRIGHT_HEADER_PATTERN.search(contents): print "%s is missing a correct copyright header." % name result = False ext = base.split('.').pop() if ' \n' in contents or contents.endswith(' '): line = 0 lines = [] parts = contents.split(' \n') if not contents.endswith(' '): parts.pop() for part in parts: line += part.count('\n') + 1 lines.append(str(line)) linenumbers = ', '.join(lines) if len(lines) > 1: print "%s has trailing whitespaces in lines %s." % (name, linenumbers) else: print "%s has trailing whitespaces in line %s." % (name, linenumbers) result = False return result def ProcessFiles(self, files, path): success = True violations = 0 for file in files: try: handle = open(file) contents = handle.read() if not self.ProcessContents(file, contents): success = False violations += 1 finally: handle.close() print "Total violating files: %s" % violations return success def GetOptions(): result = optparse.OptionParser() result.add_option('--no-lint', help="Do not run cpplint", default=False, action="store_true") return result def Main(): workspace = abspath(join(dirname(sys.argv[0]), '..')) parser = GetOptions() (options, args) = parser.parse_args() success = True print "Running C++ lint check..." if not options.no_lint: success = CppLintProcessor().Run(workspace) and success print "Running copyright header and trailing whitespaces check..." success = SourceProcessor().Run(workspace) and success if success: return 0 else: return 1 if __name__ == '__main__': sys.exit(Main())
KamilWo/bestja
refs/heads/master
addons/message_template/models.py
2
# -*- coding: utf-8 -*- from urlparse import urljoin from openerp import models, fields, api, tools from openerp.addons.email_template.email_template import mako_template_env class MessageTemplate(models.Model): _name = 'message_template' subject = fields.Char() body = fields.Text() model = fields.Char() @api.one def send(self, recipients, sender=None, record=None, record_name=None): recipient_partners = [] for recipient in recipients: recipient_partners.append( (4, recipient.sudo().partner_id.id) ) subtype = None if not sender: sender = self.env.ref('message_template.user_messages') subtype = self.env.ref('message_template.subtype_system_message') base_url = self.env['ir.config_parameter'].get_param('web.base.url') def link_to(record): """ Create an absolute link to the given record. """ path = '/web#id={}&model={}'.format(record.id, record._name) return urljoin(base_url, path) # Enable resolution of ${variables} inside body template_context = { 'record': record, 'context': self.env.context, 'base_url': base_url, 'link_to': link_to, 'site_name': self.env.user.company_id.name, } body_template = mako_template_env.from_string(tools.ustr(self.body)) body_rendered = body_template.render(template_context) subject_template = mako_template_env.from_string(tools.ustr(self.subject)) subject_rendered = subject_template.render(template_context) self.env['mail.message'].sudo().create({ 'type': 'comment', 'author_id': sender.sudo().partner_id.id, 'partner_ids': recipient_partners, 'model': self.model, 'res_id': record and record.id, 'record_name': record_name or (record and record.display_name), 'subject': subject_rendered, 'body': body_rendered, 'template': self.id, 'subtype_id': subtype and subtype.id }) @api.multi def send_group(self, group, sender=None, record=None, record_name=None): """ Send a message to all users in a group `group`. """ group_obj = self.env.ref(group) self.send( recipients=group_obj.sudo().users, sender=sender, record=record, record_name=record_name, ) class MessageTemplateMixin(models.AbstractModel): """ This mixin enables model's records to be used with Odoo messages and adds `send` and `send_group` methods to the model. """ _name = 'message_template.mixin' @api.one def send(self, template, recipients, sender=None, record_name=None): return self.env.ref(template).send( recipients=recipients, sender=sender, record=self, record_name=record_name, ) @api.one def send_group(self, template, group, sender=None, record_name=None): return self.env.ref(template).send_group( group=group, sender=sender, record=self, record_name=record_name, ) @api.multi def message_get_suggested_recipients(self): """ Used by the messages module (in JS code). No, we don't want to add additional recipients, Odoo. Thanks, but no thanks. """ return [] @api.model def message_redirect_action(self): """ Used by the messages module (in JS code). Returns an action for displaying the related record. """ return self.env['mail.thread'].message_redirect_action() def message_post(self, *args, **kwargs): """ Used by the messages module to reply in a thread. """ return self.pool['mail.thread'].message_post(*args, **kwargs) @api.model def _get_access_link(self, mail, partner): """ Used to generate a link to the associated object in e-mail notification. """ return self.env['mail.thread']._get_access_link(mail, partner) class MailMessage(models.Model): _inherit = 'mail.message' template = fields.Many2one('message_template')
Sergiy-DBX/pynet_test-
refs/heads/master
Strings/Ex_2.py
1
#!/usr/bin/env python from __future__ import print_function try: ip_input = raw_input("Enter IP address: ") except NameError: ip_input = input("Enter IP address: ") digits = ip_input.split('.') for i in digits: print("{:>12}".format(i))
GbalsaC/bitnamiP
refs/heads/master
venv/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/endpoints/authorization.py
71
# -*- coding: utf-8 -*- """ oauthlib.oauth2.rfc6749 ~~~~~~~~~~~~~~~~~~~~~~~ This module is an implementation of various logic needed for consuming and providing OAuth 2.0 RFC6749. """ from __future__ import absolute_import, unicode_literals import logging from oauthlib.common import Request from .base import BaseEndpoint, catch_errors_and_unavailability log = logging.getLogger(__name__) class AuthorizationEndpoint(BaseEndpoint): """Authorization endpoint - used by the client to obtain authorization from the resource owner via user-agent redirection. The authorization endpoint is used to interact with the resource owner and obtain an authorization grant. The authorization server MUST first verify the identity of the resource owner. The way in which the authorization server authenticates the resource owner (e.g. username and password login, session cookies) is beyond the scope of this specification. The endpoint URI MAY include an "application/x-www-form-urlencoded" formatted (per `Appendix B`_) query component, which MUST be retained when adding additional query parameters. The endpoint URI MUST NOT include a fragment component:: https://example.com/path?query=component # OK https://example.com/path?query=component#fragment # Not OK Since requests to the authorization endpoint result in user authentication and the transmission of clear-text credentials (in the HTTP response), the authorization server MUST require the use of TLS as described in Section 1.6 when sending requests to the authorization endpoint:: # We will deny any request which URI schema is not with https The authorization server MUST support the use of the HTTP "GET" method [RFC2616] for the authorization endpoint, and MAY support the use of the "POST" method as well:: # HTTP method is currently not enforced Parameters sent without a value MUST be treated as if they were omitted from the request. The authorization server MUST ignore unrecognized request parameters. Request and response parameters MUST NOT be included more than once:: # Enforced through the design of oauthlib.common.Request .. _`Appendix B`: http://tools.ietf.org/html/rfc6749#appendix-B """ def __init__(self, default_response_type, default_token_type, response_types): BaseEndpoint.__init__(self) self._response_types = response_types self._default_response_type = default_response_type self._default_token_type = default_token_type @property def response_types(self): return self._response_types @property def default_response_type(self): return self._default_response_type @property def default_response_type_handler(self): return self.response_types.get(self.default_response_type) @property def default_token_type(self): return self._default_token_type @catch_errors_and_unavailability def create_authorization_response(self, uri, http_method='GET', body=None, headers=None, scopes=None, credentials=None): """Extract response_type and route to the designated handler.""" request = Request( uri, http_method=http_method, body=body, headers=headers) request.scopes = scopes # TODO: decide whether this should be a required argument request.user = None # TODO: explain this in docs for k, v in (credentials or {}).items(): setattr(request, k, v) response_type_handler = self.response_types.get( request.response_type, self.default_response_type_handler) log.debug('Dispatching response_type %s request to %r.', request.response_type, response_type_handler) return response_type_handler.create_authorization_response( request, self.default_token_type) @catch_errors_and_unavailability def validate_authorization_request(self, uri, http_method='GET', body=None, headers=None): """Extract response_type and route to the designated handler.""" request = Request( uri, http_method=http_method, body=body, headers=headers) request.scopes = None response_type_handler = self.response_types.get( request.response_type, self.default_response_type_handler) return response_type_handler.validate_authorization_request(request)
ltilve/ChromiumGStreamerBackend
refs/heads/master
third_party/tlslite/tlslite/constants.py
11
# Authors: # Trevor Perrin # Google - defining ClientCertificateType # Google (adapted by Sam Rushing) - NPN support # Dimitris Moraitis - Anon ciphersuites # Dave Baggett (Arcode Corporation) - canonicalCipherName # Yngve Pettersen (ported by Paul Sokolovsky) - TLS 1.2 # # See the LICENSE file for legal information regarding use of this file. """Constants used in various places.""" class CertificateType: x509 = 0 openpgp = 1 class ClientCertificateType: # http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-2 rsa_sign = 1 dss_sign = 2 rsa_fixed_dh = 3 dss_fixed_dh = 4 ecdsa_sign = 64 rsa_fixed_ecdh = 65 ecdsa_fixed_ecdh = 66 class HandshakeType: hello_request = 0 client_hello = 1 server_hello = 2 certificate = 11 server_key_exchange = 12 certificate_request = 13 server_hello_done = 14 certificate_verify = 15 client_key_exchange = 16 finished = 20 certificate_status = 22 next_protocol = 67 encrypted_extensions = 203 class ContentType: change_cipher_spec = 20 alert = 21 handshake = 22 application_data = 23 all = (20,21,22,23) class CertificateStatusType: ocsp = 1 class ExtensionType: # RFC 6066 / 4366 server_name = 0 # RFC 6066 / 4366 status_request = 5 # RFC 6066 / 4366 srp = 12 # RFC 5054 cert_type = 9 # RFC 6091 signed_cert_timestamps = 18 # RFC 6962 extended_master_secret = 23 # draft-ietf-tls-session-hash-06 tack = 0xF300 supports_npn = 13172 channel_id = 30032 token_binding = 30033 class HashAlgorithm: none = 0 md5 = 1 sha1 = 2 sha224 = 3 sha256 = 4 sha384 = 5 class SignatureAlgorithm: anonymous = 0 rsa = 1 dsa = 2 ecdsa = 3 class NameType: host_name = 0 class ECCurveType: explicit_prime = 1 explicit_char2 = 2 named_curve = 3 class NamedCurve: secp256r1 = 23 class AlertLevel: warning = 1 fatal = 2 class AlertDescription: """ @cvar bad_record_mac: A TLS record failed to decrypt properly. If this occurs during a SRP handshake it most likely indicates a bad password. It may also indicate an implementation error, or some tampering with the data in transit. This alert will be signalled by the server if the SRP password is bad. It may also be signalled by the server if the SRP username is unknown to the server, but it doesn't wish to reveal that fact. @cvar handshake_failure: A problem occurred while handshaking. This typically indicates a lack of common ciphersuites between client and server, or some other disagreement (about SRP parameters or key sizes, for example). @cvar protocol_version: The other party's SSL/TLS version was unacceptable. This indicates that the client and server couldn't agree on which version of SSL or TLS to use. @cvar user_canceled: The handshake is being cancelled for some reason. """ close_notify = 0 unexpected_message = 10 bad_record_mac = 20 decryption_failed = 21 record_overflow = 22 decompression_failure = 30 handshake_failure = 40 no_certificate = 41 #SSLv3 bad_certificate = 42 unsupported_certificate = 43 certificate_revoked = 44 certificate_expired = 45 certificate_unknown = 46 illegal_parameter = 47 unknown_ca = 48 access_denied = 49 decode_error = 50 decrypt_error = 51 export_restriction = 60 protocol_version = 70 insufficient_security = 71 internal_error = 80 inappropriate_fallback = 86 user_canceled = 90 no_renegotiation = 100 unknown_psk_identity = 115 class CipherSuite: # Weird pseudo-ciphersuite from RFC 5746 # Signals that "secure renegotiation" is supported # We actually don't do any renegotiation, but this # prevents renegotiation attacks TLS_EMPTY_RENEGOTIATION_INFO_SCSV = 0x00FF # draft-ietf-tls-downgrade-scsv-03 TLS_FALLBACK_SCSV = 0x5600 TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA = 0xC01A TLS_SRP_SHA_WITH_AES_128_CBC_SHA = 0xC01D TLS_SRP_SHA_WITH_AES_256_CBC_SHA = 0xC020 TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA = 0xC01B TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA = 0xC01E TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA = 0xC021 TLS_RSA_WITH_3DES_EDE_CBC_SHA = 0x000A TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035 TLS_RSA_WITH_RC4_128_SHA = 0x0005 TLS_RSA_WITH_RC4_128_MD5 = 0x0004 TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x0016 TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033 TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039 TLS_DH_ANON_WITH_AES_128_CBC_SHA = 0x0034 TLS_DH_ANON_WITH_AES_256_CBC_SHA = 0x003A TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067 TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E TLS_ECDHE_RSA_WITH_RC4_128_SHA = 0xc011 TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA = 0xc012 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xc013 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xc014 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xc027 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xc02f tripleDESSuites = [] tripleDESSuites.append(TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA) tripleDESSuites.append(TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA) tripleDESSuites.append(TLS_RSA_WITH_3DES_EDE_CBC_SHA) tripleDESSuites.append(TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA) tripleDESSuites.append(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA) aes128Suites = [] aes128Suites.append(TLS_SRP_SHA_WITH_AES_128_CBC_SHA) aes128Suites.append(TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA) aes128Suites.append(TLS_RSA_WITH_AES_128_CBC_SHA) aes128Suites.append(TLS_DHE_RSA_WITH_AES_128_CBC_SHA) aes128Suites.append(TLS_DH_ANON_WITH_AES_128_CBC_SHA) aes128Suites.append(TLS_RSA_WITH_AES_128_CBC_SHA256) aes128Suites.append(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256) aes128Suites.append(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA) aes128Suites.append(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256) aes256Suites = [] aes256Suites.append(TLS_SRP_SHA_WITH_AES_256_CBC_SHA) aes256Suites.append(TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA) aes256Suites.append(TLS_RSA_WITH_AES_256_CBC_SHA) aes256Suites.append(TLS_DH_ANON_WITH_AES_256_CBC_SHA) aes256Suites.append(TLS_DHE_RSA_WITH_AES_256_CBC_SHA) aes256Suites.append(TLS_RSA_WITH_AES_256_CBC_SHA256) aes256Suites.append(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256) aes256Suites.append(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA) aes128GcmSuites = [] aes128GcmSuites.append(TLS_RSA_WITH_AES_128_GCM_SHA256) aes128GcmSuites.append(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256) aes128GcmSuites.append(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256) rc4Suites = [] rc4Suites.append(TLS_RSA_WITH_RC4_128_SHA) rc4Suites.append(TLS_RSA_WITH_RC4_128_MD5) rc4Suites.append(TLS_ECDHE_RSA_WITH_RC4_128_SHA) shaSuites = [] shaSuites.append(TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA) shaSuites.append(TLS_SRP_SHA_WITH_AES_128_CBC_SHA) shaSuites.append(TLS_SRP_SHA_WITH_AES_256_CBC_SHA) shaSuites.append(TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA) shaSuites.append(TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA) shaSuites.append(TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA) shaSuites.append(TLS_RSA_WITH_3DES_EDE_CBC_SHA) shaSuites.append(TLS_RSA_WITH_AES_128_CBC_SHA) shaSuites.append(TLS_RSA_WITH_AES_256_CBC_SHA) shaSuites.append(TLS_RSA_WITH_RC4_128_SHA) shaSuites.append(TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA) shaSuites.append(TLS_DHE_RSA_WITH_AES_128_CBC_SHA) shaSuites.append(TLS_DHE_RSA_WITH_AES_256_CBC_SHA) shaSuites.append(TLS_DH_ANON_WITH_AES_128_CBC_SHA) shaSuites.append(TLS_DH_ANON_WITH_AES_256_CBC_SHA) shaSuites.append(TLS_ECDHE_RSA_WITH_RC4_128_SHA) shaSuites.append(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA) shaSuites.append(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA) shaSuites.append(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA) sha256Suites = [] sha256Suites.append(TLS_RSA_WITH_AES_128_CBC_SHA256) sha256Suites.append(TLS_RSA_WITH_AES_256_CBC_SHA256) sha256Suites.append(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256) sha256Suites.append(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256) sha256Suites.append(TLS_RSA_WITH_AES_128_GCM_SHA256) sha256Suites.append(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256) sha256Suites.append(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256) sha256Suites.append(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256) aeadSuites = aes128GcmSuites md5Suites = [] md5Suites.append(TLS_RSA_WITH_RC4_128_MD5) @staticmethod def _filterSuites(suites, settings, version=None): if version is None: version = settings.maxVersion macNames = settings.macNames cipherNames = settings.cipherNames keyExchangeNames = settings.keyExchangeNames macSuites = [] if "sha" in macNames: macSuites += CipherSuite.shaSuites if "sha256" in macNames and version >= (3,3): macSuites += CipherSuite.sha256Suites if "md5" in macNames: macSuites += CipherSuite.md5Suites if "aead" in macNames and version >= (3,3): macSuites += CipherSuite.aeadSuites cipherSuites = [] if "aes128gcm" in cipherNames and version >= (3,3): cipherSuites += CipherSuite.aes128GcmSuites if "aes128" in cipherNames: cipherSuites += CipherSuite.aes128Suites if "aes256" in cipherNames: cipherSuites += CipherSuite.aes256Suites if "3des" in cipherNames: cipherSuites += CipherSuite.tripleDESSuites if "rc4" in cipherNames: cipherSuites += CipherSuite.rc4Suites keyExchangeSuites = [] if "rsa" in keyExchangeNames: keyExchangeSuites += CipherSuite.certSuites if "dhe_rsa" in keyExchangeNames: keyExchangeSuites += CipherSuite.dheCertSuites if "ecdhe_rsa" in keyExchangeNames: keyExchangeSuites += CipherSuite.ecdheCertSuites if "srp_sha" in keyExchangeNames: keyExchangeSuites += CipherSuite.srpSuites if "srp_sha_rsa" in keyExchangeNames: keyExchangeSuites += CipherSuite.srpCertSuites if "dh_anon" in keyExchangeNames: keyExchangeSuites += CipherSuite.anonSuites return [s for s in suites if s in macSuites and s in cipherSuites and s in keyExchangeSuites] srpSuites = [] srpSuites.append(TLS_SRP_SHA_WITH_AES_256_CBC_SHA) srpSuites.append(TLS_SRP_SHA_WITH_AES_128_CBC_SHA) srpSuites.append(TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA) @staticmethod def getSrpSuites(settings, version=None): return CipherSuite._filterSuites(CipherSuite.srpSuites, settings, version) srpCertSuites = [] srpCertSuites.append(TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA) srpCertSuites.append(TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA) srpCertSuites.append(TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA) @staticmethod def getSrpCertSuites(settings, version=None): return CipherSuite._filterSuites(CipherSuite.srpCertSuites, settings, version) srpAllSuites = srpSuites + srpCertSuites @staticmethod def getSrpAllSuites(settings, version=None): return CipherSuite._filterSuites(CipherSuite.srpAllSuites, settings, version) certSuites = [] certSuites.append(TLS_RSA_WITH_AES_128_GCM_SHA256) certSuites.append(TLS_RSA_WITH_AES_256_CBC_SHA256) certSuites.append(TLS_RSA_WITH_AES_128_CBC_SHA256) certSuites.append(TLS_RSA_WITH_AES_256_CBC_SHA) certSuites.append(TLS_RSA_WITH_AES_128_CBC_SHA) certSuites.append(TLS_RSA_WITH_3DES_EDE_CBC_SHA) certSuites.append(TLS_RSA_WITH_RC4_128_SHA) certSuites.append(TLS_RSA_WITH_RC4_128_MD5) @staticmethod def getCertSuites(settings, version=None): return CipherSuite._filterSuites(CipherSuite.certSuites, settings, version) dheCertSuites = [] dheCertSuites.append(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256) dheCertSuites.append(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256) dheCertSuites.append(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256) dheCertSuites.append(TLS_DHE_RSA_WITH_AES_256_CBC_SHA) dheCertSuites.append(TLS_DHE_RSA_WITH_AES_128_CBC_SHA) dheCertSuites.append(TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA) @staticmethod def getDheCertSuites(settings, version=None): return CipherSuite._filterSuites(CipherSuite.dheCertSuites, settings, version) ecdheCertSuites = [] ecdheCertSuites.append(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256) ecdheCertSuites.append(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256) ecdheCertSuites.append(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA) ecdheCertSuites.append(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA) ecdheCertSuites.append(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA) ecdheCertSuites.append(TLS_ECDHE_RSA_WITH_RC4_128_SHA) @staticmethod def getEcdheCertSuites(settings, version=None): return CipherSuite._filterSuites(CipherSuite.ecdheCertSuites, settings, version) certAllSuites = srpCertSuites + certSuites + dheCertSuites + ecdheCertSuites anonSuites = [] anonSuites.append(TLS_DH_ANON_WITH_AES_256_CBC_SHA) anonSuites.append(TLS_DH_ANON_WITH_AES_128_CBC_SHA) @staticmethod def getAnonSuites(settings, version=None): return CipherSuite._filterSuites(CipherSuite.anonSuites, settings, version) dhAllSuites = dheCertSuites + anonSuites ecdhAllSuites = ecdheCertSuites @staticmethod def canonicalCipherName(ciphersuite): "Return the canonical name of the cipher whose number is provided." if ciphersuite in CipherSuite.aes128Suites: return "aes128" elif ciphersuite in CipherSuite.aes256Suites: return "aes256" elif ciphersuite in CipherSuite.rc4Suites: return "rc4" elif ciphersuite in CipherSuite.tripleDESSuites: return "3des" else: return None @staticmethod def canonicalMacName(ciphersuite): "Return the canonical name of the MAC whose number is provided." if ciphersuite in CipherSuite.shaSuites: return "sha" elif ciphersuite in CipherSuite.md5Suites: return "md5" else: return None # The following faults are induced as part of testing. The faultAlerts # dictionary describes the allowed alerts that may be triggered by these # faults. class Fault: badUsername = 101 badPassword = 102 badA = 103 clientSrpFaults = list(range(101,104)) badVerifyMessage = 601 clientCertFaults = list(range(601,602)) badPremasterPadding = 501 shortPremasterSecret = 502 clientNoAuthFaults = list(range(501,503)) badB = 201 serverFaults = list(range(201,202)) badFinished = 300 badMAC = 301 badPadding = 302 genericFaults = list(range(300,303)) faultAlerts = {\ badUsername: (AlertDescription.unknown_psk_identity, \ AlertDescription.bad_record_mac),\ badPassword: (AlertDescription.bad_record_mac,),\ badA: (AlertDescription.illegal_parameter,),\ badPremasterPadding: (AlertDescription.bad_record_mac,),\ shortPremasterSecret: (AlertDescription.bad_record_mac,),\ badVerifyMessage: (AlertDescription.decrypt_error,),\ badFinished: (AlertDescription.decrypt_error,),\ badMAC: (AlertDescription.bad_record_mac,),\ badPadding: (AlertDescription.bad_record_mac,) } faultNames = {\ badUsername: "bad username",\ badPassword: "bad password",\ badA: "bad A",\ badPremasterPadding: "bad premaster padding",\ shortPremasterSecret: "short premaster secret",\ badVerifyMessage: "bad verify message",\ badFinished: "bad finished message",\ badMAC: "bad MAC",\ badPadding: "bad padding" }
eunchong/build
refs/heads/master
third_party/buildbot_8_4p1/buildbot/test/unit/test_db_changes.py
4
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import mock import pprint import sqlalchemy as sa from twisted.trial import unittest from twisted.internet import defer, task from buildbot.changes.changes import Change from buildbot.db import changes from buildbot.test.util import connector_component from buildbot.test.fake import fakedb from buildbot.util import epoch2datetime class TestChangesConnectorComponent( connector_component.ConnectorComponentMixin, unittest.TestCase): def setUp(self): d = self.setUpConnectorComponent( table_names=['changes', 'change_links', 'change_files', 'change_properties', 'scheduler_changes', 'schedulers', 'sourcestamps', 'sourcestamp_changes', 'patches' ]) def finish_setup(_): self.db.changes = changes.ChangesConnectorComponent(self.db) d.addCallback(finish_setup) return d def tearDown(self): return self.tearDownConnectorComponent() # common sample data change13_rows = [ fakedb.Change(changeid=13, author="dustin", comments="fix spelling", is_dir=0, branch="master", revision="deadbeef", when_timestamp=266738400, revlink=None, category=None, repository='', project=''), fakedb.ChangeLink(changeid=13, link='http://buildbot.net'), fakedb.ChangeLink(changeid=13, link='http://sf.net/projects/buildbot'), fakedb.ChangeFile(changeid=13, filename='master/README.txt'), fakedb.ChangeFile(changeid=13, filename='slave/README.txt'), fakedb.ChangeProperty(changeid=13, property_name='notest', property_value='["no","Change"]'), ] change14_rows = [ fakedb.Change(changeid=14, author="warner", comments="fix whitespace", is_dir=0, branch="warnerdb", revision="0e92a098b", when_timestamp=266738404, revlink='http://warner/0e92a098b', category='devel', repository='git://warner', project='Buildbot'), fakedb.ChangeFile(changeid=14, filename='master/buildbot/__init__.py'), ] change14_dict = { 'changeid': 14, 'author': u'warner', 'branch': u'warnerdb', 'category': u'devel', 'comments': u'fix whitespace', 'files': [u'master/buildbot/__init__.py'], 'is_dir': 0, 'links': [], 'project': u'Buildbot', 'properties': {}, 'repository': u'git://warner', 'revision': u'0e92a098b', 'revlink': u'http://warner/0e92a098b', 'when_timestamp': epoch2datetime(266738404), } def change14(self): c = Change(**dict( category='devel', isdir=0, repository=u'git://warner', links=[], who=u'warner', when=266738404, comments=u'fix whitespace', project=u'Buildbot', branch=u'warnerdb', revlink=u'http://warner/0e92a098b', properties={}, files=[u'master/buildbot/__init__.py'], revision=u'0e92a098b')) c.number = 14 return c # assertions def assertChangesEqual(self, ca, cb): ok = True ok = ok and ca.number == cb.number ok = ok and ca.who == cb.who ok = ok and sorted(ca.files) == sorted(cb.files) ok = ok and ca.comments == cb.comments ok = ok and bool(ca.isdir) == bool(cb.isdir) ok = ok and sorted(ca.links) == sorted(cb.links) ok = ok and ca.revision == cb.revision ok = ok and ca.when == cb.when ok = ok and ca.branch == cb.branch ok = ok and ca.category == cb.category ok = ok and ca.revlink == cb.revlink ok = ok and ca.properties == cb.properties ok = ok and ca.repository == cb.repository ok = ok and ca.project == cb.project if not ok: def printable(c): return pprint.pformat(c.__dict__) self.fail("changes do not match; expected\n%s\ngot\n%s" % (printable(ca), printable(cb))) # tests def test_getChange(self): d = self.insertTestData(self.change14_rows) def get14(_): return self.db.changes.getChange(14) d.addCallback(get14) def check14(chdict): self.assertEqual(chdict, self.change14_dict) d.addCallback(check14) return d def test_Change_fromChdict_with_chdict(self): # test that the chdict getChange returns works with Change.fromChdict d = Change.fromChdict(mock.Mock(), self.change14_dict) def check(c): self.assertChangesEqual(c, self.change14()) d.addCallback(check) return d def test_getChange_missing(self): d = defer.succeed(None) def get14(_): return self.db.changes.getChange(14) d.addCallback(get14) def check14(chdict): self.failUnless(chdict is None) d.addCallback(check14) return d def test_getLatestChangeid(self): d = self.insertTestData(self.change13_rows) def get(_): return self.db.changes.getLatestChangeid() d.addCallback(get) def check(changeid): self.assertEqual(changeid, 13) d.addCallback(check) return d def test_getLatestChangeid_empty(self): d = defer.succeed(None) def get(_): return self.db.changes.getLatestChangeid() d.addCallback(get) def check(changeid): self.assertEqual(changeid, None) d.addCallback(check) return d def test_addChange(self): d = self.db.changes.addChange( author=u'dustin', files=[u'master/LICENSING.txt', u'slave/LICENSING.txt'], comments=u'fix spelling', is_dir=0, links=[u'http://slashdot.org', u'http://wired.com/g'], revision=u'2d6caa52', when_timestamp=epoch2datetime(266738400), branch=u'master', category=None, revlink=None, properties={u'platform': (u'linux', 'Change')}, repository=u'', project=u'') # check all of the columns of the four relevant tables def check_change(changeid): def thd(conn): self.assertEqual(changeid, 1) r = conn.execute(self.db.model.changes.select()) r = r.fetchall() self.assertEqual(len(r), 1) self.assertEqual(r[0].changeid, changeid) self.assertEqual(r[0].author, 'dustin') self.assertEqual(r[0].comments, 'fix spelling') self.assertFalse(r[0].is_dir) self.assertEqual(r[0].branch, 'master') self.assertEqual(r[0].revision, '2d6caa52') self.assertEqual(r[0].when_timestamp, 266738400) self.assertEqual(r[0].category, None) self.assertEqual(r[0].repository, '') self.assertEqual(r[0].project, '') return self.db.pool.do(thd) d.addCallback(check_change) def check_change_links(_): def thd(conn): query = self.db.model.change_links.select() query.where(self.db.model.change_links.c.changeid == 1) query.order_by(self.db.model.change_links.c.link) r = conn.execute(query) r = r.fetchall() self.assertEqual(len(r), 2) self.assertEqual(r[0].link, 'http://slashdot.org') self.assertEqual(r[1].link, 'http://wired.com/g') return self.db.pool.do(thd) d.addCallback(check_change_links) def check_change_files(_): def thd(conn): query = self.db.model.change_files.select() query.where(self.db.model.change_files.c.changeid == 1) query.order_by(self.db.model.change_files.c.filename) r = conn.execute(query) r = r.fetchall() self.assertEqual(len(r), 2) self.assertEqual(r[0].filename, 'master/LICENSING.txt') self.assertEqual(r[1].filename, 'slave/LICENSING.txt') return self.db.pool.do(thd) d.addCallback(check_change_files) def check_change_properties(_): def thd(conn): query = self.db.model.change_properties.select() query.where(self.db.model.change_properties.c.changeid == 1) query.order_by(self.db.model.change_properties.c.property_name) r = conn.execute(query) r = r.fetchall() self.assertEqual(len(r), 1) self.assertEqual(r[0].property_name, 'platform') self.assertEqual(r[0].property_value, '["linux", "Change"]') return self.db.pool.do(thd) d.addCallback(check_change_properties) return d def test_addChange_when_timestamp_None(self): clock = task.Clock() clock.advance(1239898353) d = self.db.changes.addChange( author=u'dustin', files=[], comments=u'fix spelling', is_dir=0, links=[], revision=u'2d6caa52', when_timestamp=None, branch=u'master', category=None, revlink=None, properties={}, repository=u'', project=u'', _reactor=clock) # check all of the columns of the four relevant tables def check_change(changeid): def thd(conn): r = conn.execute(self.db.model.changes.select()) r = r.fetchall() self.assertEqual(len(r), 1) self.assertEqual(r[0].changeid, changeid) self.assertEqual(r[0].when_timestamp, 1239898353) return self.db.pool.do(thd) d.addCallback(check_change) def check_change_links(_): def thd(conn): query = self.db.model.change_links.select() r = conn.execute(query) r = r.fetchall() self.assertEqual(len(r), 0) return self.db.pool.do(thd) d.addCallback(check_change_links) def check_change_files(_): def thd(conn): query = self.db.model.change_files.select() r = conn.execute(query) r = r.fetchall() self.assertEqual(len(r), 0) return self.db.pool.do(thd) d.addCallback(check_change_files) def check_change_properties(_): def thd(conn): query = self.db.model.change_properties.select() r = conn.execute(query) r = r.fetchall() self.assertEqual(len(r), 0) return self.db.pool.do(thd) d.addCallback(check_change_properties) return d def test_pruneChanges(self): d = self.insertTestData([ fakedb.Scheduler(schedulerid=29), fakedb.SourceStamp(id=234), fakedb.Change(changeid=11), fakedb.Change(changeid=12), fakedb.SchedulerChange(schedulerid=29, changeid=12), fakedb.SourceStampChange(sourcestampid=234, changeid=12), ] + self.change13_rows + [ fakedb.SchedulerChange(schedulerid=29, changeid=13), ] + self.change14_rows + [ fakedb.SchedulerChange(schedulerid=29, changeid=14), fakedb.Change(changeid=15), fakedb.SourceStampChange(sourcestampid=234, changeid=15), ] ) # pruning with a horizon of 2 should delete changes 11, 12 and 13 d.addCallback(lambda _ : self.db.changes.pruneChanges(2)) def check(_): def thd(conn): results = {} for tbl_name in ('scheduler_changes', 'sourcestamp_changes', 'change_files', 'change_links', 'change_properties', 'changes'): tbl = self.db.model.metadata.tables[tbl_name] r = conn.execute(sa.select([tbl.c.changeid])) results[tbl_name] = sorted([ r[0] for r in r.fetchall() ]) self.assertEqual(results, { 'scheduler_changes': [14], 'sourcestamp_changes': [15], 'change_files': [14], 'change_links': [], 'change_properties': [], 'changes': [14, 15], }) return self.db.pool.do(thd) d.addCallback(check) return d def test_pruneChanges_None(self): d = self.insertTestData(self.change13_rows) d.addCallback(lambda _ : self.db.changes.pruneChanges(None)) def check(_): def thd(conn): tbl = self.db.model.changes r = conn.execute(tbl.select()) self.assertEqual([ row.changeid for row in r.fetchall() ], [ 13 ]) return self.db.pool.do(thd) d.addCallback(check) return d def test_getRecentChanges_subset(self): d = self.insertTestData([ fakedb.Change(changeid=8), fakedb.Change(changeid=9), fakedb.Change(changeid=10), fakedb.Change(changeid=11), fakedb.Change(changeid=12), ] + self.change13_rows + self.change14_rows) d.addCallback(lambda _ : self.db.changes.getRecentChanges(5)) def check(changes): changeids = [ c['changeid'] for c in changes ] self.assertEqual(changeids, [10, 11, 12, 13, 14]) d.addCallback(check) return d def test_getRecentChanges_empty(self): d = defer.succeed(None) d.addCallback(lambda _ : self.db.changes.getRecentChanges(5)) def check(changes): changeids = [ c['changeid'] for c in changes ] self.assertEqual(changeids, []) d.addCallback(check) return d def test_getRecentChanges_missing(self): d = self.insertTestData(self.change13_rows + self.change14_rows) d.addCallback(lambda _ : self.db.changes.getRecentChanges(5)) def check(changes): # requested 5, but only got 2 changeids = [ c['changeid'] for c in changes ] self.assertEqual(changeids, [13, 14]) # double-check that they have .files, etc. self.assertEqual(sorted(changes[0]['files']), sorted(['master/README.txt', 'slave/README.txt'])) self.assertEqual(sorted(changes[0]['links']), sorted(['http://buildbot.net', 'http://sf.net/projects/buildbot'])) self.assertEqual(changes[0]['properties'], { 'notest' : ('no', 'Change') }) d.addCallback(check) return d
jhawkesworth/ansible
refs/heads/devel
lib/ansible/modules/cloud/amazon/ec2_snapshot.py
71
#!/usr/bin/python # Copyright: 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 ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = ''' --- module: ec2_snapshot short_description: creates a snapshot from an existing volume description: - creates an EC2 snapshot from an existing EBS volume version_added: "1.5" options: volume_id: description: - volume from which to take the snapshot required: false description: description: - description to be applied to the snapshot required: false instance_id: description: - instance that has the required volume to snapshot mounted required: false device_name: description: - device name of a mounted volume to be snapshotted required: false snapshot_tags: description: - a hash/dictionary of tags to add to the snapshot required: false version_added: "1.6" wait: description: - wait for the snapshot to be ready type: bool required: false default: yes version_added: "1.5.1" wait_timeout: description: - how long before wait gives up, in seconds - specify 0 to wait forever required: false default: 0 version_added: "1.5.1" state: description: - whether to add or create a snapshot required: false default: present choices: ['absent', 'present'] version_added: "1.9" snapshot_id: description: - snapshot id to remove required: false version_added: "1.9" last_snapshot_min_age: description: - If the volume's most recent snapshot has started less than `last_snapshot_min_age' minutes ago, a new snapshot will not be created. required: false default: 0 version_added: "2.0" author: "Will Thames (@willthames)" extends_documentation_fragment: - aws - ec2 ''' EXAMPLES = ''' # Simple snapshot of volume using volume_id - ec2_snapshot: volume_id: vol-abcdef12 description: snapshot of /data from DB123 taken 2013/11/28 12:18:32 # Snapshot of volume mounted on device_name attached to instance_id - ec2_snapshot: instance_id: i-12345678 device_name: /dev/sdb1 description: snapshot of /data from DB123 taken 2013/11/28 12:18:32 # Snapshot of volume with tagging - ec2_snapshot: instance_id: i-12345678 device_name: /dev/sdb1 snapshot_tags: frequency: hourly source: /data # Remove a snapshot - local_action: module: ec2_snapshot snapshot_id: snap-abcd1234 state: absent # Create a snapshot only if the most recent one is older than 1 hour - local_action: module: ec2_snapshot volume_id: vol-abcdef12 last_snapshot_min_age: 60 ''' import time import datetime try: import boto.exception except ImportError: pass # Taken care of by ec2.HAS_BOTO from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import HAS_BOTO, ec2_argument_spec, ec2_connect # Find the most recent snapshot def _get_snapshot_starttime(snap): return datetime.datetime.strptime(snap.start_time, '%Y-%m-%dT%H:%M:%S.000Z') def _get_most_recent_snapshot(snapshots, max_snapshot_age_secs=None, now=None): """ Gets the most recently created snapshot and optionally filters the result if the snapshot is too old :param snapshots: list of snapshots to search :param max_snapshot_age_secs: filter the result if its older than this :param now: simulate time -- used for unit testing :return: """ if len(snapshots) == 0: return None if not now: now = datetime.datetime.utcnow() youngest_snapshot = max(snapshots, key=_get_snapshot_starttime) # See if the snapshot is younger that the given max age snapshot_start = datetime.datetime.strptime(youngest_snapshot.start_time, '%Y-%m-%dT%H:%M:%S.000Z') snapshot_age = now - snapshot_start if max_snapshot_age_secs is not None: if snapshot_age.total_seconds() > max_snapshot_age_secs: return None return youngest_snapshot def _create_with_wait(snapshot, wait_timeout_secs, sleep_func=time.sleep): """ Wait for the snapshot to be created :param snapshot: :param wait_timeout_secs: fail this step after this many seconds :param sleep_func: :return: """ time_waited = 0 snapshot.update() while snapshot.status != 'completed': sleep_func(3) snapshot.update() time_waited += 3 if wait_timeout_secs and time_waited > wait_timeout_secs: return False return True def create_snapshot(module, ec2, state=None, description=None, wait=None, wait_timeout=None, volume_id=None, instance_id=None, snapshot_id=None, device_name=None, snapshot_tags=None, last_snapshot_min_age=None): snapshot = None changed = False required = [volume_id, snapshot_id, instance_id] if required.count(None) != len(required) - 1: # only 1 must be set module.fail_json(msg='One and only one of volume_id or instance_id or snapshot_id must be specified') if instance_id and not device_name or device_name and not instance_id: module.fail_json(msg='Instance ID and device name must both be specified') if instance_id: try: volumes = ec2.get_all_volumes(filters={'attachment.instance-id': instance_id, 'attachment.device': device_name}) except boto.exception.BotoServerError as e: module.fail_json(msg="%s: %s" % (e.error_code, e.error_message)) if not volumes: module.fail_json(msg="Could not find volume with name %s attached to instance %s" % (device_name, instance_id)) volume_id = volumes[0].id if state == 'absent': if not snapshot_id: module.fail_json(msg='snapshot_id must be set when state is absent') try: ec2.delete_snapshot(snapshot_id) except boto.exception.BotoServerError as e: # exception is raised if snapshot does not exist if e.error_code == 'InvalidSnapshot.NotFound': module.exit_json(changed=False) else: module.fail_json(msg="%s: %s" % (e.error_code, e.error_message)) # successful delete module.exit_json(changed=True) if last_snapshot_min_age > 0: try: current_snapshots = ec2.get_all_snapshots(filters={'volume_id': volume_id}) except boto.exception.BotoServerError as e: module.fail_json(msg="%s: %s" % (e.error_code, e.error_message)) last_snapshot_min_age = last_snapshot_min_age * 60 # Convert to seconds snapshot = _get_most_recent_snapshot(current_snapshots, max_snapshot_age_secs=last_snapshot_min_age) try: # Create a new snapshot if we didn't find an existing one to use if snapshot is None: snapshot = ec2.create_snapshot(volume_id, description=description) changed = True if wait: if not _create_with_wait(snapshot, wait_timeout): module.fail_json(msg='Timed out while creating snapshot.') if snapshot_tags: for k, v in snapshot_tags.items(): snapshot.add_tag(k, v) except boto.exception.BotoServerError as e: module.fail_json(msg="%s: %s" % (e.error_code, e.error_message)) module.exit_json(changed=changed, snapshot_id=snapshot.id, volume_id=snapshot.volume_id, volume_size=snapshot.volume_size, tags=snapshot.tags.copy()) def create_snapshot_ansible_module(): argument_spec = ec2_argument_spec() argument_spec.update( dict( volume_id=dict(), description=dict(), instance_id=dict(), snapshot_id=dict(), device_name=dict(), wait=dict(type='bool', default=True), wait_timeout=dict(type='int', default=0), last_snapshot_min_age=dict(type='int', default=0), snapshot_tags=dict(type='dict', default=dict()), state=dict(choices=['absent', 'present'], default='present'), ) ) module = AnsibleModule(argument_spec=argument_spec) return module def main(): module = create_snapshot_ansible_module() if not HAS_BOTO: module.fail_json(msg='boto required for this module') volume_id = module.params.get('volume_id') snapshot_id = module.params.get('snapshot_id') description = module.params.get('description') instance_id = module.params.get('instance_id') device_name = module.params.get('device_name') wait = module.params.get('wait') wait_timeout = module.params.get('wait_timeout') last_snapshot_min_age = module.params.get('last_snapshot_min_age') snapshot_tags = module.params.get('snapshot_tags') state = module.params.get('state') ec2 = ec2_connect(module) create_snapshot( module=module, state=state, description=description, wait=wait, wait_timeout=wait_timeout, ec2=ec2, volume_id=volume_id, instance_id=instance_id, snapshot_id=snapshot_id, device_name=device_name, snapshot_tags=snapshot_tags, last_snapshot_min_age=last_snapshot_min_age ) if __name__ == '__main__': main()
WeZZard/ShadowVPN
refs/heads/master
tools/gen_foreign_sh.py
169
#!/usr/bin/env python3 # # Copyright (c) 2014 clowwindy # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from ipaddress import ip_network import sys print('''#!/bin/sh tun=tun0 add_or_delete=add if [ "$1" == "down" ] || [ "$1" == "del" ]; then add_or_delete=del fi ''') for line in sys.stdin: line = line.strip() if not line: continue elif line.startswith('#'): continue subnet = ip_network(line) print('route $add_or_delete -net %s netmask %s $tun' % (subnet.network_address, subnet.netmask))
allenai/allennlp
refs/heads/master
allennlp/modules/token_embedders/empty_embedder.py
1
import torch from allennlp.modules.token_embedders.token_embedder import TokenEmbedder @TokenEmbedder.register("empty") class EmptyEmbedder(TokenEmbedder): """ Assumes you want to completely ignore the output of a `TokenIndexer` for some reason, and does not return anything when asked to embed it. You should almost never need to use this; normally you would just not use a particular `TokenIndexer`. It's only in very rare cases, like simplicity in data processing for language modeling (where we use just one `TextField` to handle input embedding and computing target ids), where you might want to use this. Registered as a `TokenEmbedder` with name "empty". """ def __init__(self) -> None: super().__init__() def get_output_dim(self): return 0 def forward(self, *inputs, **kwargs) -> torch.Tensor: return None
jjmiranda/edx-platform
refs/heads/master
openedx/core/djangoapps/theming/core.py
10
""" Core logic for Comprehensive Theming. """ from django.conf import settings from .helpers import get_themes from logging import getLogger logger = getLogger(__name__) # pylint: disable=invalid-name def enable_theming(): """ Add directories and relevant paths to settings for comprehensive theming. """ # Deprecated Warnings if hasattr(settings, "COMPREHENSIVE_THEME_DIR"): logger.warning( "\033[93m \nDeprecated: " "\n\tCOMPREHENSIVE_THEME_DIR setting has been deprecated in favor of COMPREHENSIVE_THEME_DIRS.\033[00m" ) for theme in get_themes(): locale_dir = theme.path / "conf" / "locale" if locale_dir.isdir(): settings.LOCALE_PATHS = (locale_dir, ) + settings.LOCALE_PATHS if theme.themes_base_dir not in settings.MAKO_TEMPLATES['main']: settings.MAKO_TEMPLATES['main'].insert(0, theme.themes_base_dir)
kevin-coder/tensorflow-fork
refs/heads/master
tensorflow/python/kernel_tests/sparse_ops_test.py
10
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for Python ops defined in sparse_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradient_checker from tensorflow.python.ops import nn_ops from tensorflow.python.ops import sparse_ops from tensorflow.python.ops import variables import tensorflow.python.ops.sparse_grad # pylint: disable=unused-import from tensorflow.python.platform import googletest from tensorflow.python.platform import test # TODO(zongheng): it'd be great to factor out this function and various random # SparseTensor gen funcs. def _sparsify(x, thresh=0.5, index_dtype=np.int64): x[x < thresh] = 0 non_zero = np.where(x) x_indices = np.vstack(non_zero).astype(index_dtype).T x_values = x[non_zero] x_shape = x.shape return sparse_tensor.SparseTensor( indices=x_indices, values=x_values, dense_shape=x_shape), len(x_values) class SparseToIndicatorTest(test_util.TensorFlowTestCase): def _SparseTensor_5x6(self, dtype): ind = np.array([[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]]) val = np.array([0, 10, 13, 14, 32, 33]) shape = np.array([5, 6]) return sparse_tensor.SparseTensor( constant_op.constant(ind, dtypes.int64), constant_op.constant(val, dtype), constant_op.constant(shape, dtypes.int64)) def _SparseTensor_2x3x4(self, dtype): # Includes two entries with the form [1, 1, x] : 150. ind = np.array([[0, 0, 1], [0, 1, 0], [0, 1, 2], [1, 0, 3], [1, 1, 0], [1, 1, 1], [1, 1, 2], [1, 2, 2]]) val = np.array([1, 10, 12, 103, 150, 149, 150, 122]) shape = np.array([2, 3, 4]) return sparse_tensor.SparseTensor( constant_op.constant(ind, dtypes.int64), constant_op.constant(val, dtype), constant_op.constant(shape, dtypes.int64)) def testInt32(self): with test_util.force_cpu(): sp_input = self._SparseTensor_5x6(dtypes.int32) output = sparse_ops.sparse_to_indicator(sp_input, 50) expected_output = np.zeros((5, 50), dtype=np.bool) expected_trues = ((0, 0), (1, 10), (1, 13), (1, 14), (3, 32), (3, 33)) for expected_true in expected_trues: expected_output[expected_true] = True self.assertAllEqual(output, expected_output) def testInt64(self): with test_util.force_cpu(): sp_input = self._SparseTensor_5x6(dtypes.int64) output = sparse_ops.sparse_to_indicator(sp_input, 50) expected_output = np.zeros((5, 50), dtype=np.bool) expected_trues = [(0, 0), (1, 10), (1, 13), (1, 14), (3, 32), (3, 33)] for expected_true in expected_trues: expected_output[expected_true] = True self.assertAllEqual(output, expected_output) def testHigherRank(self): with test_util.force_cpu(): sp_input = self._SparseTensor_2x3x4(dtypes.int64) output = sparse_ops.sparse_to_indicator(sp_input, 200) expected_output = np.zeros((2, 3, 200), dtype=np.bool) expected_trues = [(0, 0, 1), (0, 1, 10), (0, 1, 12), (1, 0, 103), (1, 1, 149), (1, 1, 150), (1, 2, 122)] for expected_true in expected_trues: expected_output[expected_true] = True self.assertAllEqual(output, expected_output) class SparseMergeTest(test_util.TensorFlowTestCase): def _SparseTensorValue_3x50(self, indices_dtype, values_dtype): # NOTE: This input is intentionally not sorted to validate the # already_sorted flag below. ind = np.array([[0, 0], [1, 0], [1, 2], [2, 0], [2, 1], [1, 1]]) # NB: these are not sorted indices = np.array([0, 13, 10, 33, 32, 14]) values = np.array([-3, 4, 1, 9, 5, 1]) shape = np.array([3, 3]) indices = sparse_tensor.SparseTensorValue( np.array(ind, np.int64), np.array(indices, indices_dtype), np.array(shape, np.int64)) values = sparse_tensor.SparseTensorValue( np.array(ind, np.int64), np.array(values, values_dtype), np.array(shape, np.int64)) return indices, values def _SparseTensor_3x50(self, indices_dtype, values_dtype): indices, values = self._SparseTensorValue_3x50(indices_dtype, values_dtype) return (sparse_tensor.SparseTensor.from_value(indices), sparse_tensor.SparseTensor.from_value(values)) def _AssertResultsSorted(self, output, vocab_size): self.assertAllEqual(output.indices, [[0, 0], [1, 10], [1, 13], [1, 14], [2, 32], [2, 33]]) self.assertAllEqual(output.values, [-3, 1, 4, 1, 5, 9]) self.assertAllEqual(output.dense_shape, [3, vocab_size]) def _AssertResultsNotSorted(self, output, vocab_size): self.assertAllEqual(output.indices, [[0, 0], [1, 13], [1, 10], [2, 33], [2, 32], [1, 14]]) self.assertAllEqual(output.values, [-3, 4, 1, 9, 5, 1]) self.assertAllEqual(output.dense_shape, [3, vocab_size]) def testInt32AndFloat32(self): vocab_size = 50 indices_v, values_v = self._SparseTensorValue_3x50(np.int32, np.float32) with test_util.force_cpu(): for indices in (indices_v, sparse_tensor.SparseTensor.from_value(indices_v)): for values in (values_v, sparse_tensor.SparseTensor.from_value(values_v)): sp_output = sparse_ops.sparse_merge(indices, values, vocab_size) output = self.evaluate(sp_output) self._AssertResultsSorted(output, vocab_size) def testInt64AndFloat32(self): vocab_size = 50 with test_util.force_cpu(): indices, values = self._SparseTensor_3x50(np.int64, np.float32) sp_output = sparse_ops.sparse_merge(indices, values, vocab_size) output = self.evaluate(sp_output) self._AssertResultsSorted(output, vocab_size) def testInt64AndFloat64(self): vocab_size = 50 with test_util.force_cpu(): indices, values = self._SparseTensor_3x50(np.int64, np.float64) sp_output = sparse_ops.sparse_merge(indices, values, vocab_size) output = self.evaluate(sp_output) self._AssertResultsSorted(output, vocab_size) def testInt32AndFloat32NonCanonicalOrder(self): vocab_size = 50 with test_util.force_cpu(): indices, values = self._SparseTensor_3x50(np.int32, np.float32) sp_output = sparse_ops.sparse_merge( indices, values, vocab_size, already_sorted=True) output = self.evaluate(sp_output) self._AssertResultsNotSorted(output, vocab_size) def testInt64AndFloat32NonCanonicalOrder(self): vocab_size = 50 with test_util.force_cpu(): indices, values = self._SparseTensor_3x50(np.int64, np.float32) sp_output = sparse_ops.sparse_merge( indices, values, vocab_size, already_sorted=True) output = self.evaluate(sp_output) self._AssertResultsNotSorted(output, vocab_size) def testInt64AndFloat64NonCanonicalOrder(self): vocab_size = 50 vocab_size_tensor = constant_op.constant(vocab_size, dtypes.int64) with test_util.force_cpu(): indices, values = self._SparseTensor_3x50(np.int64, np.float64) sp_output = sparse_ops.sparse_merge( indices, values, vocab_size_tensor, already_sorted=True) output = self.evaluate(sp_output) self._AssertResultsNotSorted(output, vocab_size) def testShouldSetLastDimensionInDynamicShape(self): with ops.Graph().as_default(): shape = constant_op.constant([2, 2], dtype=dtypes.int64) dynamic_shape = array_ops.placeholder_with_default(shape, shape=[2]) ids = sparse_tensor.SparseTensor( indices=[[0, 0], [0, 1]], values=[1, 3], dense_shape=dynamic_shape) values = sparse_tensor.SparseTensor( indices=[[0, 0], [0, 1]], values=[0.4, 0.7], dense_shape=dynamic_shape) merged = sparse_ops.sparse_merge( sp_ids=ids, sp_values=values, vocab_size=5) self.assertEqual(5, merged.get_shape()[1]) class SparseMergeHighDimTest(test_util.TensorFlowTestCase): def _SparseTensor_3x50(self, indices_dtype, values_dtype): # NOTE: This input is intentionally not sorted to validate the # already_sorted flag below. ind = np.array([[0, 0], [1, 0], [1, 2], [2, 0], [2, 1], [1, 1]]) # NB: these are not sorted indices0 = np.array([0, 13, 10, 33, 32, 14]) indices1 = np.array([12, 4, 0, 0, 1, 30]) values = np.array([-3, 4, 1, 9, 5, 1]) shape = np.array([3, 3]) indices0 = sparse_tensor.SparseTensorValue( np.array(ind, np.int64), np.array(indices0, indices_dtype), np.array(shape, np.int64)) indices1 = sparse_tensor.SparseTensorValue( np.array(ind, np.int64), np.array(indices1, indices_dtype), np.array(shape, np.int64)) values = sparse_tensor.SparseTensorValue( np.array(ind, np.int64), np.array(values, values_dtype), np.array(shape, np.int64)) return ([sparse_tensor.SparseTensor.from_value(indices0), sparse_tensor.SparseTensor.from_value(indices1)], sparse_tensor.SparseTensor.from_value(values)) def _AssertResultsSorted(self, output, vocab_size): self.assertAllEqual( output.indices, [[0, 0, 12], [1, 10, 0], [1, 13, 4], [1, 14, 30], [2, 32, 1], [2, 33, 0]]) self.assertAllEqual(output.values, [-3, 1, 4, 1, 5, 9]) self.assertAllEqual(output.dense_shape, [3] + vocab_size) def testInt64AndFloat32(self): vocab_size = [50, 31] with test_util.force_cpu(): indices, values = self._SparseTensor_3x50(np.int64, np.float32) sp_output = sparse_ops.sparse_merge(indices, values, vocab_size) output = self.evaluate(sp_output) self._AssertResultsSorted(output, vocab_size) def testInt64AndFloat64(self): vocab_size = [50, 31] with test_util.force_cpu(): indices, values = self._SparseTensor_3x50(np.int64, np.float64) sp_output = sparse_ops.sparse_merge(indices, values, vocab_size) output = self.evaluate(sp_output) self._AssertResultsSorted(output, vocab_size) def testInt64AndFloat64Shape(self): vocab_size = [50, 30] with test_util.force_cpu(): indices, values = self._SparseTensor_3x50(np.int64, np.float64) sp_output = sparse_ops.sparse_merge(indices, values, vocab_size) output = self.evaluate(sp_output) self._AssertResultsSorted(output, vocab_size) class SparseRetainTest(test_util.TensorFlowTestCase): def _SparseTensorValue_5x6(self): ind = np.array([[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]]) val = np.array([0, 10, 13, 14, 32, 33]) shape = np.array([5, 6]) return sparse_tensor.SparseTensorValue( np.array(ind, np.int64), np.array(val, np.int32), np.array(shape, np.int64)) def _SparseTensor_5x6(self): return sparse_tensor.SparseTensor.from_value(self._SparseTensorValue_5x6()) def testBasic(self): with test_util.force_cpu(): for sp_input in (self._SparseTensorValue_5x6(), self._SparseTensor_5x6()): to_retain = np.array([1, 0, 0, 1, 1, 0], dtype=np.bool) sp_output = sparse_ops.sparse_retain(sp_input, to_retain) output = self.evaluate(sp_output) self.assertAllEqual(output.indices, [[0, 0], [1, 4], [3, 2]]) self.assertAllEqual(output.values, [0, 14, 32]) self.assertAllEqual(output.dense_shape, [5, 6]) def testRetainNone(self): with test_util.force_cpu(): sp_input = self._SparseTensor_5x6() to_retain = np.zeros((6,), dtype=np.bool) sp_output = sparse_ops.sparse_retain(sp_input, to_retain) output = self.evaluate(sp_output) self.assertAllEqual(output.indices, np.array([]).reshape((0, 2))) self.assertAllEqual(output.values, []) self.assertAllEqual(output.dense_shape, [5, 6]) def testMismatchedRetainShape(self): with test_util.force_cpu(): sp_input = self._SparseTensor_5x6() to_retain = np.array([1, 0, 0, 1, 0], dtype=np.bool) with self.assertRaises(ValueError): sparse_ops.sparse_retain(sp_input, to_retain) class SparseResetShapeTest(test_util.TensorFlowTestCase): _IND_2_5_6 = np.array( [[0, 0, 0], [0, 1, 0], [0, 1, 3], [1, 1, 4], [1, 3, 2], [1, 3, 3]], dtype=np.int64) _VAL_2_5_6 = np.array([0, 10, 13, 14, 32, 33], dtype=np.int32) _SHP_2_5_6 = np.array([2, 5, 6], dtype=np.int64) def _SparseTensor_2x5x6(self): return sparse_tensor.SparseTensor( constant_op.constant(self._IND_2_5_6, dtypes.int64), constant_op.constant(self._VAL_2_5_6, dtypes.int32), constant_op.constant(self._SHP_2_5_6, dtypes.int64)) def _SparseTensor_2x5x6_Empty(self): return sparse_tensor.SparseTensor( constant_op.constant( np.empty(shape=[0, 3], dtype=np.int64), dtypes.int64), constant_op.constant(np.empty(shape=[0], dtype=np.int32), dtypes.int32), constant_op.constant(self._SHP_2_5_6, dtypes.int64)) def _SparseTensorValue_2x5x6(self): return sparse_tensor.SparseTensorValue(self._IND_2_5_6, self._VAL_2_5_6, self._SHP_2_5_6) def testStaticShapeInfoPreservedWhenNewShapeIsProvidedAndStatic(self): sp_input = self._SparseTensor_2x5x6() new_shape = np.array([3, 6, 7], dtype=np.int64) sp_output = sparse_ops.sparse_reset_shape(sp_input, new_shape) self.assertAllEqual([3, 6, 7], sp_output.get_shape()) def testBasic(self): with test_util.force_cpu(): sp_input = self._SparseTensor_2x5x6() new_shape = np.array([3, 6, 7], dtype=np.int64) sp_output = sparse_ops.sparse_reset_shape(sp_input, new_shape) output = self.evaluate(sp_output) self.assertAllEqual(output.indices, [[0, 0, 0], [0, 1, 0], [0, 1, 3], [1, 1, 4], [1, 3, 2], [1, 3, 3]]) self.assertAllEqual(output.values, [0, 10, 13, 14, 32, 33]) self.assertAllEqual(output.dense_shape, [3, 6, 7]) def testInputUnavailableInGraphConstructionOk(self): with test_util.force_cpu(): sp_input = self._SparseTensorValue_2x5x6() new_shape = np.array([3, 6, 7], dtype=np.int64) sp_output = sparse_ops.sparse_reset_shape(sp_input, new_shape) output = self.evaluate(sp_output) self.assertAllEqual(output.indices, [[0, 0, 0], [0, 1, 0], [0, 1, 3], [1, 1, 4], [1, 3, 2], [1, 3, 3]]) self.assertAllEqual(output.values, [0, 10, 13, 14, 32, 33]) self.assertAllEqual(output.dense_shape, [3, 6, 7]) @test_util.run_deprecated_v1 def testFeedInputUnavailableInGraphConstructionOk(self): with self.session(use_gpu=False) as sess: sp_input = array_ops.sparse_placeholder(dtype=dtypes.int32) new_shape = np.array([3, 6, 7], dtype=np.int64) sp_output = sparse_ops.sparse_reset_shape(sp_input, new_shape) output = sess.run(sp_output, feed_dict={sp_input: self._SparseTensorValue_2x5x6()}) self.assertAllEqual(output.indices, [[0, 0, 0], [0, 1, 0], [0, 1, 3], [1, 1, 4], [1, 3, 2], [1, 3, 3]]) self.assertAllEqual(output.values, [0, 10, 13, 14, 32, 33]) self.assertAllEqual(output.dense_shape, [3, 6, 7]) def testTightBoundingBox(self): with test_util.force_cpu(): sp_input = self._SparseTensor_2x5x6() sp_output = sparse_ops.sparse_reset_shape(sp_input) output = self.evaluate(sp_output) self.assertAllEqual(output.indices, [[0, 0, 0], [0, 1, 0], [0, 1, 3], [1, 1, 4], [1, 3, 2], [1, 3, 3]]) self.assertAllEqual(output.values, [0, 10, 13, 14, 32, 33]) self.assertAllEqual(output.dense_shape, [2, 4, 5]) def testTightBoundingBoxEmpty(self): with test_util.force_cpu(): sp_input = self._SparseTensor_2x5x6_Empty() sp_output = sparse_ops.sparse_reset_shape(sp_input) output = self.evaluate(sp_output) self.assertAllEqual(output.indices.shape, [0, 3]) self.assertAllEqual(output.values.shape, [0]) self.assertAllEqual(output.dense_shape, [0, 0, 0]) def testInvalidRank(self): with test_util.force_cpu(): sp_input = self._SparseTensor_2x5x6() new_shape = np.array([3, 7], dtype=np.int64) with self.assertRaises(ValueError): sparse_ops.sparse_reset_shape(sp_input, new_shape) @test_util.run_deprecated_v1 def testInvalidRankNewShapeUnavailableInGraphConstruction(self): with self.session(use_gpu=False) as sess: new_shape = array_ops.placeholder(dtype=dtypes.int64) sp_input = self._SparseTensor_2x5x6() out = sparse_ops.sparse_reset_shape(sp_input, new_shape) with self.assertRaisesOpError("x == y did not hold element-wise"): sess.run(out, feed_dict={new_shape: np.array([3, 7], dtype=np.int64)}) def testInvalidDimensionSizeStatic(self): sp_input = self._SparseTensor_2x5x6() new_shape = np.array([3, 7, 5], dtype=np.int64) with self.assertRaisesRegexp(ValueError, "should have dimension sizes"): sparse_ops.sparse_reset_shape(sp_input, new_shape) @test_util.run_deprecated_v1 def testInvalidDimensionSizeDynamic(self): with self.session(use_gpu=False) as sess: sp_input = self._SparseTensor_2x5x6() new_shape = array_ops.placeholder(dtype=dtypes.int32) out = sparse_ops.sparse_reset_shape(sp_input, new_shape) with self.assertRaisesOpError("x <= y did not hold element-wise"): sess.run(out, feed_dict={new_shape: [3, 7, 5]}) @test_util.run_deprecated_v1 def testInvalidDimensionSizeInputUnavailableInGraphConstruction(self): sp_input = array_ops.sparse_placeholder(dtype=dtypes.int32) with self.session(use_gpu=False) as sess: new_shape = np.array([3, 7, 5], dtype=np.int64) out = sparse_ops.sparse_reset_shape(sp_input, new_shape) with self.assertRaisesOpError("x <= y did not hold element-wise"): sess.run(out, feed_dict={sp_input: self._SparseTensorValue_2x5x6()}) class SparseFillEmptyRowsTest(test_util.TensorFlowTestCase): def _SparseTensorValue_5x6(self, dtype=np.int32): ind = np.array([[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]]) val = np.array([0, 10, 13, 14, 32, 33]) shape = np.array([5, 6]) return sparse_tensor.SparseTensorValue( np.array(ind, np.int64), np.array(val, dtype), np.array( shape, np.int64)) def _SparseTensor_5x6(self): return sparse_tensor.SparseTensor.from_value(self._SparseTensorValue_5x6()) def _SparseTensor_String5x6(self): ind = np.array([[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]]) val = np.array(["a", "b", "c", "d", "e", "f"]) shape = np.array([5, 6]) return sparse_tensor.SparseTensor( constant_op.constant(ind, dtypes.int64), constant_op.constant(val, dtypes.string), constant_op.constant(shape, dtypes.int64)) def _SparseTensor_2x6(self): ind = np.array([[0, 0], [1, 0], [1, 3], [1, 4]]) val = np.array([0, 10, 13, 14]) shape = np.array([2, 6]) return sparse_tensor.SparseTensor( constant_op.constant(ind, dtypes.int64), constant_op.constant(val, dtypes.int32), constant_op.constant(shape, dtypes.int64)) def testFillNumber(self): with test_util.force_cpu(): for sp_input in (self._SparseTensorValue_5x6(), self._SparseTensor_5x6()): sp_output, empty_row_indicator = ( sparse_ops.sparse_fill_empty_rows(sp_input, -1)) output, empty_row_indicator_out = self.evaluate( [sp_output, empty_row_indicator]) self.assertAllEqual( output.indices, [[0, 0], [1, 0], [1, 3], [1, 4], [2, 0], [3, 2], [3, 3], [4, 0]]) self.assertAllEqual(output.values, [0, 10, 13, 14, -1, 32, 33, -1]) self.assertAllEqual(output.dense_shape, [5, 6]) self.assertAllEqual(empty_row_indicator_out, np.array([0, 0, 1, 0, 1]).astype(np.bool)) @test_util.run_deprecated_v1 def testFillFloat(self): with self.session(use_gpu=False): values = constant_op.constant( [0.0, 10.0, 13.0, 14.0, 32.0, 33.0], dtype=dtypes.float64) default_value = constant_op.constant(-1.0, dtype=dtypes.float64) sp_input = sparse_tensor.SparseTensorValue( indices=np.array([[0, 0], [1, 0], [1, 3], [1, 4], [3, 2], [3, 3]]), values=values, dense_shape=np.array([5, 6])) sp_output, empty_row_indicator = (sparse_ops.sparse_fill_empty_rows( sp_input, default_value)) output, empty_row_indicator_out = self.evaluate( [sp_output, empty_row_indicator]) self.assertAllEqual(output.indices, [[0, 0], [1, 0], [1, 3], [1, 4], [2, 0], [3, 2], [3, 3], [4, 0]]) self.assertAllClose(output.values, [0, 10, 13, 14, -1, 32, 33, -1]) self.assertAllEqual(output.dense_shape, [5, 6]) self.assertAllEqual(empty_row_indicator_out, np.array([0, 0, 1, 0, 1]).astype(np.bool)) values_grad_err = gradient_checker.compute_gradient_error( values, values.shape.as_list(), sp_output.values, [8], delta=1e-8) self.assertGreater(values_grad_err, 0) self.assertLess(values_grad_err, 1e-8) default_value_grad_err = gradient_checker.compute_gradient_error( default_value, default_value.shape.as_list(), sp_output.values, [8], delta=1e-8) self.assertGreater(default_value_grad_err, 0) self.assertLess(default_value_grad_err, 1e-8) def testFillString(self): with test_util.force_cpu(): sp_input = self._SparseTensor_String5x6() sp_output, empty_row_indicator = ( sparse_ops.sparse_fill_empty_rows(sp_input, "")) output, empty_row_indicator_out = self.evaluate( [sp_output, empty_row_indicator]) self.assertAllEqual( output.indices, [[0, 0], [1, 0], [1, 3], [1, 4], [2, 0], [3, 2], [3, 3], [4, 0]]) self.assertAllEqual(output.values, [b"a", b"b", b"c", b"d", b"", b"e", b"f", b""]) self.assertAllEqual(output.dense_shape, [5, 6]) self.assertAllEqual(empty_row_indicator_out, np.array([0, 0, 1, 0, 1]).astype(np.bool)) def testNoEmptyRows(self): with test_util.force_cpu(): sp_input = self._SparseTensor_2x6() sp_output, empty_row_indicator = ( sparse_ops.sparse_fill_empty_rows(sp_input, -1)) output, empty_row_indicator_out = self.evaluate( [sp_output, empty_row_indicator]) self.assertAllEqual(output.indices, [[0, 0], [1, 0], [1, 3], [1, 4]]) self.assertAllEqual(output.values, [0, 10, 13, 14]) self.assertAllEqual(output.dense_shape, [2, 6]) self.assertAllEqual(empty_row_indicator_out, np.zeros(2).astype(np.bool)) class SparseAddTest(test_util.TensorFlowTestCase): def testValuesInVariable(self): indices = constant_op.constant([[1]], dtype=dtypes.int64) values = variables.Variable([1], trainable=False, dtype=dtypes.float32) shape = constant_op.constant([1], dtype=dtypes.int64) sp_input = sparse_tensor.SparseTensor(indices, values, shape) sp_output = sparse_ops.sparse_add(sp_input, sp_input) with test_util.force_cpu(): self.evaluate(variables.global_variables_initializer()) output = self.evaluate(sp_output) self.assertAllEqual(output.values, [2]) class SparseReduceTest(test_util.TensorFlowTestCase): # [[1, ?, 2] # [?, 3, ?]] # where ? is implicitly-zero. ind = np.array([[0, 0], [0, 2], [1, 1]]).astype(np.int64) vals = np.array([1, 1, 1]).astype(np.int32) dense_shape = np.array([2, 3]).astype(np.int64) def _compare(self, sp_t, reduction_axes, ndims, keep_dims, do_sum): densified = self.evaluate(sparse_ops.sparse_tensor_to_dense(sp_t)) np_ans = densified if reduction_axes is None: if do_sum: np_ans = np.sum(np_ans, keepdims=keep_dims) else: np_ans = np.max(np_ans, keepdims=keep_dims) else: if not isinstance(reduction_axes, list): # Single scalar. reduction_axes = [reduction_axes] reduction_axes = np.array(reduction_axes).astype(np.int32) # Handles negative axes. reduction_axes = (reduction_axes + ndims) % ndims # Loop below depends on sorted. reduction_axes.sort() for ra in reduction_axes.ravel()[::-1]: if do_sum: np_ans = np.sum(np_ans, axis=ra, keepdims=keep_dims) else: np_ans = np.max(np_ans, axis=ra, keepdims=keep_dims) with self.cached_session(): if do_sum: tf_dense_ans = sparse_ops.sparse_reduce_sum(sp_t, reduction_axes, keep_dims) else: tf_dense_ans = sparse_ops.sparse_reduce_max(sp_t, reduction_axes, keep_dims) out_dense = self.evaluate(tf_dense_ans) if do_sum: tf_sparse_ans = sparse_ops.sparse_reduce_sum_sparse(sp_t, reduction_axes, keep_dims) else: tf_sparse_ans = sparse_ops.sparse_reduce_max_sparse(sp_t, reduction_axes, keep_dims) # Convert to dense for comparison purposes. out_sparse = sparse_ops.sparse_tensor_to_dense(tf_sparse_ans) self.assertAllClose(np_ans, out_dense) self.assertAllClose(np_ans, out_sparse) def _compare_all(self, sp_t, reduction_axes, ndims): self._compare(sp_t, reduction_axes, ndims, False, False) self._compare(sp_t, reduction_axes, ndims, False, True) self._compare(sp_t, reduction_axes, ndims, True, False) self._compare(sp_t, reduction_axes, ndims, True, True) def testSimpleAndRandomInputs(self): if np.__version__ == "1.13.0": self.skipTest("numpy 1.13.0 bug") sp_t = sparse_tensor.SparseTensor(self.ind, self.vals, self.dense_shape) with test_util.force_cpu(): self._compare_all(sp_t, None, ndims=2) self._compare_all(sp_t, 0, ndims=2) self._compare_all(sp_t, [1], ndims=2) self._compare_all(sp_t, [0, 1], ndims=2) self._compare_all(sp_t, [1, 0], ndims=2) self._compare_all(sp_t, [-1], ndims=2) self._compare_all(sp_t, [1, -2], ndims=2) np.random.seed(1618) test_dims = [(1618, 1, 11, 7, 1), (1,), (1, 1, 1)] with test_util.force_cpu(): for dims in test_dims: sp_t, unused_nnz = _sparsify(np.random.randn(*dims)) # reduce all using None self._compare_all(sp_t, None, ndims=len(dims)) # reduce random axes from 1D to N-D for d in range(1, len(dims) + 1): axes = np.random.choice(len(dims), size=d, replace=False).tolist() self._compare_all(sp_t, axes, ndims=len(dims)) def testInvalidAxes(self): sp_t = sparse_tensor.SparseTensor(self.ind, self.vals, self.dense_shape) with test_util.force_cpu(): with self.assertRaisesOpError("Invalid reduction dimension -3"): self.evaluate(sparse_ops.sparse_reduce_sum(sp_t, -3)) with self.assertRaisesOpError("Invalid reduction dimension 2"): self.evaluate(sparse_ops.sparse_reduce_sum(sp_t, 2)) with self.assertRaisesOpError("Invalid reduction dimension -3"): self.evaluate(sparse_ops.sparse_reduce_max(sp_t, -3)) with self.assertRaisesOpError("Invalid reduction dimension 2"): self.evaluate(sparse_ops.sparse_reduce_max(sp_t, 2)) @test_util.run_deprecated_v1 def testGradient(self): if np.__version__ == "1.13.0": self.skipTest("numpy 1.13.0 bug") np.random.seed(8161) test_dims = [(11, 1, 5, 7, 1), (2, 2)] with self.session(use_gpu=False): for dims in test_dims: sp_t, nnz = _sparsify(np.random.randn(*dims)) # reduce random axes from 1D to N-D for d in range(1, len(dims) + 1): axes = np.random.choice(len(dims), size=d, replace=False).tolist() reduced = sparse_ops.sparse_reduce_sum(sp_t, axes) err = gradient_checker.compute_gradient_error( sp_t.values, (nnz,), reduced, self.evaluate(reduced).shape) self.assertLess(err, 1e-3) # Tests for negative axes. reduced = sparse_ops.sparse_reduce_sum(sp_t, -1) err = gradient_checker.compute_gradient_error( sp_t.values, (nnz,), reduced, self.evaluate(reduced).shape) self.assertLess(err, 1e-3) def _testSparseReduceShape(self, sp_t, reduction_axes, ndims, keep_dims, do_sum): densified = self.evaluate(sparse_ops.sparse_tensor_to_dense(sp_t)) np_op = np.sum tf_op = sparse_ops.sparse_reduce_sum if not do_sum: np_op = np.max tf_op = sparse_ops.sparse_reduce_max np_ans = densified if reduction_axes is None: np_ans = np_op(np_ans, keepdims=keep_dims) else: if not isinstance(reduction_axes, list): # Single scalar. reduction_axes = [reduction_axes] reduction_axes = np.array(reduction_axes).astype(np.int32) # Handles negative axes. reduction_axes = (reduction_axes + ndims) % ndims # Loop below depends on sorted. reduction_axes.sort() for ra in reduction_axes.ravel()[::-1]: np_ans = np_op(np_ans, axis=ra, keepdims=keep_dims) tf_ans = tf_op(sp_t, reduction_axes, keep_dims) self.assertAllEqual(np_ans.shape, tf_ans.get_shape().as_list()) def testSparseReduceSumOrMaxShape(self): sp_t = sparse_tensor.SparseTensor(self.ind, self.vals, self.dense_shape) with test_util.force_cpu(): for do_sum in [True, False]: for keep_dims in [True, False]: self._testSparseReduceShape(sp_t, None, 2, keep_dims, do_sum) self._testSparseReduceShape(sp_t, 0, 2, keep_dims, do_sum) self._testSparseReduceShape(sp_t, [1], 2, keep_dims, do_sum) self._testSparseReduceShape(sp_t, [0, 1], 2, keep_dims, do_sum) self._testSparseReduceShape(sp_t, [1, 0], 2, keep_dims, do_sum) self._testSparseReduceShape(sp_t, [-1], 2, keep_dims, do_sum) self._testSparseReduceShape(sp_t, [1, -2], 2, keep_dims, do_sum) class SparseMathOpsTest(test_util.TensorFlowTestCase): def _check(self, result_tensor, result_np, input_sp_t): self.assertTrue(isinstance(result_tensor, sparse_tensor.SparseTensor)) self.assertTrue(isinstance(input_sp_t, sparse_tensor.SparseTensor)) self.assertAllEqual(input_sp_t.indices, result_tensor.indices) self.assertAllEqual(input_sp_t.dense_shape, result_tensor.dense_shape) res_densified = sparse_ops.sparse_to_dense( result_tensor.indices, result_tensor.dense_shape, result_tensor.values) self.assertAllEqual(result_np, res_densified) @test_util.run_deprecated_v1 def testCwiseShapeValidation(self): # Test case for GitHub 24072. with test_util.force_cpu(): a = array_ops.ones([3, 4, 1], dtype=dtypes.int32) b = sparse_tensor.SparseTensor([[0, 0, 1, 0], [0, 0, 3, 0]], [10, 20], [1, 1, 4, 2]) c = a * b with self.assertRaisesRegexp( errors.InvalidArgumentError, "broadcasts dense to sparse only; got incompatible shapes"): self.evaluate(c) def testCwiseDivAndMul(self): np.random.seed(1618) sp_shapes = [(10, 10, 10), (5, 5), (1618,), (3, 3, 7)] dense_shapes = [(10, 10, 1), (5, 5), (1,), (1, 7)] with test_util.force_cpu(): for dtype in [np.float32, np.float64, np.int32, np.int64]: for sp_shape, dense_shape in zip(sp_shapes, dense_shapes): sp_vals_np = np.random.rand(*sp_shape).astype(dtype) + 1 dense_vals_np = np.random.rand(*dense_shape).astype(dtype) + 1 sp_t, unused_nnz = _sparsify(sp_vals_np, thresh=1.5) sp_t_densified = sparse_ops.sparse_tensor_to_dense(sp_t) dense_t = constant_op.constant(dense_vals_np) self._check(sp_t / dense_t, sp_t_densified / dense_vals_np, sp_t) # Check commutative. self._check(sp_t * dense_t, sp_t_densified * dense_vals_np, sp_t) self._check(dense_t * sp_t, sp_t_densified * dense_vals_np, sp_t) if dtype in [np.int32, np.int64]: res = sp_t / dense_t # should invoke "__truediv__" self.assertEqual(res.values.dtype, np.float64) def testCwiseAdd(self): with test_util.force_cpu(): # Identity(2) + AllOnes(2,2). Should be equal to 2 * Identity(2). indices = [[0, 0], [1, 1]] vals = [1, 1] shape = (2, 2) sp_t = sparse_tensor.SparseTensor(indices, vals, shape) dense_t = array_ops.ones(shape, dtype=dtypes.int32) self._check( sparse_ops.sparse_dense_cwise_add(sp_t, dense_t), np.identity(2) * 2, sp_t) # Variant of above, but broadcasts the dense side. dense_t = array_ops.ones([1], dtype=dtypes.int32) self._check( sparse_ops.sparse_dense_cwise_add(sp_t, dense_t), np.identity(2) * 2, sp_t) @test_util.run_deprecated_v1 def testGradients(self): np.random.seed(1618) sp_shapes = [(10, 10, 10), (5, 5), (1618,), (3, 3, 7)] dense_shapes = [(10, 10, 1), (5, 5), (1,), (1, 7)] with self.session(use_gpu=False): for dtype in [np.float32, np.float64]: for sp_shape, dense_shape in zip(sp_shapes, dense_shapes): sp_vals_np = np.random.rand(*sp_shape).astype(dtype) + 1 dense_vals_np = np.random.rand(*dense_shape).astype(dtype) + 1 sp_t, nnz = _sparsify(sp_vals_np, thresh=1.5) dense_t = constant_op.constant(dense_vals_np) cmul = sp_t * dense_t err = gradient_checker.compute_gradient_error([sp_t.values, dense_t], [(nnz,), dense_shape], cmul.values, (nnz,)) self.assertLess(err, 1e-4) cdiv = sp_t / dense_t err = gradient_checker.compute_gradient_error(sp_t.values, (nnz,), cdiv.values, (nnz,)) self.assertLess(err, 1e-4) err = gradient_checker.compute_gradient_error( dense_t, dense_shape, cdiv.values, (nnz,), x_init_value=dense_vals_np) self.assertLess(err, 2e-4) class SparseSoftmaxTest(test_util.TensorFlowTestCase): @test_util.run_deprecated_v1 def testEquivalentToDensified(self): np.random.seed(1618) n, m = np.random.choice(20, size=2) for dtype in [np.float32, np.float64]: sp_vals_np = np.random.rand(n, m).astype(dtype) batched_sp_t, unused_nnz1 = _sparsify( sp_vals_np.reshape((1, n, m)), thresh=0.) # No masking. with test_util.force_cpu(): densified = constant_op.constant(sp_vals_np) sp_result = self.evaluate( sparse_ops.sparse_softmax(batched_sp_t)).values.reshape((n, m)) dense_result = nn_ops.softmax(densified) self.assertAllClose(dense_result, sp_result) def testHigherRanks(self): # For the first shape: # First batch: # [? e.] # [1. ? ] # Second batch: # [e ? ] # [e e ] # # The softmax results should be: # [? 1.] [1 ?] # [1. ? ] and [.5 .5] # where ? means implicitly zero. # # The second shape: same input data, but with a higher-rank shape. shapes = [[2, 2, 2], [2, 1, 2, 2]] for shape in shapes: values = np.asarray( [0., np.e, 1., 0., np.e, 0., np.e, np.e]).reshape(shape) sp_t, unused_nnz = _sparsify(values, thresh=1e-2) expected_values = [1., 1., 1., .5, .5] with test_util.force_cpu(): result = sparse_ops.sparse_softmax(sp_t) self.assertAllEqual(expected_values, result.values) self.assertAllEqual(sp_t.indices, result.indices) self.assertAllEqual(shape, result.dense_shape) @test_util.run_deprecated_v1 def testGradient(self): x_shape = [2, 5, 10] with self.cached_session(use_gpu=False): for dtype in [np.float32, np.float64]: x_np = np.random.randn(*x_shape).astype(dtype) x_tf, nnz = _sparsify(x_np) y_tf = sparse_ops.sparse_softmax(x_tf) err = gradient_checker.compute_gradient_error(x_tf.values, (nnz,), y_tf.values, (nnz,)) self.assertLess(err, 1e-4) class SparseMinimumMaximumTest(test_util.TensorFlowTestCase): def _assertSparseTensorValueEqual(self, a, b): self.assertAllEqual(a.indices, b.indices) self.assertAllEqual(a.values, b.values) self.assertAllEqual(a.dense_shape, b.dense_shape) def testBasic(self): with test_util.force_cpu(): # 1-D, values at index 0. sp_zero = sparse_tensor.SparseTensor([[0]], [0], [7]) sp_one = sparse_tensor.SparseTensor([[0]], [1], [7]) max_tf = sparse_ops.sparse_maximum(sp_zero, sp_one) min_tf = sparse_ops.sparse_minimum(sp_zero, sp_one) self._assertSparseTensorValueEqual(sp_one, max_tf) self._assertSparseTensorValueEqual(sp_zero, min_tf) # Values at different indices. sp_zero = sparse_tensor.SparseTensor([[0]], [0], [7]) sp_zero_2 = sparse_tensor.SparseTensor([[1]], [0], [7]) expected = sparse_tensor.SparseTensor([[0], [1]], [0, 0], [7]) max_tf = sparse_ops.sparse_maximum(sp_zero, sp_zero_2) min_tf = sparse_ops.sparse_minimum(sp_zero, sp_zero_2) self._assertSparseTensorValueEqual(expected, max_tf) self._assertSparseTensorValueEqual(expected, min_tf) @test_util.run_deprecated_v1 def testRandom(self): np.random.seed(1618) shapes = [(13,), (6, 8), (1, 7, 1)] for shape in shapes: for dtype in [np.int32, np.int64, np.float16, np.float32, np.float64]: a_np = np.random.randn(*shape).astype(dtype) b_np = np.random.randn(*shape).astype(dtype) sp_a, unused_a_nnz = _sparsify(a_np, thresh=-.5) sp_b, unused_b_nnz = _sparsify(b_np, thresh=-.5) with self.cached_session(use_gpu=False): maximum_tf = sparse_ops.sparse_maximum(sp_a, sp_b) maximum_tf_densified = sparse_ops.sparse_tensor_to_dense( maximum_tf).eval() minimum_tf = sparse_ops.sparse_minimum(sp_a, sp_b) minimum_tf_densified = sparse_ops.sparse_tensor_to_dense( minimum_tf).eval() a_densified = sparse_ops.sparse_tensor_to_dense(sp_a).eval() b_densified = sparse_ops.sparse_tensor_to_dense(sp_b).eval() self.assertAllEqual( np.maximum(a_densified, b_densified), maximum_tf_densified) self.assertAllEqual( np.minimum(a_densified, b_densified), minimum_tf_densified) def testMismatchedShapes(self): with test_util.force_cpu(): sp_zero = sparse_tensor.SparseTensor([[0, 0]], [0], [1, 1]) sp_one = sparse_tensor.SparseTensor([[0]], [1], [2]) with self.assertRaisesOpError("Operands do not have the same ranks"): self.evaluate(sparse_ops.sparse_maximum(sp_zero, sp_one)) sp_zero = sparse_tensor.SparseTensor([[0]], [0], [1]) sp_one = sparse_tensor.SparseTensor([[0]], [1], [2]) with self.assertRaisesOpError("Operands' shapes do not match"): self.evaluate(sparse_ops.sparse_maximum(sp_zero, sp_one)) class SparseTransposeTest(test.TestCase): def testTranspose(self): if np.__version__ == "1.13.0": self.skipTest("numpy 1.13.0 bug") with test_util.force_cpu(): np.random.seed(1618) shapes = [np.random.randint(1, 10, size=rank) for rank in range(1, 6)] for shape in shapes: for dtype in [np.int32, np.int64, np.float32, np.float64]: dn_input = np.random.randn(*shape).astype(dtype) rank = self.evaluate(array_ops.rank(dn_input)) perm = np.random.choice(rank, rank, False) sp_input, unused_a_nnz = _sparsify(dn_input) sp_trans = sparse_ops.sparse_transpose(sp_input, perm=perm) dn_trans = sparse_ops.sparse_tensor_to_dense(sp_trans) expected_trans = array_ops.transpose(dn_input, perm=perm) self.assertAllEqual(expected_trans.shape, sp_trans.get_shape()) self.assertAllEqual(dn_trans, expected_trans) class SparsePlaceholderTest(test.TestCase): @test_util.run_deprecated_v1 def testPlaceholder(self): foo = array_ops.sparse_placeholder(dtypes.float32, shape=(10, 47)) self.assertAllEqual([10, 47], foo.get_shape()) self.assertAllEqual([None, 2], foo.indices.get_shape().as_list()) @test_util.run_deprecated_v1 def testPartialShapePlaceholder(self): foo = array_ops.sparse_placeholder(dtypes.float32, shape=(None, 47)) self.assertAllEqual([None, None], foo.get_shape().as_list()) self.assertAllEqual([None, 2], foo.indices.get_shape().as_list()) @test_util.run_deprecated_v1 def testNoShapePlaceholder(self): foo = array_ops.sparse_placeholder(dtypes.float32, shape=None) self.assertAllEqual(None, foo.get_shape()) self.assertAllEqual([None, None], foo.indices.get_shape().as_list()) if __name__ == "__main__": googletest.main()
henryfjordan/django
refs/heads/master
django/utils/autoreload.py
295
# Autoreloading launcher. # Borrowed from Peter Hunt and the CherryPy project (http://www.cherrypy.org). # Some taken from Ian Bicking's Paste (http://pythonpaste.org/). # # Portions copyright (c) 2004, CherryPy Team (team@cherrypy.org) # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the CherryPy Team nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import signal import sys import time import traceback from django.apps import apps from django.conf import settings from django.core.signals import request_finished from django.utils import six from django.utils._os import npath from django.utils.six.moves import _thread as thread # This import does nothing, but it's necessary to avoid some race conditions # in the threading module. See http://code.djangoproject.com/ticket/2330 . try: import threading # NOQA except ImportError: pass try: import termios except ImportError: termios = None USE_INOTIFY = False try: # Test whether inotify is enabled and likely to work import pyinotify fd = pyinotify.INotifyWrapper.create().inotify_init() if fd >= 0: USE_INOTIFY = True os.close(fd) except ImportError: pass RUN_RELOADER = True FILE_MODIFIED = 1 I18N_MODIFIED = 2 _mtimes = {} _win = (sys.platform == "win32") _exception = None _error_files = [] _cached_modules = set() _cached_filenames = [] def gen_filenames(only_new=False): """ Returns a list of filenames referenced in sys.modules and translation files. """ # N.B. ``list(...)`` is needed, because this runs in parallel with # application code which might be mutating ``sys.modules``, and this will # fail with RuntimeError: cannot mutate dictionary while iterating global _cached_modules, _cached_filenames module_values = set(sys.modules.values()) _cached_filenames = clean_files(_cached_filenames) if _cached_modules == module_values: # No changes in module list, short-circuit the function if only_new: return [] else: return _cached_filenames + clean_files(_error_files) new_modules = module_values - _cached_modules new_filenames = clean_files( [filename.__file__ for filename in new_modules if hasattr(filename, '__file__')]) if not _cached_filenames and settings.USE_I18N: # Add the names of the .mo files that can be generated # by compilemessages management command to the list of files watched. basedirs = [os.path.join(os.path.dirname(os.path.dirname(__file__)), 'conf', 'locale'), 'locale'] for app_config in reversed(list(apps.get_app_configs())): basedirs.append(os.path.join(npath(app_config.path), 'locale')) basedirs.extend(settings.LOCALE_PATHS) basedirs = [os.path.abspath(basedir) for basedir in basedirs if os.path.isdir(basedir)] for basedir in basedirs: for dirpath, dirnames, locale_filenames in os.walk(basedir): for filename in locale_filenames: if filename.endswith('.mo'): new_filenames.append(os.path.join(dirpath, filename)) _cached_modules = _cached_modules.union(new_modules) _cached_filenames += new_filenames if only_new: return new_filenames + clean_files(_error_files) else: return _cached_filenames + clean_files(_error_files) def clean_files(filelist): filenames = [] for filename in filelist: if not filename: continue if filename.endswith(".pyc") or filename.endswith(".pyo"): filename = filename[:-1] if filename.endswith("$py.class"): filename = filename[:-9] + ".py" if os.path.exists(filename): filenames.append(filename) return filenames def reset_translations(): import gettext from django.utils.translation import trans_real gettext._translations = {} trans_real._translations = {} trans_real._default = None trans_real._active = threading.local() def inotify_code_changed(): """ Checks for changed code using inotify. After being called it blocks until a change event has been fired. """ class EventHandler(pyinotify.ProcessEvent): modified_code = None def process_default(self, event): if event.path.endswith('.mo'): EventHandler.modified_code = I18N_MODIFIED else: EventHandler.modified_code = FILE_MODIFIED wm = pyinotify.WatchManager() notifier = pyinotify.Notifier(wm, EventHandler()) def update_watch(sender=None, **kwargs): if sender and getattr(sender, 'handles_files', False): # No need to update watches when request serves files. # (sender is supposed to be a django.core.handlers.BaseHandler subclass) return mask = ( pyinotify.IN_MODIFY | pyinotify.IN_DELETE | pyinotify.IN_ATTRIB | pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO | pyinotify.IN_CREATE | pyinotify.IN_DELETE_SELF | pyinotify.IN_MOVE_SELF ) for path in gen_filenames(only_new=True): wm.add_watch(path, mask) # New modules may get imported when a request is processed. request_finished.connect(update_watch) # Block until an event happens. update_watch() notifier.check_events(timeout=None) notifier.read_events() notifier.process_events() notifier.stop() # If we are here the code must have changed. return EventHandler.modified_code def code_changed(): global _mtimes, _win for filename in gen_filenames(): stat = os.stat(filename) mtime = stat.st_mtime if _win: mtime -= stat.st_ctime if filename not in _mtimes: _mtimes[filename] = mtime continue if mtime != _mtimes[filename]: _mtimes = {} try: del _error_files[_error_files.index(filename)] except ValueError: pass return I18N_MODIFIED if filename.endswith('.mo') else FILE_MODIFIED return False def check_errors(fn): def wrapper(*args, **kwargs): global _exception try: fn(*args, **kwargs) except Exception: _exception = sys.exc_info() et, ev, tb = _exception if getattr(ev, 'filename', None) is None: # get the filename from the last item in the stack filename = traceback.extract_tb(tb)[-1][0] else: filename = ev.filename if filename not in _error_files: _error_files.append(filename) raise return wrapper def raise_last_exception(): global _exception if _exception is not None: six.reraise(*_exception) def ensure_echo_on(): if termios: fd = sys.stdin if fd.isatty(): attr_list = termios.tcgetattr(fd) if not attr_list[3] & termios.ECHO: attr_list[3] |= termios.ECHO if hasattr(signal, 'SIGTTOU'): old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN) else: old_handler = None termios.tcsetattr(fd, termios.TCSANOW, attr_list) if old_handler is not None: signal.signal(signal.SIGTTOU, old_handler) def reloader_thread(): ensure_echo_on() if USE_INOTIFY: fn = inotify_code_changed else: fn = code_changed while RUN_RELOADER: change = fn() if change == FILE_MODIFIED: sys.exit(3) # force reload elif change == I18N_MODIFIED: reset_translations() time.sleep(1) def restart_with_reloader(): while True: args = [sys.executable] + ['-W%s' % o for o in sys.warnoptions] + sys.argv if sys.platform == "win32": args = ['"%s"' % arg for arg in args] new_environ = os.environ.copy() new_environ["RUN_MAIN"] = 'true' exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ) if exit_code != 3: return exit_code def python_reloader(main_func, args, kwargs): if os.environ.get("RUN_MAIN") == "true": thread.start_new_thread(main_func, args, kwargs) try: reloader_thread() except KeyboardInterrupt: pass else: try: exit_code = restart_with_reloader() if exit_code < 0: os.kill(os.getpid(), -exit_code) else: sys.exit(exit_code) except KeyboardInterrupt: pass def jython_reloader(main_func, args, kwargs): from _systemrestart import SystemRestart thread.start_new_thread(main_func, args) while True: if code_changed(): raise SystemRestart time.sleep(1) def main(main_func, args=None, kwargs=None): if args is None: args = () if kwargs is None: kwargs = {} if sys.platform.startswith('java'): reloader = jython_reloader else: reloader = python_reloader wrapped_main_func = check_errors(main_func) reloader(wrapped_main_func, args, kwargs)
Cito/DBUtils
refs/heads/main
dbutils/persistent_pg.py
1
"""PersistentPg - persistent classic PyGreSQL connections. Implements steady, thread-affine persistent connections to a PostgreSQL database using the classic (not DB-API 2 compliant) PyGreSQL API. This should result in a speedup for persistent applications such as the application server of "Webware for Python," without loss of robustness. Robustness is provided by using "hardened" SteadyPg connections. Even if the underlying database is restarted and all connections are lost, they will be automatically and transparently reopened. However, since you don't want this to happen in the middle of a database transaction, you must explicitly start transactions with the begin() method so that SteadyPg knows that the underlying connection shall not be replaced and errors passed on until the transaction is completed. Measures are taken to make the database connections thread-affine. This means the same thread always uses the same cached connection, and no other thread will use it. So the fact that the classic PyGreSQL pg module is not thread-safe at the connection level is no problem here. For best performance, the application server should keep threads persistent. For this, you have to set MinServerThreads = MaxServerThreads in Webware. For more information on PostgreSQL, see: https://www.postgresql.org/ For more information on PyGreSQL, see: http://www.pygresql.org For more information on Webware for Python, see: https://webwareforpython.github.io/w4py/ Usage: First you need to set up a generator for your kind of database connections by creating an instance of PersistentPg, passing the following parameters: maxusage: the maximum number of reuses of a single connection (the default of 0 or None means unlimited reuse) When this maximum usage number of the connection is reached, the connection is automatically reset (closed and reopened). setsession: An optional list of SQL commands that may serve to prepare the session, e.g. ["set datestyle to german", ...] closeable: if this is set to true, then closing connections will be allowed, but by default this will be silently ignored threadlocal: an optional class for representing thread-local data that will be used instead of our Python implementation (threading.local is faster, but cannot be used in all cases) Additionally, you have to pass the parameters for the actual PostgreSQL connection which are passed via PyGreSQL, such as the names of the host, database, user, password etc. For instance, if you want every connection to your local database 'mydb' to be reused 1000 times: from dbutils.persistent_pg import PersistentPg persist = PersistentPg(5, dbname='mydb') Once you have set up the generator with these parameters, you can request database connections of that kind: db = persist.connection() You can use these connections just as if they were ordinary classic PyGreSQL API connections. Actually what you get is the hardened SteadyPg version of a classic PyGreSQL connection. Closing a persistent connection with db.close() will be silently ignored since it would be reopened at the next usage anyway and contrary to the intent of having persistent connections. Instead, the connection will be automatically closed when the thread dies. You can change this behavior by setting the closeable parameter. Note that you need to explicitly start transactions by calling the begin() method. This ensures that the transparent reopening will be suspended until the end of the transaction, and that the connection will be rolled back before being reused in the same thread. To end transactions, use one of the end(), commit() or rollback() methods. By setting the threadlocal parameter to threading.local, getting connections may become a bit faster, but this may not work in all environments (for instance, mod_wsgi is known to cause problems since it clears the threading.local data between requests). Ideas for improvement: * Add a thread for monitoring, restarting (or closing) bad or expired connections (similar to DBConnectionPool/ResourcePool by Warren Smith). * Optionally log usage, bad connections and exceeding of limits. Copyright, credits and license: * Contributed as supplement for Webware for Python and PyGreSQL by Christoph Zwerschke in September 2005 * Based on an idea presented on the Webware developer mailing list by Geoffrey Talvola in July 2005 Licensed under the MIT license. """ from . import __version__ from .steady_pg import SteadyPgConnection try: # Prefer the pure Python version of threading.local. # The C implementation turned out to be problematic with mod_wsgi, # since it does not keep the thread-local data between requests. from _threading_local import local except ImportError: # Fall back to the default version of threading.local. from threading import local class PersistentPg: """Generator for persistent classic PyGreSQL connections. After you have created the connection pool, you can use connection() to get thread-affine, steady PostgreSQL connections. """ version = __version__ def __init__( self, maxusage=None, setsession=None, closeable=False, threadlocal=None, *args, **kwargs): """Set up the persistent PostgreSQL connection generator. maxusage: maximum number of reuses of a single connection (0 or None means unlimited reuse) When this maximum usage number of the connection is reached, the connection is automatically reset (closed and reopened). setsession: optional list of SQL commands that may serve to prepare the session, e.g. ["set datestyle to ...", "set time zone ..."] closeable: if this is set to true, then closing connections will be allowed, but by default this will be silently ignored threadlocal: an optional class for representing thread-local data that will be used instead of our Python implementation (threading.local is faster, but cannot be used in all cases) args, kwargs: the parameters that shall be used to establish the PostgreSQL connections using class PyGreSQL pg.DB() """ self._maxusage = maxusage self._setsession = setsession self._closeable = closeable self._args, self._kwargs = args, kwargs self.thread = (threadlocal or local)() def steady_connection(self): """Get a steady, non-persistent PyGreSQL connection.""" return SteadyPgConnection( self._maxusage, self._setsession, self._closeable, *self._args, **self._kwargs) def connection(self): """Get a steady, persistent PyGreSQL connection.""" try: con = self.thread.connection except AttributeError: con = self.steady_connection() self.thread.connection = con return con
Zhongqilong/mykbengineer
refs/heads/master
kbe/res/scripts/common/Lib/site-packages/pip/status_codes.py
408
SUCCESS = 0 ERROR = 1 UNKNOWN_ERROR = 2 VIRTUALENV_NOT_FOUND = 3 PREVIOUS_BUILD_DIR_ERROR = 4 NO_MATCHES_FOUND = 23
dims/neutron
refs/heads/master
neutron/agent/l3_agent.py
5
# Copyright (c) 2015 OpenStack Foundation. # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import sys from oslo_config import cfg from oslo_service import service from neutron.agent.common import config from neutron.agent.l3 import config as l3_config from neutron.agent.l3 import ha from neutron.agent.linux import external_process from neutron.agent.linux import interface from neutron.agent.linux import pd from neutron.agent.linux import ra from neutron.agent.metadata import config as metadata_config from neutron.common import config as common_config from neutron.common import topics from neutron import service as neutron_service def register_opts(conf): conf.register_opts(l3_config.OPTS) conf.register_opts(metadata_config.DRIVER_OPTS) conf.register_opts(metadata_config.SHARED_OPTS) conf.register_opts(ha.OPTS) config.register_interface_driver_opts_helper(conf) config.register_agent_state_opts_helper(conf) conf.register_opts(interface.OPTS) conf.register_opts(external_process.OPTS) conf.register_opts(pd.OPTS) conf.register_opts(ra.OPTS) config.register_availability_zone_opts_helper(conf) def main(manager='neutron.agent.l3.agent.L3NATAgentWithStateReport'): register_opts(cfg.CONF) common_config.init(sys.argv[1:]) config.setup_logging() server = neutron_service.Service.create( binary='neutron-l3-agent', topic=topics.L3_AGENT, report_interval=cfg.CONF.AGENT.report_interval, manager=manager) service.launch(cfg.CONF, server).wait()
rabernat/PyTables
refs/heads/develop
examples/table2.py
13
# This shows how to use the cols accessors for table columns from __future__ import print_function import tables class Particle(tables.IsDescription): name = tables.StringCol(16, pos=1) # 16-character String lati = tables.Int32Col(pos=2) # integer longi = tables.Int32Col(pos=3) # integer vector = tables.Int32Col(shape=(2,), pos=4) # Integer matrix2D = tables.Float64Col(shape=(2, 2), pos=5) # double (double-precision) # Open a file in "w"rite mode fileh = tables.open_file("table2.h5", mode="w") table = fileh.create_table(fileh.root, 'table', Particle, "A table") # Append several rows in only one call table.append( [("Particle: 10", 10, 0, (10 * 9, 1), [[10 ** 2, 11 * 3]] * 2), ("Particle: 11", 11, -1, (11 * 10, 2), [[11 ** 2, 10 * 3]] * 2), ("Particle: 12", 12, -2, (12 * 11, 3), [[12 ** 2, 9 * 3]] * 2), ("Particle: 13", 13, -3, (13 * 11, 4), [[13 ** 2, 8 * 3]] * 2), ("Particle: 14", 14, -4, (14 * 11, 5), [[14 ** 2, 7 * 3]] * 2)]) print("str(Cols)-->", table.cols) print("repr(Cols)-->", repr(table.cols)) print("Column handlers:") for name in table.colnames: print(table.cols._f_col(name)) print("Select table.cols.name[1]-->", table.cols.name[1]) print("Select table.cols.name[1:2]-->", table.cols.name[1:2]) print("Select table.cols.name[:]-->", table.cols.name[:]) print("Select table.cols._f_col('name')[:]-->", table.cols._f_col('name')[:]) print("Select table.cols.lati[1]-->", table.cols.lati[1]) print("Select table.cols.lati[1:2]-->", table.cols.lati[1:2]) print("Select table.cols.vector[:]-->", table.cols.vector[:]) print("Select table.cols['matrix2D'][:]-->", table.cols.matrix2D[:]) fileh.close()
sirex/Misago
refs/heads/master
misago/markup/templatetags/__init__.py
12133432
scifiswapnil/Project-LoCatr
refs/heads/master
lib/python2.7/site-packages/django/conf/locale/el/__init__.py
12133432
japeto/Vigtech-Services
refs/heads/master
env/lib/python2.7/site-packages/django/conf/locale/nl/__init__.py
12133432
macs03/demo-cms
refs/heads/master
cms/lib/python2.7/site-packages/djangocms_style/migrations_django/__init__.py
12133432
peguin40/zulip
refs/heads/master
zerver/tests/webhooks/__init__.py
12133432
yotchang4s/cafebabepy
refs/heads/develop
src/main/python/test/test_regrtest.py
2
""" Tests of regrtest.py. Note: test_regrtest cannot be run twice in parallel. """ import contextlib import faulthandler import io import os.path import platform import re import subprocess import sys import sysconfig import tempfile import textwrap import unittest from test import libregrtest from test import support Py_DEBUG = hasattr(sys, 'getobjects') ROOT_DIR = os.path.join(os.path.dirname(__file__), '..', '..') ROOT_DIR = os.path.abspath(os.path.normpath(ROOT_DIR)) TEST_INTERRUPTED = textwrap.dedent(""" from signal import SIGINT try: from _testcapi import raise_signal raise_signal(SIGINT) except ImportError: import os os.kill(os.getpid(), SIGINT) """) class ParseArgsTestCase(unittest.TestCase): """ Test regrtest's argument parsing, function _parse_args(). """ def checkError(self, args, msg): with support.captured_stderr() as err, self.assertRaises(SystemExit): libregrtest._parse_args(args) self.assertIn(msg, err.getvalue()) def test_help(self): for opt in '-h', '--help': with self.subTest(opt=opt): with support.captured_stdout() as out, \ self.assertRaises(SystemExit): libregrtest._parse_args([opt]) self.assertIn('Run Python regression tests.', out.getvalue()) @unittest.skipUnless(hasattr(faulthandler, 'dump_traceback_later'), "faulthandler.dump_traceback_later() required") def test_timeout(self): ns = libregrtest._parse_args(['--timeout', '4.2']) self.assertEqual(ns.timeout, 4.2) self.checkError(['--timeout'], 'expected one argument') self.checkError(['--timeout', 'foo'], 'invalid float value') def test_wait(self): ns = libregrtest._parse_args(['--wait']) self.assertTrue(ns.wait) def test_slaveargs(self): ns = libregrtest._parse_args(['--slaveargs', '[[], {}]']) self.assertEqual(ns.slaveargs, '[[], {}]') self.checkError(['--slaveargs'], 'expected one argument') def test_start(self): for opt in '-S', '--start': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, 'foo']) self.assertEqual(ns.start, 'foo') self.checkError([opt], 'expected one argument') def test_verbose(self): ns = libregrtest._parse_args(['-v']) self.assertEqual(ns.verbose, 1) ns = libregrtest._parse_args(['-vvv']) self.assertEqual(ns.verbose, 3) ns = libregrtest._parse_args(['--verbose']) self.assertEqual(ns.verbose, 1) ns = libregrtest._parse_args(['--verbose'] * 3) self.assertEqual(ns.verbose, 3) ns = libregrtest._parse_args([]) self.assertEqual(ns.verbose, 0) def test_verbose2(self): for opt in '-w', '--verbose2': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.verbose2) def test_verbose3(self): for opt in '-W', '--verbose3': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.verbose3) def test_quiet(self): for opt in '-q', '--quiet': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.quiet) self.assertEqual(ns.verbose, 0) def test_slow(self): for opt in '-o', '--slowest': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.print_slow) def test_header(self): ns = libregrtest._parse_args(['--header']) self.assertTrue(ns.header) def test_randomize(self): for opt in '-r', '--randomize': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.randomize) def test_randseed(self): ns = libregrtest._parse_args(['--randseed', '12345']) self.assertEqual(ns.random_seed, 12345) self.assertTrue(ns.randomize) self.checkError(['--randseed'], 'expected one argument') self.checkError(['--randseed', 'foo'], 'invalid int value') def test_fromfile(self): for opt in '-f', '--fromfile': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, 'foo']) self.assertEqual(ns.fromfile, 'foo') self.checkError([opt], 'expected one argument') self.checkError([opt, 'foo', '-s'], "don't go together") def test_exclude(self): for opt in '-x', '--exclude': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.exclude) def test_single(self): for opt in '-s', '--single': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.single) self.checkError([opt, '-f', 'foo'], "don't go together") def test_match(self): for opt in '-m', '--match': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, 'pattern']) self.assertEqual(ns.match_tests, 'pattern') self.checkError([opt], 'expected one argument') def test_failfast(self): for opt in '-G', '--failfast': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, '-v']) self.assertTrue(ns.failfast) ns = libregrtest._parse_args([opt, '-W']) self.assertTrue(ns.failfast) self.checkError([opt], '-G/--failfast needs either -v or -W') def test_use(self): for opt in '-u', '--use': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, 'gui,network']) self.assertEqual(ns.use_resources, ['gui', 'network']) ns = libregrtest._parse_args([opt, 'gui,none,network']) self.assertEqual(ns.use_resources, ['network']) expected = list(libregrtest.RESOURCE_NAMES) expected.remove('gui') ns = libregrtest._parse_args([opt, 'all,-gui']) self.assertEqual(ns.use_resources, expected) self.checkError([opt], 'expected one argument') self.checkError([opt, 'foo'], 'invalid resource') def test_memlimit(self): for opt in '-M', '--memlimit': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, '4G']) self.assertEqual(ns.memlimit, '4G') self.checkError([opt], 'expected one argument') def test_testdir(self): ns = libregrtest._parse_args(['--testdir', 'foo']) self.assertEqual(ns.testdir, os.path.join(support.SAVEDCWD, 'foo')) self.checkError(['--testdir'], 'expected one argument') def test_runleaks(self): for opt in '-L', '--runleaks': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.runleaks) def test_huntrleaks(self): for opt in '-R', '--huntrleaks': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, ':']) self.assertEqual(ns.huntrleaks, (5, 4, 'reflog.txt')) ns = libregrtest._parse_args([opt, '6:']) self.assertEqual(ns.huntrleaks, (6, 4, 'reflog.txt')) ns = libregrtest._parse_args([opt, ':3']) self.assertEqual(ns.huntrleaks, (5, 3, 'reflog.txt')) ns = libregrtest._parse_args([opt, '6:3:leaks.log']) self.assertEqual(ns.huntrleaks, (6, 3, 'leaks.log')) self.checkError([opt], 'expected one argument') self.checkError([opt, '6'], 'needs 2 or 3 colon-separated arguments') self.checkError([opt, 'foo:'], 'invalid huntrleaks value') self.checkError([opt, '6:foo'], 'invalid huntrleaks value') def test_multiprocess(self): for opt in '-j', '--multiprocess': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, '2']) self.assertEqual(ns.use_mp, 2) self.checkError([opt], 'expected one argument') self.checkError([opt, 'foo'], 'invalid int value') self.checkError([opt, '2', '-T'], "don't go together") self.checkError([opt, '2', '-l'], "don't go together") self.checkError([opt, '0', '-T'], "don't go together") self.checkError([opt, '0', '-l'], "don't go together") self.checkError([opt, '0', '-T'], "don't go together") self.checkError([opt, '0', '-l'], "don't go together") self.checkError([opt, '0', '-M', '4G'], "don't go together") def test_coverage(self): for opt in '-T', '--coverage': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.trace) def test_coverdir(self): for opt in '-D', '--coverdir': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, 'foo']) self.assertEqual(ns.coverdir, os.path.join(support.SAVEDCWD, 'foo')) self.checkError([opt], 'expected one argument') def test_nocoverdir(self): for opt in '-N', '--nocoverdir': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertIsNone(ns.coverdir) def test_threshold(self): for opt in '-t', '--threshold': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt, '1000']) self.assertEqual(ns.threshold, 1000) self.checkError([opt], 'expected one argument') self.checkError([opt, 'foo'], 'invalid int value') def test_nowindows(self): for opt in '-n', '--nowindows': with self.subTest(opt=opt): with contextlib.redirect_stderr(io.StringIO()) as stderr: ns = libregrtest._parse_args([opt]) self.assertTrue(ns.nowindows) err = stderr.getvalue() self.assertIn('the --nowindows (-n) option is deprecated', err) def test_forever(self): for opt in '-F', '--forever': with self.subTest(opt=opt): ns = libregrtest._parse_args([opt]) self.assertTrue(ns.forever) def test_unrecognized_argument(self): self.checkError(['--xxx'], 'usage:') def test_long_option__partial(self): ns = libregrtest._parse_args(['--qui']) self.assertTrue(ns.quiet) self.assertEqual(ns.verbose, 0) def test_two_options(self): ns = libregrtest._parse_args(['--quiet', '--exclude']) self.assertTrue(ns.quiet) self.assertEqual(ns.verbose, 0) self.assertTrue(ns.exclude) def test_option_with_empty_string_value(self): ns = libregrtest._parse_args(['--start', '']) self.assertEqual(ns.start, '') def test_arg(self): ns = libregrtest._parse_args(['foo']) self.assertEqual(ns.args, ['foo']) def test_option_and_arg(self): ns = libregrtest._parse_args(['--quiet', 'foo']) self.assertTrue(ns.quiet) self.assertEqual(ns.verbose, 0) self.assertEqual(ns.args, ['foo']) def test_arg_option_arg(self): ns = libregrtest._parse_args(['test_unaryop', '-v', 'test_binop']) self.assertEqual(ns.verbose, 1) self.assertEqual(ns.args, ['test_unaryop', 'test_binop']) def test_unknown_option(self): self.checkError(['--unknown-option'], 'unrecognized arguments: --unknown-option') class BaseTestCase(unittest.TestCase): TEST_UNIQUE_ID = 1 TESTNAME_PREFIX = 'test_regrtest_' TESTNAME_REGEX = r'test_[a-zA-Z0-9_]+' def setUp(self): self.testdir = os.path.realpath(os.path.dirname(__file__)) self.tmptestdir = tempfile.mkdtemp() self.addCleanup(support.rmtree, self.tmptestdir) def create_test(self, name=None, code=''): if not name: name = 'noop%s' % BaseTestCase.TEST_UNIQUE_ID BaseTestCase.TEST_UNIQUE_ID += 1 # test_regrtest cannot be run twice in parallel because # of setUp() and create_test() name = self.TESTNAME_PREFIX + name path = os.path.join(self.tmptestdir, name + '.py') self.addCleanup(support.unlink, path) # Use 'x' mode to ensure that we do not override existing tests try: with open(path, 'x', encoding='utf-8') as fp: fp.write(code) except PermissionError as exc: if not sysconfig.is_python_build(): self.skipTest("cannot write %s: %s" % (path, exc)) raise return name def regex_search(self, regex, output): match = re.search(regex, output, re.MULTILINE) if not match: self.fail("%r not found in %r" % (regex, output)) return match def check_line(self, output, regex): regex = re.compile(r'^' + regex, re.MULTILINE) self.assertRegex(output, regex) def parse_executed_tests(self, output): regex = (r'^[0-9]+:[0-9]+:[0-9]+ \[ *[0-9]+(?:/ *[0-9]+)?\] (%s)' % self.TESTNAME_REGEX) parser = re.finditer(regex, output, re.MULTILINE) return list(match.group(1) for match in parser) def check_executed_tests(self, output, tests, skipped=(), failed=(), omitted=(), randomize=False, interrupted=False): if isinstance(tests, str): tests = [tests] if isinstance(skipped, str): skipped = [skipped] if isinstance(failed, str): failed = [failed] if isinstance(omitted, str): omitted = [omitted] ntest = len(tests) nskipped = len(skipped) nfailed = len(failed) nomitted = len(omitted) executed = self.parse_executed_tests(output) if randomize: self.assertEqual(set(executed), set(tests), output) else: self.assertEqual(executed, tests, output) def plural(count): return 's' if count != 1 else '' def list_regex(line_format, tests): count = len(tests) names = ' '.join(sorted(tests)) regex = line_format % (count, plural(count)) regex = r'%s:\n %s$' % (regex, names) return regex if skipped: regex = list_regex('%s test%s skipped', skipped) self.check_line(output, regex) if failed: regex = list_regex('%s test%s failed', failed) self.check_line(output, regex) if omitted: regex = list_regex('%s test%s omitted', omitted) self.check_line(output, regex) good = ntest - nskipped - nfailed - nomitted if good: regex = r'%s test%s OK\.$' % (good, plural(good)) if not skipped and not failed and good > 1: regex = 'All %s' % regex self.check_line(output, regex) if interrupted: self.check_line(output, 'Test suite interrupted by signal SIGINT.') if nfailed: result = 'FAILURE' elif interrupted: result = 'INTERRUPTED' else: result = 'SUCCESS' self.check_line(output, 'Tests result: %s' % result) def parse_random_seed(self, output): match = self.regex_search(r'Using random seed ([0-9]+)', output) randseed = int(match.group(1)) self.assertTrue(0 <= randseed <= 10000000, randseed) return randseed def run_command(self, args, input=None, exitcode=0, **kw): if not input: input = '' if 'stderr' not in kw: kw['stderr'] = subprocess.PIPE proc = subprocess.run(args, universal_newlines=True, input=input, stdout=subprocess.PIPE, **kw) if proc.returncode != exitcode: msg = ("Command %s failed with exit code %s\n" "\n" "stdout:\n" "---\n" "%s\n" "---\n" % (str(args), proc.returncode, proc.stdout)) if proc.stderr: msg += ("\n" "stderr:\n" "---\n" "%s" "---\n" % proc.stderr) self.fail(msg) return proc def run_python(self, args, **kw): args = [sys.executable, '-X', 'faulthandler', '-I', *args] proc = self.run_command(args, **kw) return proc.stdout class ProgramsTestCase(BaseTestCase): """ Test various ways to run the Python test suite. Use options close to options used on the buildbot. """ NTEST = 4 def setUp(self): super().setUp() # Create NTEST tests doing nothing self.tests = [self.create_test() for index in range(self.NTEST)] self.python_args = ['-Wd', '-E', '-bb'] self.regrtest_args = ['-uall', '-rwW', '--testdir=%s' % self.tmptestdir] if hasattr(faulthandler, 'dump_traceback_later'): self.regrtest_args.extend(('--timeout', '3600', '-j4')) if sys.platform == 'win32': self.regrtest_args.append('-n') def check_output(self, output): self.parse_random_seed(output) self.check_executed_tests(output, self.tests, randomize=True) def run_tests(self, args): output = self.run_python(args) self.check_output(output) def test_script_regrtest(self): # Lib/test/regrtest.py script = os.path.join(self.testdir, 'regrtest.py') args = [*self.python_args, script, *self.regrtest_args, *self.tests] self.run_tests(args) def test_module_test(self): # -m test args = [*self.python_args, '-m', 'test', *self.regrtest_args, *self.tests] self.run_tests(args) def test_module_regrtest(self): # -m test.regrtest args = [*self.python_args, '-m', 'test.regrtest', *self.regrtest_args, *self.tests] self.run_tests(args) def test_module_autotest(self): # -m test.autotest args = [*self.python_args, '-m', 'test.autotest', *self.regrtest_args, *self.tests] self.run_tests(args) def test_module_from_test_autotest(self): # from test import autotest code = 'from test import autotest' args = [*self.python_args, '-c', code, *self.regrtest_args, *self.tests] self.run_tests(args) def test_script_autotest(self): # Lib/test/autotest.py script = os.path.join(self.testdir, 'autotest.py') args = [*self.python_args, script, *self.regrtest_args, *self.tests] self.run_tests(args) @unittest.skipUnless(sysconfig.is_python_build(), 'run_tests.py script is not installed') def test_tools_script_run_tests(self): # Tools/scripts/run_tests.py script = os.path.join(ROOT_DIR, 'Tools', 'scripts', 'run_tests.py') args = [script, *self.regrtest_args, *self.tests] self.run_tests(args) def run_batch(self, *args): proc = self.run_command(args) self.check_output(proc.stdout) @unittest.skipUnless(sysconfig.is_python_build(), 'test.bat script is not installed') @unittest.skipUnless(sys.platform == 'win32', 'Windows only') def test_tools_buildbot_test(self): # Tools\buildbot\test.bat script = os.path.join(ROOT_DIR, 'Tools', 'buildbot', 'test.bat') test_args = ['--testdir=%s' % self.tmptestdir] if platform.architecture()[0] == '64bit': test_args.append('-x64') # 64-bit build if not Py_DEBUG: test_args.append('+d') # Release build, use python.exe self.run_batch(script, *test_args, *self.tests) @unittest.skipUnless(sys.platform == 'win32', 'Windows only') def test_pcbuild_rt(self): # PCbuild\rt.bat script = os.path.join(ROOT_DIR, r'PCbuild\rt.bat') rt_args = ["-q"] # Quick, don't run tests twice if platform.architecture()[0] == '64bit': rt_args.append('-x64') # 64-bit build if Py_DEBUG: rt_args.append('-d') # Debug build, use python_d.exe self.run_batch(script, *rt_args, *self.regrtest_args, *self.tests) class ArgsTestCase(BaseTestCase): """ Test arguments of the Python test suite. """ def run_tests(self, *testargs, **kw): cmdargs = ['-m', 'test', '--testdir=%s' % self.tmptestdir, *testargs] return self.run_python(cmdargs, **kw) def test_failing_test(self): # test a failing test code = textwrap.dedent(""" import unittest class FailingTest(unittest.TestCase): def test_failing(self): self.fail("bug") """) test_ok = self.create_test('ok') test_failing = self.create_test('failing', code=code) tests = [test_ok, test_failing] output = self.run_tests(*tests, exitcode=1) self.check_executed_tests(output, tests, failed=test_failing) def test_resources(self): # test -u command line option tests = {} for resource in ('audio', 'network'): code = 'from test import support\nsupport.requires(%r)' % resource tests[resource] = self.create_test(resource, code) test_names = sorted(tests.values()) # -u all: 2 resources enabled output = self.run_tests('-u', 'all', *test_names) self.check_executed_tests(output, test_names) # -u audio: 1 resource enabled output = self.run_tests('-uaudio', *test_names) self.check_executed_tests(output, test_names, skipped=tests['network']) # no option: 0 resources enabled output = self.run_tests(*test_names) self.check_executed_tests(output, test_names, skipped=test_names) def test_random(self): # test -r and --randseed command line option code = textwrap.dedent(""" import random print("TESTRANDOM: %s" % random.randint(1, 1000)) """) test = self.create_test('random', code) # first run to get the output with the random seed output = self.run_tests('-r', test) randseed = self.parse_random_seed(output) match = self.regex_search(r'TESTRANDOM: ([0-9]+)', output) test_random = int(match.group(1)) # try to reproduce with the random seed output = self.run_tests('-r', '--randseed=%s' % randseed, test) randseed2 = self.parse_random_seed(output) self.assertEqual(randseed2, randseed) match = self.regex_search(r'TESTRANDOM: ([0-9]+)', output) test_random2 = int(match.group(1)) self.assertEqual(test_random2, test_random) def test_fromfile(self): # test --fromfile tests = [self.create_test() for index in range(5)] # Write the list of files using a format similar to regrtest output: # [1/2] test_1 # [2/2] test_2 filename = support.TESTFN self.addCleanup(support.unlink, filename) # test format '0:00:00 [2/7] test_opcodes -- test_grammar took 0 sec' with open(filename, "w") as fp: previous = None for index, name in enumerate(tests, 1): line = ("00:00:%02i [%s/%s] %s" % (index, index, len(tests), name)) if previous: line += " -- %s took 0 sec" % previous print(line, file=fp) previous = name output = self.run_tests('--fromfile', filename) self.check_executed_tests(output, tests) # test format '[2/7] test_opcodes' with open(filename, "w") as fp: for index, name in enumerate(tests, 1): print("[%s/%s] %s" % (index, len(tests), name), file=fp) output = self.run_tests('--fromfile', filename) self.check_executed_tests(output, tests) # test format 'test_opcodes' with open(filename, "w") as fp: for name in tests: print(name, file=fp) output = self.run_tests('--fromfile', filename) self.check_executed_tests(output, tests) def test_interrupted(self): code = TEST_INTERRUPTED test = self.create_test('sigint', code=code) output = self.run_tests(test, exitcode=1) self.check_executed_tests(output, test, omitted=test, interrupted=True) def test_slowest(self): # test --slowest tests = [self.create_test() for index in range(3)] output = self.run_tests("--slowest", *tests) self.check_executed_tests(output, tests) regex = ('10 slowest tests:\n' '(?:- %s: .*\n){%s}' % (self.TESTNAME_REGEX, len(tests))) self.check_line(output, regex) def test_slow_interrupted(self): # Issue #25373: test --slowest with an interrupted test code = TEST_INTERRUPTED test = self.create_test("sigint", code=code) try: import threading tests = (False, True) except ImportError: tests = (False,) for multiprocessing in tests: if multiprocessing: args = ("--slowest", "-j2", test) else: args = ("--slowest", test) output = self.run_tests(*args, exitcode=1) self.check_executed_tests(output, test, omitted=test, interrupted=True) regex = ('10 slowest tests:\n') self.check_line(output, regex) def test_coverage(self): # test --coverage test = self.create_test('coverage') output = self.run_tests("--coverage", test) self.check_executed_tests(output, [test]) regex = (r'lines +cov% +module +\(path\)\n' r'(?: *[0-9]+ *[0-9]{1,2}% *[^ ]+ +\([^)]+\)+)+') self.check_line(output, regex) def test_wait(self): # test --wait test = self.create_test('wait') output = self.run_tests("--wait", test, input='key') self.check_line(output, 'Press any key to continue') def test_forever(self): # test --forever code = textwrap.dedent(""" import builtins import unittest class ForeverTester(unittest.TestCase): def test_run(self): # Store the state in the builtins module, because the test # module is reload at each run if 'RUN' in builtins.__dict__: builtins.__dict__['RUN'] += 1 if builtins.__dict__['RUN'] >= 3: self.fail("fail at the 3rd runs") else: builtins.__dict__['RUN'] = 1 """) test = self.create_test('forever', code=code) output = self.run_tests('--forever', test, exitcode=1) self.check_executed_tests(output, [test]*3, failed=test) @unittest.skipUnless(Py_DEBUG, 'need a debug build') def test_huntrleaks_fd_leak(self): # test --huntrleaks for file descriptor leak code = textwrap.dedent(""" import os import unittest # Issue #25306: Disable popups and logs to stderr on assertion # failures in MSCRT try: import msvcrt msvcrt.CrtSetReportMode except (ImportError, AttributeError): # no Windows, o release build pass else: for m in [msvcrt.CRT_WARN, msvcrt.CRT_ERROR, msvcrt.CRT_ASSERT]: msvcrt.CrtSetReportMode(m, 0) class FDLeakTest(unittest.TestCase): def test_leak(self): fd = os.open(__file__, os.O_RDONLY) # bug: never cloes the file descriptor """) test = self.create_test('huntrleaks', code=code) filename = 'reflog.txt' self.addCleanup(support.unlink, filename) output = self.run_tests('--huntrleaks', '3:3:', test, exitcode=1, stderr=subprocess.STDOUT) self.check_executed_tests(output, [test], failed=test) line = 'beginning 6 repetitions\n123456\n......\n' self.check_line(output, re.escape(line)) line2 = '%s leaked [1, 1, 1] file descriptors, sum=3\n' % test self.assertIn(line2, output) with open(filename) as fp: reflog = fp.read() self.assertIn(line2, reflog) def test_list_tests(self): # test --list-tests tests = [self.create_test() for i in range(5)] output = self.run_tests('--list-tests', *tests) self.assertEqual(output.rstrip().splitlines(), tests) if __name__ == '__main__': unittest.main()
airbnb/superset
refs/heads/master
setup.py
1
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import io import json import os import subprocess import sys from setuptools import find_packages, setup if sys.version_info < (3, 6): sys.exit("Sorry, Python < 3.6 is not supported") BASE_DIR = os.path.abspath(os.path.dirname(__file__)) PACKAGE_JSON = os.path.join(BASE_DIR, "superset-frontend", "package.json") with open(PACKAGE_JSON, "r") as package_file: version_string = json.load(package_file)["version"] with io.open("README.md", "r", encoding="utf-8") as f: long_description = f.read() def get_git_sha(): try: s = subprocess.check_output(["git", "rev-parse", "HEAD"]) return s.decode().strip() except Exception: return "" GIT_SHA = get_git_sha() version_info = {"GIT_SHA": GIT_SHA, "version": version_string} print("-==-" * 15) print("VERSION: " + version_string) print("GIT SHA: " + GIT_SHA) print("-==-" * 15) VERSION_INFO_FILE = os.path.join(BASE_DIR, "superset", "static", "version_info.json") with open(VERSION_INFO_FILE, "w") as version_file: json.dump(version_info, version_file) setup( name="apache-superset", description=("A modern, enterprise-ready business intelligence web application"), long_description=long_description, long_description_content_type="text/markdown", version=version_string, packages=find_packages(), include_package_data=True, zip_safe=False, entry_points={"console_scripts": ["superset=superset.cli:superset"]}, install_requires=[ "backoff>=1.8.0", "bleach>=3.0.2, <4.0.0", "cachelib>=0.1.1,<0.2", "celery>=4.3.0, <5.0.0, !=4.4.1", "click<8", "colorama", "contextlib2", "croniter>=0.3.28", "cryptography>=2.4.2", "flask>=1.1.0, <2.0.0", "flask-appbuilder>=3.0.1, <4.0.0", "flask-caching", "flask-compress", "flask-talisman", "flask-migrate", "flask-wtf", "geopy", "gunicorn>=20.0.2, <20.1", "humanize", "isodate", "markdown>=3.0", "msgpack>=1.0.0, <1.1", "pandas>=1.1.2, <1.2", "parsedatetime", "pathlib2", "polyline", "python-dateutil", "python-dotenv", "python-geohash", "pyarrow>=1.0.1, <1.1", "pyyaml>=5.1", "retry>=0.9.2", "selenium>=3.141.0", "simplejson>=3.15.0", "slackclient==2.5.0", # PINNED! slack changes file upload api in the future versions "sqlalchemy>=1.3.16, <2.0", "sqlalchemy-utils>=0.36.6,<0.37", "sqlparse==0.3.0", # PINNED! see https://github.com/andialbrecht/sqlparse/issues/562 "wtforms-json", ], extras_require={ "athena": ["pyathena>=1.10.8,<1.11"], "bigquery": ["pandas_gbq>=0.10.0", "pybigquery>=0.4.10"], "clickhouse": ["clickhouse-sqlalchemy>= 0.1.4, <0.2"], "cockroachdb": ["cockroachdb>=0.3.5, <0.4"], "cors": ["flask-cors>=2.0.0"], "db2": ["ibm-db-sa>=0.3.5, <0.4"], "dremio": ["sqlalchemy-dremio>=1.1.5, <1.2"], "drill": ["sqlalchemy-drill==0.1.dev"], "druid": ["pydruid>=0.6.1,<0.7"], "elasticsearch": ["elasticsearch-dbapi>=0.1.0, <0.2.0"], "exasol": ["sqlalchemy-exasol>=2.1.0, <2.2"], "excel": ["xlrd>=1.2.0, <1.3"], "gsheets": ["gsheetsdb>=0.1.9"], "hana": ["hdbcli==2.4.162", "sqlalchemy_hana==0.4.0"], "hive": ["pyhive[hive]>=0.6.1", "tableschema", "thrift>=0.11.0, <1.0.0"], "impala": ["impyla>0.16.2, <0.17"], "kylin": ["kylinpy>=2.8.1, <2.9"], "mmsql": ["pymssql>=2.1.4, <2.2"], "mysql": ["mysqlclient==1.4.2.post1"], "oracle": ["cx-Oracle>8.0.0, <8.1"], "pinot": ["pinotdb>=0.3.3, <0.4"], "postgres": ["psycopg2-binary==2.8.5"], "presto": ["pyhive[presto]>=0.4.0"], "prophet": ["fbprophet>=0.6, <0.7"], "redshift": ["sqlalchemy-redshift>=0.8.1, < 0.9"], "snowflake": ["snowflake-sqlalchemy>=1.2.3, <1.3"], "teradata": ["sqlalchemy-teradata==0.9.0.dev0"], "thumbnails": ["Pillow>=7.0.0, <8.0.0"], "vertica": ["sqlalchemy-vertica-python>=0.5.9, < 0.6"], }, python_requires="~=3.6", author="Apache Software Foundation", author_email="dev@superset.incubator.apache.org", url="https://superset.apache.org/", download_url="https://www.apache.org/dist/incubator/superset/" + version_string, classifiers=[ "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", ], )
andcor02/mbed-os
refs/heads/master
tools/host_tests/serial_nc_tx_auto.py
74
""" mbed SDK Copyright (c) 2011-2013 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys import uuid import time import string from sys import stdout class SerialNCTXTest(): def test(self, selftest): selftest.mbed.flush(); # Wait 0.5 seconds to ensure mbed is listening time.sleep(0.5) selftest.mbed.serial_write("S"); strip_chars = string.whitespace + "\0" out_str = selftest.mbed.serial_readline() selftest.notify("HOST: " + out_str) if not out_str: selftest.notify("HOST: No output detected") return selftest.RESULT_IO_SERIAL out_str_stripped = out_str.strip(strip_chars) if out_str_stripped != "TX OK - Expected": selftest.notify("HOST: Unexpected output. Expected 'TX OK - Expected' but received '%s'" % out_str_stripped) return selftest.RESULT_FAILURE out_str = selftest.mbed.serial_readline() # If no characters received, pass the test if not out_str: selftest.notify("HOST: No further output detected") return selftest.RESULT_SUCCESS else: out_str_stripped = out_str.strip(strip_chars) if out_str_stripped == "TX OK - Unexpected": selftest.notify("HOST: Unexpected output returned indicating TX still functioning") else: selftest.notify("HOST: Extraneous output '%s' detected indicating unknown error" % out_str_stripped) return selftest.RESULT_FAILURE
s20121035/rk3288_android5.1_repo
refs/heads/master
ndk/sources/host-tools/gdb-pretty-printers/stlport/gppfs-0.2/stlport/printers.py
17
# GDB pretty printers for STLport. # # Copyright (C) 2008, 2009, 2010 Free Software Foundation, Inc. # Copyright (C) 2010 Joachim Reichel # # 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/>. # pylint: disable=C0103,C0111,R0201,R0903 import gdb import re # Set the STLport version which is needed for a few features. # # - for std::list: # STLport older than 5.0? # - for std::deque, std::stack, and std::queue on 64bit systems: # STLport older than 5.2? stlport_version = 5.2 # Indicates whether std::vector is printed with indices. print_vector_with_indices = False def lookup_stlport_type (typename): "Look up a type in the public STLport namespace." namespaces = ['std::', 'stlpd_std::', 'stlp_std::', '_STL::'] for namespace in namespaces: try: return gdb.lookup_type (namespace + typename) except RuntimeError: pass def lookup_stlport_priv_type (typename): "Look up a type in the private STLport namespace." namespaces = ['std::priv::', 'stlpd_std::priv::', 'stlp_priv::', 'stlp_std::priv::', 'stlpd_std::', 'stlp_std::', '_STL::'] for namespace in namespaces: try: return gdb.lookup_type (namespace + typename) except RuntimeError: pass def get_non_debug_impl (value, member = None): "Return the non-debug implementation of value or value[member]." if member: value = value[member] try: return value['_M_non_dbg_impl'] except RuntimeError: return value class RbtreeIterator: def __init__ (self, rbtree): tree = get_non_debug_impl (rbtree , '_M_t') self.size = tree['_M_node_count'] self.node = tree['_M_header']['_M_data']['_M_left'] self.count = 0 def __iter__ (self): return self def __len__ (self): return int (self.size) def next (self): if self.count == self.size: raise StopIteration result = self.node self.count += 1 if self.count < self.size: node = self.node # Is there a right child? if node.dereference()['_M_right']: # Walk down to left-most child in right subtree. node = node.dereference()['_M_right'] while node.dereference()['_M_left']: node = node.dereference()['_M_left'] else: # Walk up to first parent reached via left subtree. parent = node.dereference()['_M_parent'] while node == parent.dereference()['_M_right']: node = parent parent = parent.dereference()['_M_parent'] node = parent self.node = node return result class BitsetPrinter: "Pretty printer for std::bitset." def __init__(self, typename, val): self.typename = typename self.val = val def to_string (self): # If template_argument handled values, we could print the # size. Or we could use a regexp on the type. return '%s' % (self.typename) def children (self): words = self.val['_M_w'] # The _M_w member can be either an unsigned long, or an # array. This depends on the template specialization used. # If it is a single long, convert to a single element list. if words.type.code == gdb.TYPE_CODE_ARRAY: word_size = words.type.target ().sizeof n_words = words.type.sizeof / word_size else: word_size = words.type.sizeof n_words = 1 words = [words] result = [] word = 0 while word < n_words: w = words[word] bit = 0 while w != 0: if w & 1: result.append (('[%d]' % (word * word_size * 8 + bit), 1)) bit += 1 w = w >> 1 word += 1 return result class DequePrinter: "Pretty printer for std::deque." class Iterator: def __init__ (self, start_node, start_cur, start_last, finish_cur, buffer_size): self.node = start_node self.item = start_cur self.node_last = start_last self.last = finish_cur self.buffer_size = buffer_size self.count = 0 def __iter__ (self): return self def next (self): if self.item == self.last: raise StopIteration result = ('[%d]' % self.count, self.item.dereference()) self.count += 1 self.item += 1 if self.item == self.node_last: self.node += 1 self.item = self.node[0] self.node_last = self.item + self.buffer_size return result def __init__ (self, typename, val): self.typename = typename self.val = get_non_debug_impl (val) size = val.type.template_argument(0).sizeof # see MAX_BYTES in stlport/stl/_alloc.h if stlport_version < 5.2: blocksize = 128 else: blocksize = 32 * gdb.lookup_type ("void").pointer().sizeof if size < blocksize: self.buffer_size = int (blocksize / size) else: self.buffer_size = 1 def to_string (self): start = self.val['_M_start'] finish = self.val['_M_finish'] delta_n = finish['_M_node'] - start['_M_node'] - 1 delta_s = start['_M_last'] - start['_M_cur'] delta_f = finish['_M_cur'] - finish['_M_first'] if delta_n == -1: size = delta_f else: size = self.buffer_size * delta_n + delta_s + delta_f ta0 = self.val.type.template_argument (0) return '%s<%s> with %d elements' % (self.typename, ta0, int (size)) def children (self): start = self.val['_M_start'] finish = self.val['_M_finish'] return self.Iterator (start['_M_node'], start['_M_cur'], start['_M_last'], finish['_M_cur'], self.buffer_size) def display_hint (self): return 'array' class ListPrinter: "Pretty printer for std::list." class Iterator: def __init__ (self, node_type, head): self.node_type = node_type # see empty() in stlport/stl/_list.h if stlport_version < 5.0: self.sentinel = head else: self.sentinel = head.address self.item = head['_M_next'] self.count = 0 def __iter__ (self): return self def next (self): if self.item == self.sentinel: raise StopIteration node = self.item.cast (self.node_type).dereference() self.item = node['_M_next'] count = self.count self.count += 1 return ('[%d]' % count, node['_M_data']) def __init__(self, typename, val): self.typename = typename self.val = get_non_debug_impl (val) def children (self): ta0 = self.val.type.template_argument(0) node_type = lookup_stlport_priv_type ('_List_node<%s>' % ta0).pointer() return self.Iterator (node_type, self.val['_M_node']['_M_data']) def to_string (self): ta0 = self.val.type.template_argument (0) # see empty() in stlport/stl/_list.h if stlport_version < 5.0: sentinel = self.val['_M_node']['_M_data'] else: sentinel = self.val['_M_node']['_M_data'].address if self.val['_M_node']['_M_data']['_M_next'] == sentinel: return 'empty %s<%s>' % (self.typename, ta0) return '%s<%s>' % (self.typename, ta0) def display_hint (self): return 'array' class MapPrinter: "Pretty printer for std::map and std::multimap." class Iterator: def __init__ (self, rbiter, node_type): self.rbiter = rbiter self.node_type = node_type self.count = 0 def __iter__ (self): return self def next (self): if self.count % 2 == 0: item = self.rbiter.next().dereference() self.pair = (item.cast (self.node_type))['_M_value_field'] element = self.pair['first'] else: element = self.pair['second'] count = self.count self.count += 1 return ('[%d]' % count, element) def __init__ (self, typename, val): self.typename = typename self.val = val def children (self): key_type = self.val.type.template_argument (0) value_type = self.val.type.template_argument (1) pair_type \ = lookup_stlport_type ('pair<%s const,%s>' % (key_type,value_type)) node_type \ = lookup_stlport_priv_type ('_Rb_tree_node<%s >' % str (pair_type)) return self.Iterator (RbtreeIterator (self.val), node_type) def to_string (self): ta0 = self.val.type.template_argument (0) count = get_non_debug_impl (self.val, '_M_t')['_M_node_count'] return ('%s<%s> with %d elements' % (self.typename, ta0, count)) def display_hint (self): return 'map' class SetPrinter: "Pretty printer for std::set and std::multiset." class Iterator: def __init__ (self, rbiter, node_type): self.rbiter = rbiter self.node_type = node_type self.count = 0 def __iter__ (self): return self def next (self): item = self.rbiter.next().dereference() element = (item.cast (self.node_type))['_M_value_field'] count = self.count self.count += 1 return ('[%d]' % count, element) def __init__ (self, typename, val): self.typename = typename self.val = val def children (self): value_type = self.val.type.template_argument (0) node_type \ = lookup_stlport_priv_type ('_Rb_tree_node<%s>' % (value_type)) return self.Iterator (RbtreeIterator (self.val), node_type) def to_string (self): ta0 = self.val.type.template_argument (0) count = get_non_debug_impl (self.val, '_M_t')['_M_node_count'] return ('%s<%s> with %d elements' % (self.typename, ta0, count)) def display_hint (self): return 'array' class SlistPrinter: "Pretty printer for std::slist." class Iterator: def __init__ (self, node_type, head): self.node_type = node_type self.item = head['_M_next'] self.count = 0 def __iter__ (self): return self def next (self): if self.item == 0: raise StopIteration node = self.item.cast (self.node_type).dereference() self.item = node['_M_next'] count = self.count self.count += 1 return ('[%d]' % count, node['_M_data']) def __init__(self, typename, val): self.typename = typename self.val = get_non_debug_impl (val) def children (self): ta0 = self.val.type.template_argument(0) node_type = lookup_stlport_priv_type ('_Slist_node<%s>' % ta0).pointer() return self.Iterator (node_type, self.val['_M_head']['_M_data']) def to_string (self): ta0 = self.val.type.template_argument (0) if self.val['_M_head']['_M_data']['_M_next'] == 0: return 'empty %s<%s>' % (self.typename, ta0) return '%s<%s>' % (self.typename, ta0) def display_hint (self): return 'array' class StringPrinter: "Pretty printer for std::string or std::wstring." def __init__ (self, _typename, val): self.val = get_non_debug_impl (val) def to_string (self): try: # STLport 5.2 and later return self.val['_M_start_of_storage']['_M_data'] except RuntimeError: try: # STLport 5.0 and 5.1 with short string optimization static_buf = self.val['_M_buffers']['_M_static_buf'] data = self.val['_M_end_of_storage']['_M_data'] if static_buf.address + 1 == data: ta0 = self.val.type.template_argument (0) start = static_buf.cast (ta0.pointer()) finish = self.val['_M_finish'] if start == finish: # STLport 5.0 without _STLP_FORCE_STRING_TERMINATION return "" return start return self.val['_M_buffers']['_M_dynamic_buf'] except RuntimeError: # STLport 5.0 and 5.1 without short string optimization, # and STLport 4.6 start = self.val['_M_start'] finish = self.val['_M_finish'] if start == finish: # STLport 5.0 without _STLP_FORCE_STRING_TERMINATION return "" return start def display_hint (self): return 'string' class VectorPrinter: "Pretty printer for std::vector." class Iterator: def __init__ (self, start, finish, bit_vector): self.bit_vector = bit_vector self.count = 0 if bit_vector: self.item = start['_M_p'] self.io = start['_M_offset'] self.finish = finish['_M_p'] self.fo = finish['_M_offset'] self.isize = 8 * self.item.dereference().type.sizeof else: self.item = start self.finish = finish def __iter__ (self): return self def next (self): count = self.count self.count += 1 if self.bit_vector: if self.item == self.finish and self.io == self.fo: raise StopIteration element = self.item.dereference() value = 0 if element & (1 << self.io): value = 1 self.io += 1 if self.io >= self.isize: self.item += 1 self.io = 0 return ('[%d]' % count, value) else: if self.item == self.finish: raise StopIteration element = self.item.dereference() self.item += 1 return ('[%d]' % count, element) def __init__ (self, typename, val): self.typename = typename self.val = get_non_debug_impl (val) self.bit_vector \ = val.type.template_argument (0).code == gdb.TYPE_CODE_BOOL def children (self): start = self.val['_M_start'] finish = self.val['_M_finish'] return self.Iterator (start, finish, self.bit_vector) def to_string (self): if self.bit_vector: start = self.val['_M_start']['_M_p'] so = self.val['_M_start']['_M_offset'] finish = self.val['_M_finish']['_M_p'] fo = self.val['_M_finish']['_M_offset'] end = self.val['_M_end_of_storage']['_M_data'] isize = 8 * start.dereference().type.sizeof length = (isize - so) + isize * (finish - start - 1) + fo capacity = isize * (end - start) return ('%s<bool> of length %d, capacity %d' % (self.typename, length, capacity)) else: start = self.val['_M_start'] finish = self.val['_M_finish'] end = self.val['_M_end_of_storage']['_M_data'] length = finish - start capacity = end - start ta0 = self.val.type.template_argument (0) return ('%s<%s> of length %d, capacity %d' % (self.typename, ta0, length, capacity)) def display_hint (self): if print_vector_with_indices: return None else: return 'array' class WrapperPrinter: "Pretty printer for std::stack, std::queue, and std::priority_queue." def __init__ (self, typename, val): self.typename = typename self.val = val self.visualizer = gdb.default_visualizer (val['c']) def children (self): return self.visualizer.children() def to_string (self): ta0 = self.val.type.template_argument (0) return ('%s<%s>, wrapping %s' % (self.typename, ta0, self.visualizer.to_string())) def display_hint (self): if hasattr (self.visualizer, 'display_hint'): return self.visualizer.display_hint() return None class UnorderedMapPrinter: """Pretty printer for std::tr1::unordered_map and std::tr1::unordered_multimap.""" class Iterator: def __init__ (self, node_type, head): self.node_type = node_type self.item = head['_M_next'] self.count = 0 def __iter__ (self): return self def next (self): if self.item == 0 and self.count % 2 == 0: raise StopIteration if self.count % 2 == 0: self.pair = self.item.cast (self.node_type).dereference() self.item = self.pair['_M_next'] element = self.pair['_M_data']['first'] else: element = self.pair['_M_data']['second'] count = self.count self.count += 1 return ('[%d]' % count, element) def __init__(self, typename, val): self.typename = typename self.val = get_non_debug_impl (val) def children (self): key_type = self.val.type.template_argument (0) value_type = self.val.type.template_argument (1) pair_type \ = lookup_stlport_type ('pair<%s const,%s>' % (key_type,value_type)) node_type \ = lookup_stlport_priv_type ('_Slist_node<%s >' % str (pair_type)).pointer() elements = get_non_debug_impl (self.val, '_M_ht')['_M_elems'] return self.Iterator (node_type, elements['_M_head']['_M_data']) def to_string (self): ta0 = self.val.type.template_argument (0) length = get_non_debug_impl (self.val, '_M_ht')['_M_num_elements'] if length == 0: return 'empty %s<%s>' % (self.typename, ta0) return '%s<%s> with %d elements' % (self.typename, ta0, length) def display_hint (self): return 'map' class UnorderedSetPrinter: """Pretty printer for std::tr1::unordered_set and std::tr1::unordered_multiset.""" class Iterator: def __init__ (self, node_type, head): self.node_type = node_type self.item = head['_M_next'] self.count = 0 def __iter__ (self): return self def next (self): if self.item == 0: raise StopIteration node = self.item.cast (self.node_type).dereference() self.item = node['_M_next'] count = self.count self.count += 1 return ('[%d]' % count, node['_M_data']) def __init__(self, typename, val): self.typename = typename self.val = get_non_debug_impl (val) def children (self): ta0 = self.val.type.template_argument(0) node_type = lookup_stlport_priv_type ('_Slist_node<%s>' % ta0).pointer() elements = get_non_debug_impl (self.val, '_M_ht')['_M_elems'] return self.Iterator (node_type, elements['_M_head']['_M_data']) def to_string (self): ta0 = self.val.type.template_argument (0) length = get_non_debug_impl (self.val, '_M_ht')['_M_num_elements'] if length == 0: return 'empty %s<%s>' % (self.typename, ta0) return '%s<%s> with %d elements' % (self.typename, ta0, length) def display_hint (self): return 'array' class AutoptrPrinter: "Pretty printer for std::auto_ptr." def __init__ (self, typename, val): self.typename = typename self.val = val def to_string (self): ta0 = self.val.type.template_argument (0) pointer = self.val['_M_p'].cast (ta0.pointer()) if pointer == 0: return ('%s<%s> (empty)' % (self.typename, ta0)) else: return ('%s<%s>, pointing to %s' % (self.typename, ta0, pointer.dereference())) def display_hint (self): return None class SharedptrPrinter: "Pretty printer for std::shared_ptr and std::weak_ptr." def __init__ (self, typename, val): self.typename = typename self.val = val def to_string (self): ta0 = self.val.type.template_argument (0) pointer = self.val['px'].cast (ta0.pointer()) if pointer == 0: return ('%s<%s> (empty)' % (self.typename, ta0)) else: count = self.val['pn']['pi_']['use_count_'] return ('%s<%s> (count %d), pointing to %s' % (self.typename, ta0, count, pointer.dereference())) def display_hint (self): return None def lookup_function (val): "Look-up and return a pretty-printer that can print val." type = val.type if type.code == gdb.TYPE_CODE_REF: type = type.target() type = type.unqualified().strip_typedefs() typename = type.tag if typename == None: return None for function in pretty_printers_dict: if function.search (typename): return pretty_printers_dict[function] (val) return None def register_stlport_printers (obj): "Register STLport pretty-printers with object file obj." if obj == None: obj = gdb obj.pretty_printers.append (lookup_function) pretty_printers_dict = {} def add_entry (regex, printer, typename): prefix = "^(stlpd?_std|_STL|std)::" suffix = "<.*>$" if typename != None: typename = "std::" + typename if regex[0:5] == "boost": prefix = "" pretty_printers_dict[re.compile (prefix+regex+suffix)] \ = lambda val: printer (typename, val) add_entry ("basic_string", StringPrinter, None) add_entry ("bitset", BitsetPrinter, "bitset") add_entry ("deque", DequePrinter, "deque") add_entry ("map", MapPrinter, "map") add_entry ("list", ListPrinter, "list") add_entry ("multimap", MapPrinter, "multimap") add_entry ("multiset", SetPrinter, "multiset") add_entry ("queue", WrapperPrinter, "queue") add_entry ("priority_queue", WrapperPrinter, "priority_queue") add_entry ("set", SetPrinter, "set") add_entry ("slist", SlistPrinter, "slist") add_entry ("stack", WrapperPrinter, "stack") add_entry ("vector", VectorPrinter, "vector") add_entry ("tr1::unordered_map", UnorderedMapPrinter, "tr1::unordered_map") add_entry ("tr1::unordered_multimap", UnorderedMapPrinter, "tr1::unordered_multimap") add_entry ("tr1::unordered_set", UnorderedSetPrinter, "tr1::unordered_set") add_entry ("tr1::unordered_multiset", UnorderedSetPrinter, "tr1::unordered_multiset") add_entry ("auto_ptr", AutoptrPrinter, "auto_ptr") add_entry ("boost::shared_ptr", SharedptrPrinter, "tr1::shared_ptr") add_entry ("boost::weak_ptr", SharedptrPrinter, "tr1::weak_ptr")
shiminasai/ciat_plataforma
refs/heads/master
mapeo/migrations/0009_auto__add_composicionfamiliar__add_productorgranosbasicos__add_usosuel.py
3
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'ComposicionFamiliar' db.create_table(u'mapeo_composicionfamiliar', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('persona', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['mapeo.Persona'])), ('familia', self.gf('django.db.models.fields.IntegerField')()), ('edad', self.gf('django.db.models.fields.IntegerField')()), ('escolaridad', self.gf('django.db.models.fields.IntegerField')()), ('participacion', self.gf('django.db.models.fields.IntegerField')()), )) db.send_create_signal(u'mapeo', ['ComposicionFamiliar']) # Adding model 'ProductorGranosBasicos' db.create_table(u'mapeo_productorgranosbasicos', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('persona', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['mapeo.Persona'])), ('organizacion', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['mapeo.Organizaciones'])), ('nombre_finca', self.gf('django.db.models.fields.CharField')(max_length=200)), ('telefono', self.gf('django.db.models.fields.IntegerField')()), ('latitud', self.gf('django.db.models.fields.IntegerField')()), ('longitud', self.gf('django.db.models.fields.IntegerField')()), ('nombre_productor', self.gf('django.db.models.fields.CharField')(max_length=200)), ('relacion', self.gf('django.db.models.fields.IntegerField')()), )) db.send_create_signal(u'mapeo', ['ProductorGranosBasicos']) # Adding model 'UsoSuelo' db.create_table(u'mapeo_usosuelo', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('persona', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['mapeo.Persona'])), ('uso', self.gf('django.db.models.fields.IntegerField')()), ('cantidad', self.gf('django.db.models.fields.FloatField')()), )) db.send_create_signal(u'mapeo', ['UsoSuelo']) def backwards(self, orm): # Deleting model 'ComposicionFamiliar' db.delete_table(u'mapeo_composicionfamiliar') # Deleting model 'ProductorGranosBasicos' db.delete_table(u'mapeo_productorgranosbasicos') # Deleting model 'UsoSuelo' db.delete_table(u'mapeo_usosuelo') models = { u'configuracion.areaaccion': { 'Meta': {'object_name': 'AreaAccion'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'configuracion.plataforma': { 'Meta': {'object_name': 'Plataforma'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'sitio_accion': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['configuracion.SitioAccion']"}) }, u'configuracion.sector': { 'Meta': {'object_name': 'Sector'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, u'configuracion.sitioaccion': { 'Meta': {'object_name': 'SitioAccion'}, 'area_accion': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['configuracion.AreaAccion']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'configuration.sector_en': { 'Meta': {'object_name': 'Sector_en'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, u'lugar.comunidad': { 'Meta': {'ordering': "['nombre']", 'object_name': 'Comunidad'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'latitud': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '8', 'decimal_places': '5', 'blank': 'True'}), 'longitud': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '8', 'decimal_places': '5', 'blank': 'True'}), 'municipio': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['lugar.Municipio']"}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '40'}) }, u'lugar.departamento': { 'Meta': {'ordering': "['nombre']", 'object_name': 'Departamento'}, 'extension': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True'}), 'latitud': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '8', 'decimal_places': '5', 'blank': 'True'}), 'longitud': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '8', 'decimal_places': '5', 'blank': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}), 'pais': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['lugar.Pais']"}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'unique': 'True', 'null': 'True'}) }, u'lugar.municipio': { 'Meta': {'ordering': "['departamento__nombre', 'nombre']", 'object_name': 'Municipio'}, 'departamento': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['lugar.Departamento']"}), 'extension': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'id': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True'}), 'latitud': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '8', 'decimal_places': '5', 'blank': 'True'}), 'longitud': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '8', 'decimal_places': '5', 'blank': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'unique': 'True', 'null': 'True'}) }, u'lugar.pais': { 'Meta': {'object_name': 'Pais'}, 'codigo': ('django.db.models.fields.CharField', [], {'max_length': '2'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, u'mapeo.accionar': { 'Meta': {'object_name': 'Accionar'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'mapeo.campoaccion': { 'Meta': {'object_name': 'CampoAccion'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'mapeo.composicionfamiliar': { 'Meta': {'object_name': 'ComposicionFamiliar'}, 'edad': ('django.db.models.fields.IntegerField', [], {}), 'escolaridad': ('django.db.models.fields.IntegerField', [], {}), 'familia': ('django.db.models.fields.IntegerField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'participacion': ('django.db.models.fields.IntegerField', [], {}), 'persona': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['mapeo.Persona']"}) }, u'mapeo.decisor': { 'Meta': {'object_name': 'Decisor'}, 'campo': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['mapeo.CampoAccion']", 'symmetrical': 'False', 'blank': 'True'}), 'correo_electronico': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nivel': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['mapeo.Accionar']", 'symmetrical': 'False', 'blank': 'True'}), 'persona': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['mapeo.Persona']"}), 'pertenece': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['mapeo.Organizaciones']", 'symmetrical': 'False', 'blank': 'True'}), 'proyecto': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['mapeo.Proyectos']", 'symmetrical': 'False', 'blank': 'True'}) }, u'mapeo.especialidades': { 'Meta': {'object_name': 'Especialidades'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'mapeo.formaatencion': { 'Meta': {'object_name': 'FormaAtencion'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'mapeo.fuentemanoobra': { 'Meta': {'object_name': 'FuenteManoObra'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'mapeo.lideres': { 'Meta': {'object_name': 'Lideres'}, 'atiende': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'correo_electronico': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'fecha': ('django.db.models.fields.DateField', [], {}), 'finca': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'forma_atiende': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['mapeo.FormaAtencion']", 'symmetrical': 'False', 'blank': 'True'}), 'fuente': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['mapeo.FuenteManoObra']", 'symmetrical': 'False', 'blank': 'True'}), 'ganado': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'jefe': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'organizacion': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'org'", 'null': 'True', 'symmetrical': 'False', 'to': u"orm['mapeo.Organizaciones']"}), 'persona': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['mapeo.Persona']"}), 'proyecto': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['mapeo.Proyectos']", 'symmetrical': 'False', 'blank': 'True'}), 'rubro_principal_agro': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'principal'", 'null': 'True', 'to': u"orm['mapeo.RubrosAgropecuarios']"}), 'rubro_principal_no_agro': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'principalno'", 'null': 'True', 'to': u"orm['mapeo.RubrosNoAgropecuarios']"}), 'rubros_agro': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'agro'", 'blank': 'True', 'to': u"orm['mapeo.RubrosAgropecuarios']"}), 'rubros_no_agro': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'noagro'", 'blank': 'True', 'to': u"orm['mapeo.RubrosNoAgropecuarios']"}), 'tamano': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'tipologia': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, u'mapeo.organizaciones': { 'Meta': {'ordering': "[u'nombre']", 'unique_together': "((u'font_color', u'nombre'),)", 'object_name': 'Organizaciones'}, 'area_accion': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['configuracion.AreaAccion']"}), 'contacto': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'correo_electronico': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'departamento': ('smart_selects.db_fields.ChainedForeignKey', [], {'to': u"orm['lugar.Departamento']", 'null': 'True', 'blank': 'True'}), 'direccion': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'font_color': ('mapeo.models.ColorField', [], {'unique': 'True', 'max_length': '10', 'blank': 'True'}), 'fundacion': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'generalidades': ('ckeditor.fields.RichTextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'logo': (u'sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'municipio': ('smart_selects.db_fields.ChainedForeignKey', [], {'to': u"orm['lugar.Municipio']", 'null': 'True', 'blank': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'pais': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['lugar.Pais']"}), 'plataforma': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['configuracion.Plataforma']"}), 'rss': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'sector': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['configuracion.Sector']"}), 'sector_en': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['configuration.Sector_en']", 'null': 'True', 'blank': 'True'}), 'siglas': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'sitio_accion': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['configuracion.SitioAccion']"}), 'sitio_web': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'telefono': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'temas': ('ckeditor.fields.RichTextField', [], {'null': 'True', 'blank': 'True'}) }, u'mapeo.persona': { 'Meta': {'object_name': 'Persona'}, 'cedula': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'comunidad': ('smart_selects.db_fields.ChainedForeignKey', [], {'to': u"orm['lugar.Comunidad']"}), 'departamento': ('smart_selects.db_fields.ChainedForeignKey', [], {'to': u"orm['lugar.Departamento']"}), 'edad': ('django.db.models.fields.IntegerField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'municipio': ('smart_selects.db_fields.ChainedForeignKey', [], {'to': u"orm['lugar.Municipio']"}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'pais': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['lugar.Pais']"}), 'sexo': ('django.db.models.fields.IntegerField', [], {}), 'tipo_persona': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, u'mapeo.productor': { 'Meta': {'object_name': 'Productor'}, 'fecha': ('django.db.models.fields.DateField', [], {}), 'fecha1': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'finca': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'fuente': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['mapeo.FuenteManoObra']", 'symmetrical': 'False', 'blank': 'True'}), 'ganado': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'jefe': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'organizacion': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'organizacion'", 'blank': 'True', 'to': u"orm['mapeo.Organizaciones']"}), 'persona': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['mapeo.Persona']"}), 'proyecto': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['mapeo.Proyectos']", 'symmetrical': 'False', 'blank': 'True'}), 'rubro_principal_agro': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'dos'", 'null': 'True', 'to': u"orm['mapeo.RubrosAgropecuarios']"}), 'rubro_principal_no_agro': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'cuatro'", 'null': 'True', 'to': u"orm['mapeo.RubrosNoAgropecuarios']"}), 'rubros_agro': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'uno'", 'blank': 'True', 'to': u"orm['mapeo.RubrosAgropecuarios']"}), 'rubros_no_agro': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'tres'", 'blank': 'True', 'to': u"orm['mapeo.RubrosNoAgropecuarios']"}), 'tamano': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}), 'tipologia': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, u'mapeo.productorgranosbasicos': { 'Meta': {'object_name': 'ProductorGranosBasicos'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'latitud': ('django.db.models.fields.IntegerField', [], {}), 'longitud': ('django.db.models.fields.IntegerField', [], {}), 'nombre_finca': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'nombre_productor': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'organizacion': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['mapeo.Organizaciones']"}), 'persona': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['mapeo.Persona']"}), 'relacion': ('django.db.models.fields.IntegerField', [], {}), 'telefono': ('django.db.models.fields.IntegerField', [], {}) }, u'mapeo.proyectos': { 'Meta': {'object_name': 'Proyectos'}, 'alianza': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['configuracion.Plataforma']", 'symmetrical': 'False'}), 'codigo': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'corto': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'descripcion': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'ejecutora': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['mapeo.Organizaciones']"}), 'encargado': ('django.db.models.fields.CharField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'finalizacion': ('django.db.models.fields.DateField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'influencia': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['lugar.Municipio']", 'symmetrical': 'False'}), 'informacion': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'inicio': ('django.db.models.fields.DateField', [], {}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'socias': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "u'socias'", 'symmetrical': 'False', 'to': u"orm['mapeo.Organizaciones']"}), 'temas': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['mapeo.Temas']", 'symmetrical': 'False', 'blank': 'True'}), 'tipo': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['mapeo.TiposProyectos']", 'null': 'True', 'blank': 'True'}) }, u'mapeo.rubrosagropecuarios': { 'Meta': {'object_name': 'RubrosAgropecuarios'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'mapeo.rubrosnoagropecuarios': { 'Meta': {'object_name': 'RubrosNoAgropecuarios'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'mapeo.tecnicoespinvestigador': { 'Meta': {'object_name': 'TecnicoEspInvestigador'}, 'correo_electronico': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'especialidad': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['mapeo.Especialidades']", 'symmetrical': 'False', 'blank': 'True'}), 'experiencia': ('django.db.models.fields.CharField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'formacion': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'persona': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['mapeo.Persona']"}), 'pertenece': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['mapeo.Organizaciones']", 'symmetrical': 'False', 'blank': 'True'}), 'proyecto': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['mapeo.Proyectos']", 'symmetrical': 'False', 'blank': 'True'}) }, u'mapeo.temas': { 'Meta': {'object_name': 'Temas'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'mapeo.timelineproyecto': { 'Meta': {'object_name': 'TimeLineProyecto'}, 'fecha': ('django.db.models.fields.DateField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'mes': ('django.db.models.fields.IntegerField', [], {}), 'proyecto': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['mapeo.Proyectos']"}), 'texto': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'year': ('django.db.models.fields.IntegerField', [], {}) }, u'mapeo.tiposproyectos': { 'Meta': {'object_name': 'TiposProyectos'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'mapeo.usosuelo': { 'Meta': {'object_name': 'UsoSuelo'}, 'cantidad': ('django.db.models.fields.FloatField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'persona': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['mapeo.Persona']"}), 'uso': ('django.db.models.fields.IntegerField', [], {}) } } complete_apps = ['mapeo']
odoobgorg/odoo
refs/heads/9.0
addons/l10n_mx/__openerp__.py
18
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Coded by: Alejandro Negrin anegrin@vauxoo.com, # Planified by: Alejandro Negrin, Humberto Arocha, Moises Lopez # Finance by: Vauxoo. # Audited by: Humberto Arocha (hbto@vauxoo.com) y Moises Lopez (moylop260@vauxoo.com) # Part of Odoo. See LICENSE file for full copyright and licensing details. { "name": "Mexico - Accounting", "version": "2.0", "author": "Vauxoo", 'category': 'Localization', "description": """ Minimal accounting configuration for Mexico. ============================================ This Chart of account is a minimal proposal to be able to use OoB the accounting feature of Openerp. This doesn't pretend be all the localization for MX it is just the minimal data required to start from 0 in mexican localization. This modules and its content is updated frequently by openerp-mexico team. With this module you will have: - Minimal chart of account tested in production eviroments. - Minimal chart of taxes, to comply with SAT_ requirements. .. SAT: http://www.sat.gob.mx/ """, "depends": ["account", "base_vat"], "demo_xml": [], "data": [ "data/account_chart.xml", "data/account_tax.xml", "data/account_chart_template.yml", ], "installable": True, "certificate": False, }
ITURO/ituro
refs/heads/master
ituro/sumo/management/commands/__init__.py
12133432
bop/hybrid
refs/heads/master
lib/python2.6/site-packages/django/conf/locale/de_CH/__init__.py
12133432
arivarton/multi-torrent-downloader
refs/heads/master
mtorrentd/site-modules/__init__.py
12133432
yagoulas/OpenBazaar
refs/heads/master
test/test_ec.py
3
import unittest import pyelliptic as ec from node import crypto_util class TestPyellipticSymmetric(unittest.TestCase): @classmethod def setUpClass(cls): cls.ciphername = "aes-256-cfb" cls.secret_key = "YELLOW SUBMARINE" def test_symmetric_one_pass(self): encrypt, decrypt = 1, 0 iv = ec.Cipher.gen_IV(self.ciphername) enc_cipher = ec.Cipher( self.secret_key, iv, encrypt, ciphername=self.ciphername ) plaintext_part1 = "Test plaintext part 1" plaintext_part2 = "Test plaintext part 2" plaintext = plaintext_part1 + plaintext_part2 ciphertext_part1 = enc_cipher.update(plaintext_part1) ciphertext_part2 = enc_cipher.update(plaintext_part2) ciphertext_final = enc_cipher.final() ciphertext = "".join(( ciphertext_part1, ciphertext_part2, ciphertext_final )) dec_cipher = ec.Cipher( self.secret_key, iv, decrypt, ciphername=self.ciphername ) self.assertEqual(plaintext, dec_cipher.ciphering(ciphertext)) class TestPyellipticAsymmetric(unittest.TestCase): @classmethod def setUpClass(cls): cls.alice = ec.ECC(curve=crypto_util.BTC_CURVE) cls.bob = ec.ECC(curve=crypto_util.BTC_CURVE) cls.bob_pubkey = cls.bob.get_pubkey() cls.bob_privkey = cls.bob.get_privkey() cls.alice_pubkey = cls.alice.get_pubkey() cls.data = "YELLOW SUBMARINE" def test_asymmetric_enc_dec(self): plaintext = "Hello Bob" ciphertext = self.alice.encrypt(plaintext, self.bob_pubkey) self.assertEqual(plaintext, self.bob.decrypt(ciphertext)) def test_asymmetric_sing_ver(self): signature = self.bob.sign("Hello Alice") bob_pubkey = self.bob.get_pubkey() self.assertTrue( ec.ECC(pubkey=bob_pubkey).verify(signature, "Hello Alice") ) def test_key_agreement(self): key1 = self.alice.get_ecdh_key(self.bob_pubkey).encode("hex") key2 = self.bob.get_ecdh_key(self.alice_pubkey).encode("hex") self.assertEqual(key1, key2) def test_curve_mismatch(self): agent1 = ec.ECC(curve="sect571r1") agent2 = self.alice # working on another curve with self.assertRaises(Exception): agent2.get_ecdh_key(agent1.get_pubkey()) def test_encrypt_is_static(self): obj_agent1 = ec.ECC(curve=crypto_util.BTC_CURVE) obj_agent2 = ec.ECC(curve='sect283k1') cls_agent3 = ec.ECC encd1 = obj_agent1.encrypt(self.data, self.bob_pubkey) encd2 = obj_agent2.encrypt(self.data, self.bob_pubkey) encd3 = cls_agent3.encrypt(self.data, self.bob_pubkey) dcd1 = self.bob.decrypt(encd1) dcd2 = self.bob.decrypt(encd2) dcd3 = self.bob.decrypt(encd3) self.assertEqual(dcd1, dcd2) self.assertEqual(dcd2, dcd3) if __name__ == "__main__": unittest.main()
bitcity/django-allauth
refs/heads/master
test_settings.py
26
# -*- coding: utf-8 -*- import django SECRET_KEY = 'psst' SITE_ID = 1 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } ROOT_URLCONF = 'allauth.urls' if django.VERSION >= (1, 8): TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages' ], }, }, ] else: TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.request", "django.contrib.messages.context_processors.messages", ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.amazon', 'allauth.socialaccount.providers.angellist', 'allauth.socialaccount.providers.baidu', 'allauth.socialaccount.providers.bitbucket', 'allauth.socialaccount.providers.bitly', 'allauth.socialaccount.providers.coinbase', 'allauth.socialaccount.providers.douban', 'allauth.socialaccount.providers.dropbox', 'allauth.socialaccount.providers.dropbox_oauth2', 'allauth.socialaccount.providers.edmodo', 'allauth.socialaccount.providers.evernote', 'allauth.socialaccount.providers.feedly', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.flickr', 'allauth.socialaccount.providers.foursquare', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.github', 'allauth.socialaccount.providers.hubic', 'allauth.socialaccount.providers.instagram', 'allauth.socialaccount.providers.linkedin', 'allauth.socialaccount.providers.linkedin_oauth2', 'allauth.socialaccount.providers.mailru', 'allauth.socialaccount.providers.windowslive', 'allauth.socialaccount.providers.odnoklassniki', 'allauth.socialaccount.providers.openid', 'allauth.socialaccount.providers.orcid', 'allauth.socialaccount.providers.paypal', 'allauth.socialaccount.providers.persona', 'allauth.socialaccount.providers.soundcloud', 'allauth.socialaccount.providers.spotify', 'allauth.socialaccount.providers.stackexchange', 'allauth.socialaccount.providers.tumblr', 'allauth.socialaccount.providers.twitch', 'allauth.socialaccount.providers.twitter', 'allauth.socialaccount.providers.vimeo', 'allauth.socialaccount.providers.weibo', 'allauth.socialaccount.providers.vk', 'allauth.socialaccount.providers.xing', ) AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) STATIC_ROOT = '/tmp/' # Dummy STATIC_URL = '/static/'
domenicosolazzo/practice-django
refs/heads/master
venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/chardet/euckrfreq.py
3120
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # Sampling from about 20M text materials include literature and computer technology # 128 --> 0.79 # 256 --> 0.92 # 512 --> 0.986 # 1024 --> 0.99944 # 2048 --> 0.99999 # # Idea Distribution Ratio = 0.98653 / (1-0.98653) = 73.24 # Random Distribution Ration = 512 / (2350-512) = 0.279. # # Typical Distribution Ratio EUCKR_TYPICAL_DISTRIBUTION_RATIO = 6.0 EUCKR_TABLE_SIZE = 2352 # Char to FreqOrder table , EUCKRCharToFreqOrder = ( \ 13, 130, 120,1396, 481,1719,1720, 328, 609, 212,1721, 707, 400, 299,1722, 87, 1397,1723, 104, 536,1117,1203,1724,1267, 685,1268, 508,1725,1726,1727,1728,1398, 1399,1729,1730,1731, 141, 621, 326,1057, 368,1732, 267, 488, 20,1733,1269,1734, 945,1400,1735, 47, 904,1270,1736,1737, 773, 248,1738, 409, 313, 786, 429,1739, 116, 987, 813,1401, 683, 75,1204, 145,1740,1741,1742,1743, 16, 847, 667, 622, 708,1744,1745,1746, 966, 787, 304, 129,1747, 60, 820, 123, 676,1748,1749,1750, 1751, 617,1752, 626,1753,1754,1755,1756, 653,1757,1758,1759,1760,1761,1762, 856, 344,1763,1764,1765,1766, 89, 401, 418, 806, 905, 848,1767,1768,1769, 946,1205, 709,1770,1118,1771, 241,1772,1773,1774,1271,1775, 569,1776, 999,1777,1778,1779, 1780, 337, 751,1058, 28, 628, 254,1781, 177, 906, 270, 349, 891,1079,1782, 19, 1783, 379,1784, 315,1785, 629, 754,1402, 559,1786, 636, 203,1206,1787, 710, 567, 1788, 935, 814,1789,1790,1207, 766, 528,1791,1792,1208,1793,1794,1795,1796,1797, 1403,1798,1799, 533,1059,1404,1405,1156,1406, 936, 884,1080,1800, 351,1801,1802, 1803,1804,1805, 801,1806,1807,1808,1119,1809,1157, 714, 474,1407,1810, 298, 899, 885,1811,1120, 802,1158,1812, 892,1813,1814,1408, 659,1815,1816,1121,1817,1818, 1819,1820,1821,1822, 319,1823, 594, 545,1824, 815, 937,1209,1825,1826, 573,1409, 1022,1827,1210,1828,1829,1830,1831,1832,1833, 556, 722, 807,1122,1060,1834, 697, 1835, 900, 557, 715,1836,1410, 540,1411, 752,1159, 294, 597,1211, 976, 803, 770, 1412,1837,1838, 39, 794,1413, 358,1839, 371, 925,1840, 453, 661, 788, 531, 723, 544,1023,1081, 869, 91,1841, 392, 430, 790, 602,1414, 677,1082, 457,1415,1416, 1842,1843, 475, 327,1024,1417, 795, 121,1844, 733, 403,1418,1845,1846,1847, 300, 119, 711,1212, 627,1848,1272, 207,1849,1850, 796,1213, 382,1851, 519,1852,1083, 893,1853,1854,1855, 367, 809, 487, 671,1856, 663,1857,1858, 956, 471, 306, 857, 1859,1860,1160,1084,1861,1862,1863,1864,1865,1061,1866,1867,1868,1869,1870,1871, 282, 96, 574,1872, 502,1085,1873,1214,1874, 907,1875,1876, 827, 977,1419,1420, 1421, 268,1877,1422,1878,1879,1880, 308,1881, 2, 537,1882,1883,1215,1884,1885, 127, 791,1886,1273,1423,1887, 34, 336, 404, 643,1888, 571, 654, 894, 840,1889, 0, 886,1274, 122, 575, 260, 908, 938,1890,1275, 410, 316,1891,1892, 100,1893, 1894,1123, 48,1161,1124,1025,1895, 633, 901,1276,1896,1897, 115, 816,1898, 317, 1899, 694,1900, 909, 734,1424, 572, 866,1425, 691, 85, 524,1010, 543, 394, 841, 1901,1902,1903,1026,1904,1905,1906,1907,1908,1909, 30, 451, 651, 988, 310,1910, 1911,1426, 810,1216, 93,1912,1913,1277,1217,1914, 858, 759, 45, 58, 181, 610, 269,1915,1916, 131,1062, 551, 443,1000, 821,1427, 957, 895,1086,1917,1918, 375, 1919, 359,1920, 687,1921, 822,1922, 293,1923,1924, 40, 662, 118, 692, 29, 939, 887, 640, 482, 174,1925, 69,1162, 728,1428, 910,1926,1278,1218,1279, 386, 870, 217, 854,1163, 823,1927,1928,1929,1930, 834,1931, 78,1932, 859,1933,1063,1934, 1935,1936,1937, 438,1164, 208, 595,1938,1939,1940,1941,1219,1125,1942, 280, 888, 1429,1430,1220,1431,1943,1944,1945,1946,1947,1280, 150, 510,1432,1948,1949,1950, 1951,1952,1953,1954,1011,1087,1955,1433,1043,1956, 881,1957, 614, 958,1064,1065, 1221,1958, 638,1001, 860, 967, 896,1434, 989, 492, 553,1281,1165,1959,1282,1002, 1283,1222,1960,1961,1962,1963, 36, 383, 228, 753, 247, 454,1964, 876, 678,1965, 1966,1284, 126, 464, 490, 835, 136, 672, 529, 940,1088,1435, 473,1967,1968, 467, 50, 390, 227, 587, 279, 378, 598, 792, 968, 240, 151, 160, 849, 882,1126,1285, 639,1044, 133, 140, 288, 360, 811, 563,1027, 561, 142, 523,1969,1970,1971, 7, 103, 296, 439, 407, 506, 634, 990,1972,1973,1974,1975, 645,1976,1977,1978,1979, 1980,1981, 236,1982,1436,1983,1984,1089, 192, 828, 618, 518,1166, 333,1127,1985, 818,1223,1986,1987,1988,1989,1990,1991,1992,1993, 342,1128,1286, 746, 842,1994, 1995, 560, 223,1287, 98, 8, 189, 650, 978,1288,1996,1437,1997, 17, 345, 250, 423, 277, 234, 512, 226, 97, 289, 42, 167,1998, 201,1999,2000, 843, 836, 824, 532, 338, 783,1090, 182, 576, 436,1438,1439, 527, 500,2001, 947, 889,2002,2003, 2004,2005, 262, 600, 314, 447,2006, 547,2007, 693, 738,1129,2008, 71,1440, 745, 619, 688,2009, 829,2010,2011, 147,2012, 33, 948,2013,2014, 74, 224,2015, 61, 191, 918, 399, 637,2016,1028,1130, 257, 902,2017,2018,2019,2020,2021,2022,2023, 2024,2025,2026, 837,2027,2028,2029,2030, 179, 874, 591, 52, 724, 246,2031,2032, 2033,2034,1167, 969,2035,1289, 630, 605, 911,1091,1168,2036,2037,2038,1441, 912, 2039, 623,2040,2041, 253,1169,1290,2042,1442, 146, 620, 611, 577, 433,2043,1224, 719,1170, 959, 440, 437, 534, 84, 388, 480,1131, 159, 220, 198, 679,2044,1012, 819,1066,1443, 113,1225, 194, 318,1003,1029,2045,2046,2047,2048,1067,2049,2050, 2051,2052,2053, 59, 913, 112,2054, 632,2055, 455, 144, 739,1291,2056, 273, 681, 499,2057, 448,2058,2059, 760,2060,2061, 970, 384, 169, 245,1132,2062,2063, 414, 1444,2064,2065, 41, 235,2066, 157, 252, 877, 568, 919, 789, 580,2067, 725,2068, 2069,1292,2070,2071,1445,2072,1446,2073,2074, 55, 588, 66,1447, 271,1092,2075, 1226,2076, 960,1013, 372,2077,2078,2079,2080,2081,1293,2082,2083,2084,2085, 850, 2086,2087,2088,2089,2090, 186,2091,1068, 180,2092,2093,2094, 109,1227, 522, 606, 2095, 867,1448,1093, 991,1171, 926, 353,1133,2096, 581,2097,2098,2099,1294,1449, 1450,2100, 596,1172,1014,1228,2101,1451,1295,1173,1229,2102,2103,1296,1134,1452, 949,1135,2104,2105,1094,1453,1454,1455,2106,1095,2107,2108,2109,2110,2111,2112, 2113,2114,2115,2116,2117, 804,2118,2119,1230,1231, 805,1456, 405,1136,2120,2121, 2122,2123,2124, 720, 701,1297, 992,1457, 927,1004,2125,2126,2127,2128,2129,2130, 22, 417,2131, 303,2132, 385,2133, 971, 520, 513,2134,1174, 73,1096, 231, 274, 962,1458, 673,2135,1459,2136, 152,1137,2137,2138,2139,2140,1005,1138,1460,1139, 2141,2142,2143,2144, 11, 374, 844,2145, 154,1232, 46,1461,2146, 838, 830, 721, 1233, 106,2147, 90, 428, 462, 578, 566,1175, 352,2148,2149, 538,1234, 124,1298, 2150,1462, 761, 565,2151, 686,2152, 649,2153, 72, 173,2154, 460, 415,2155,1463, 2156,1235, 305,2157,2158,2159,2160,2161,2162, 579,2163,2164,2165,2166,2167, 747, 2168,2169,2170,2171,1464, 669,2172,2173,2174,2175,2176,1465,2177, 23, 530, 285, 2178, 335, 729,2179, 397,2180,2181,2182,1030,2183,2184, 698,2185,2186, 325,2187, 2188, 369,2189, 799,1097,1015, 348,2190,1069, 680,2191, 851,1466,2192,2193, 10, 2194, 613, 424,2195, 979, 108, 449, 589, 27, 172, 81,1031, 80, 774, 281, 350, 1032, 525, 301, 582,1176,2196, 674,1045,2197,2198,1467, 730, 762,2199,2200,2201, 2202,1468,2203, 993,2204,2205, 266,1070, 963,1140,2206,2207,2208, 664,1098, 972, 2209,2210,2211,1177,1469,1470, 871,2212,2213,2214,2215,2216,1471,2217,2218,2219, 2220,2221,2222,2223,2224,2225,2226,2227,1472,1236,2228,2229,2230,2231,2232,2233, 2234,2235,1299,2236,2237, 200,2238, 477, 373,2239,2240, 731, 825, 777,2241,2242, 2243, 521, 486, 548,2244,2245,2246,1473,1300, 53, 549, 137, 875, 76, 158,2247, 1301,1474, 469, 396,1016, 278, 712,2248, 321, 442, 503, 767, 744, 941,1237,1178, 1475,2249, 82, 178,1141,1179, 973,2250,1302,2251, 297,2252,2253, 570,2254,2255, 2256, 18, 450, 206,2257, 290, 292,1142,2258, 511, 162, 99, 346, 164, 735,2259, 1476,1477, 4, 554, 343, 798,1099,2260,1100,2261, 43, 171,1303, 139, 215,2262, 2263, 717, 775,2264,1033, 322, 216,2265, 831,2266, 149,2267,1304,2268,2269, 702, 1238, 135, 845, 347, 309,2270, 484,2271, 878, 655, 238,1006,1478,2272, 67,2273, 295,2274,2275, 461,2276, 478, 942, 412,2277,1034,2278,2279,2280, 265,2281, 541, 2282,2283,2284,2285,2286, 70, 852,1071,2287,2288,2289,2290, 21, 56, 509, 117, 432,2291,2292, 331, 980, 552,1101, 148, 284, 105, 393,1180,1239, 755,2293, 187, 2294,1046,1479,2295, 340,2296, 63,1047, 230,2297,2298,1305, 763,1306, 101, 800, 808, 494,2299,2300,2301, 903,2302, 37,1072, 14, 5,2303, 79, 675,2304, 312, 2305,2306,2307,2308,2309,1480, 6,1307,2310,2311,2312, 1, 470, 35, 24, 229, 2313, 695, 210, 86, 778, 15, 784, 592, 779, 32, 77, 855, 964,2314, 259,2315, 501, 380,2316,2317, 83, 981, 153, 689,1308,1481,1482,1483,2318,2319, 716,1484, 2320,2321,2322,2323,2324,2325,1485,2326,2327, 128, 57, 68, 261,1048, 211, 170, 1240, 31,2328, 51, 435, 742,2329,2330,2331, 635,2332, 264, 456,2333,2334,2335, 425,2336,1486, 143, 507, 263, 943,2337, 363, 920,1487, 256,1488,1102, 243, 601, 1489,2338,2339,2340,2341,2342,2343,2344, 861,2345,2346,2347,2348,2349,2350, 395, 2351,1490,1491, 62, 535, 166, 225,2352,2353, 668, 419,1241, 138, 604, 928,2354, 1181,2355,1492,1493,2356,2357,2358,1143,2359, 696,2360, 387, 307,1309, 682, 476, 2361,2362, 332, 12, 222, 156,2363, 232,2364, 641, 276, 656, 517,1494,1495,1035, 416, 736,1496,2365,1017, 586,2366,2367,2368,1497,2369, 242,2370,2371,2372,1498, 2373, 965, 713,2374,2375,2376,2377, 740, 982,1499, 944,1500,1007,2378,2379,1310, 1501,2380,2381,2382, 785, 329,2383,2384,1502,2385,2386,2387, 932,2388,1503,2389, 2390,2391,2392,1242,2393,2394,2395,2396,2397, 994, 950,2398,2399,2400,2401,1504, 1311,2402,2403,2404,2405,1049, 749,2406,2407, 853, 718,1144,1312,2408,1182,1505, 2409,2410, 255, 516, 479, 564, 550, 214,1506,1507,1313, 413, 239, 444, 339,1145, 1036,1508,1509,1314,1037,1510,1315,2411,1511,2412,2413,2414, 176, 703, 497, 624, 593, 921, 302,2415, 341, 165,1103,1512,2416,1513,2417,2418,2419, 376,2420, 700, 2421,2422,2423, 258, 768,1316,2424,1183,2425, 995, 608,2426,2427,2428,2429, 221, 2430,2431,2432,2433,2434,2435,2436,2437, 195, 323, 726, 188, 897, 983,1317, 377, 644,1050, 879,2438, 452,2439,2440,2441,2442,2443,2444, 914,2445,2446,2447,2448, 915, 489,2449,1514,1184,2450,2451, 515, 64, 427, 495,2452, 583,2453, 483, 485, 1038, 562, 213,1515, 748, 666,2454,2455,2456,2457, 334,2458, 780, 996,1008, 705, 1243,2459,2460,2461,2462,2463, 114,2464, 493,1146, 366, 163,1516, 961,1104,2465, 291,2466,1318,1105,2467,1517, 365,2468, 355, 951,1244,2469,1319,2470, 631,2471, 2472, 218,1320, 364, 320, 756,1518,1519,1321,1520,1322,2473,2474,2475,2476, 997, 2477,2478,2479,2480, 665,1185,2481, 916,1521,2482,2483,2484, 584, 684,2485,2486, 797,2487,1051,1186,2488,2489,2490,1522,2491,2492, 370,2493,1039,1187, 65,2494, 434, 205, 463,1188,2495, 125, 812, 391, 402, 826, 699, 286, 398, 155, 781, 771, 585,2496, 590, 505,1073,2497, 599, 244, 219, 917,1018, 952, 646,1523,2498,1323, 2499,2500, 49, 984, 354, 741,2501, 625,2502,1324,2503,1019, 190, 357, 757, 491, 95, 782, 868,2504,2505,2506,2507,2508,2509, 134,1524,1074, 422,1525, 898,2510, 161,2511,2512,2513,2514, 769,2515,1526,2516,2517, 411,1325,2518, 472,1527,2519, 2520,2521,2522,2523,2524, 985,2525,2526,2527,2528,2529,2530, 764,2531,1245,2532, 2533, 25, 204, 311,2534, 496,2535,1052,2536,2537,2538,2539,2540,2541,2542, 199, 704, 504, 468, 758, 657,1528, 196, 44, 839,1246, 272, 750,2543, 765, 862,2544, 2545,1326,2546, 132, 615, 933,2547, 732,2548,2549,2550,1189,1529,2551, 283,1247, 1053, 607, 929,2552,2553,2554, 930, 183, 872, 616,1040,1147,2555,1148,1020, 441, 249,1075,2556,2557,2558, 466, 743,2559,2560,2561, 92, 514, 426, 420, 526,2562, 2563,2564,2565,2566,2567,2568, 185,2569,2570,2571,2572, 776,1530, 658,2573, 362, 2574, 361, 922,1076, 793,2575,2576,2577,2578,2579,2580,1531, 251,2581,2582,2583, 2584,1532, 54, 612, 237,1327,2585,2586, 275, 408, 647, 111,2587,1533,1106, 465, 3, 458, 9, 38,2588, 107, 110, 890, 209, 26, 737, 498,2589,1534,2590, 431, 202, 88,1535, 356, 287,1107, 660,1149,2591, 381,1536, 986,1150, 445,1248,1151, 974,2592,2593, 846,2594, 446, 953, 184,1249,1250, 727,2595, 923, 193, 883,2596, 2597,2598, 102, 324, 539, 817,2599, 421,1041,2600, 832,2601, 94, 175, 197, 406, 2602, 459,2603,2604,2605,2606,2607, 330, 555,2608,2609,2610, 706,1108, 389,2611, 2612,2613,2614, 233,2615, 833, 558, 931, 954,1251,2616,2617,1537, 546,2618,2619, 1009,2620,2621,2622,1538, 690,1328,2623, 955,2624,1539,2625,2626, 772,2627,2628, 2629,2630,2631, 924, 648, 863, 603,2632,2633, 934,1540, 864, 865,2634, 642,1042, 670,1190,2635,2636,2637,2638, 168,2639, 652, 873, 542,1054,1541,2640,2641,2642, # 512, 256 #Everything below is of no interest for detection purpose 2643,2644,2645,2646,2647,2648,2649,2650,2651,2652,2653,2654,2655,2656,2657,2658, 2659,2660,2661,2662,2663,2664,2665,2666,2667,2668,2669,2670,2671,2672,2673,2674, 2675,2676,2677,2678,2679,2680,2681,2682,2683,2684,2685,2686,2687,2688,2689,2690, 2691,2692,2693,2694,2695,2696,2697,2698,2699,1542, 880,2700,2701,2702,2703,2704, 2705,2706,2707,2708,2709,2710,2711,2712,2713,2714,2715,2716,2717,2718,2719,2720, 2721,2722,2723,2724,2725,1543,2726,2727,2728,2729,2730,2731,2732,1544,2733,2734, 2735,2736,2737,2738,2739,2740,2741,2742,2743,2744,2745,2746,2747,2748,2749,2750, 2751,2752,2753,2754,1545,2755,2756,2757,2758,2759,2760,2761,2762,2763,2764,2765, 2766,1546,2767,1547,2768,2769,2770,2771,2772,2773,2774,2775,2776,2777,2778,2779, 2780,2781,2782,2783,2784,2785,2786,1548,2787,2788,2789,1109,2790,2791,2792,2793, 2794,2795,2796,2797,2798,2799,2800,2801,2802,2803,2804,2805,2806,2807,2808,2809, 2810,2811,2812,1329,2813,2814,2815,2816,2817,2818,2819,2820,2821,2822,2823,2824, 2825,2826,2827,2828,2829,2830,2831,2832,2833,2834,2835,2836,2837,2838,2839,2840, 2841,2842,2843,2844,2845,2846,2847,2848,2849,2850,2851,2852,2853,2854,2855,2856, 1549,2857,2858,2859,2860,1550,2861,2862,1551,2863,2864,2865,2866,2867,2868,2869, 2870,2871,2872,2873,2874,1110,1330,2875,2876,2877,2878,2879,2880,2881,2882,2883, 2884,2885,2886,2887,2888,2889,2890,2891,2892,2893,2894,2895,2896,2897,2898,2899, 2900,2901,2902,2903,2904,2905,2906,2907,2908,2909,2910,2911,2912,2913,2914,2915, 2916,2917,2918,2919,2920,2921,2922,2923,2924,2925,2926,2927,2928,2929,2930,1331, 2931,2932,2933,2934,2935,2936,2937,2938,2939,2940,2941,2942,2943,1552,2944,2945, 2946,2947,2948,2949,2950,2951,2952,2953,2954,2955,2956,2957,2958,2959,2960,2961, 2962,2963,2964,1252,2965,2966,2967,2968,2969,2970,2971,2972,2973,2974,2975,2976, 2977,2978,2979,2980,2981,2982,2983,2984,2985,2986,2987,2988,2989,2990,2991,2992, 2993,2994,2995,2996,2997,2998,2999,3000,3001,3002,3003,3004,3005,3006,3007,3008, 3009,3010,3011,3012,1553,3013,3014,3015,3016,3017,1554,3018,1332,3019,3020,3021, 3022,3023,3024,3025,3026,3027,3028,3029,3030,3031,3032,3033,3034,3035,3036,3037, 3038,3039,3040,3041,3042,3043,3044,3045,3046,3047,3048,3049,3050,1555,3051,3052, 3053,1556,1557,3054,3055,3056,3057,3058,3059,3060,3061,3062,3063,3064,3065,3066, 3067,1558,3068,3069,3070,3071,3072,3073,3074,3075,3076,1559,3077,3078,3079,3080, 3081,3082,3083,1253,3084,3085,3086,3087,3088,3089,3090,3091,3092,3093,3094,3095, 3096,3097,3098,3099,3100,3101,3102,3103,3104,3105,3106,3107,3108,1152,3109,3110, 3111,3112,3113,1560,3114,3115,3116,3117,1111,3118,3119,3120,3121,3122,3123,3124, 3125,3126,3127,3128,3129,3130,3131,3132,3133,3134,3135,3136,3137,3138,3139,3140, 3141,3142,3143,3144,3145,3146,3147,3148,3149,3150,3151,3152,3153,3154,3155,3156, 3157,3158,3159,3160,3161,3162,3163,3164,3165,3166,3167,3168,3169,3170,3171,3172, 3173,3174,3175,3176,1333,3177,3178,3179,3180,3181,3182,3183,3184,3185,3186,3187, 3188,3189,1561,3190,3191,1334,3192,3193,3194,3195,3196,3197,3198,3199,3200,3201, 3202,3203,3204,3205,3206,3207,3208,3209,3210,3211,3212,3213,3214,3215,3216,3217, 3218,3219,3220,3221,3222,3223,3224,3225,3226,3227,3228,3229,3230,3231,3232,3233, 3234,1562,3235,3236,3237,3238,3239,3240,3241,3242,3243,3244,3245,3246,3247,3248, 3249,3250,3251,3252,3253,3254,3255,3256,3257,3258,3259,3260,3261,3262,3263,3264, 3265,3266,3267,3268,3269,3270,3271,3272,3273,3274,3275,3276,3277,1563,3278,3279, 3280,3281,3282,3283,3284,3285,3286,3287,3288,3289,3290,3291,3292,3293,3294,3295, 3296,3297,3298,3299,3300,3301,3302,3303,3304,3305,3306,3307,3308,3309,3310,3311, 3312,3313,3314,3315,3316,3317,3318,3319,3320,3321,3322,3323,3324,3325,3326,3327, 3328,3329,3330,3331,3332,3333,3334,3335,3336,3337,3338,3339,3340,3341,3342,3343, 3344,3345,3346,3347,3348,3349,3350,3351,3352,3353,3354,3355,3356,3357,3358,3359, 3360,3361,3362,3363,3364,1335,3365,3366,3367,3368,3369,3370,3371,3372,3373,3374, 3375,3376,3377,3378,3379,3380,3381,3382,3383,3384,3385,3386,3387,1336,3388,3389, 3390,3391,3392,3393,3394,3395,3396,3397,3398,3399,3400,3401,3402,3403,3404,3405, 3406,3407,3408,3409,3410,3411,3412,3413,3414,1337,3415,3416,3417,3418,3419,1338, 3420,3421,3422,1564,1565,3423,3424,3425,3426,3427,3428,3429,3430,3431,1254,3432, 3433,3434,1339,3435,3436,3437,3438,3439,1566,3440,3441,3442,3443,3444,3445,3446, 3447,3448,3449,3450,3451,3452,3453,3454,1255,3455,3456,3457,3458,3459,1567,1191, 3460,1568,1569,3461,3462,3463,1570,3464,3465,3466,3467,3468,1571,3469,3470,3471, 3472,3473,1572,3474,3475,3476,3477,3478,3479,3480,3481,3482,3483,3484,3485,3486, 1340,3487,3488,3489,3490,3491,3492,1021,3493,3494,3495,3496,3497,3498,1573,3499, 1341,3500,3501,3502,3503,3504,3505,3506,3507,3508,3509,3510,3511,1342,3512,3513, 3514,3515,3516,1574,1343,3517,3518,3519,1575,3520,1576,3521,3522,3523,3524,3525, 3526,3527,3528,3529,3530,3531,3532,3533,3534,3535,3536,3537,3538,3539,3540,3541, 3542,3543,3544,3545,3546,3547,3548,3549,3550,3551,3552,3553,3554,3555,3556,3557, 3558,3559,3560,3561,3562,3563,3564,3565,3566,3567,3568,3569,3570,3571,3572,3573, 3574,3575,3576,3577,3578,3579,3580,1577,3581,3582,1578,3583,3584,3585,3586,3587, 3588,3589,3590,3591,3592,3593,3594,3595,3596,3597,3598,3599,3600,3601,3602,3603, 3604,1579,3605,3606,3607,3608,3609,3610,3611,3612,3613,3614,3615,3616,3617,3618, 3619,3620,3621,3622,3623,3624,3625,3626,3627,3628,3629,1580,3630,3631,1581,3632, 3633,3634,3635,3636,3637,3638,3639,3640,3641,3642,3643,3644,3645,3646,3647,3648, 3649,3650,3651,3652,3653,3654,3655,3656,1582,3657,3658,3659,3660,3661,3662,3663, 3664,3665,3666,3667,3668,3669,3670,3671,3672,3673,3674,3675,3676,3677,3678,3679, 3680,3681,3682,3683,3684,3685,3686,3687,3688,3689,3690,3691,3692,3693,3694,3695, 3696,3697,3698,3699,3700,1192,3701,3702,3703,3704,1256,3705,3706,3707,3708,1583, 1257,3709,3710,3711,3712,3713,3714,3715,3716,1584,3717,3718,3719,3720,3721,3722, 3723,3724,3725,3726,3727,3728,3729,3730,3731,3732,3733,3734,3735,3736,3737,3738, 3739,3740,3741,3742,3743,3744,3745,1344,3746,3747,3748,3749,3750,3751,3752,3753, 3754,3755,3756,1585,3757,3758,3759,3760,3761,3762,3763,3764,3765,3766,1586,3767, 3768,3769,3770,3771,3772,3773,3774,3775,3776,3777,3778,1345,3779,3780,3781,3782, 3783,3784,3785,3786,3787,3788,3789,3790,3791,3792,3793,3794,3795,1346,1587,3796, 3797,1588,3798,3799,3800,3801,3802,3803,3804,3805,3806,1347,3807,3808,3809,3810, 3811,1589,3812,3813,3814,3815,3816,3817,3818,3819,3820,3821,1590,3822,3823,1591, 1348,3824,3825,3826,3827,3828,3829,3830,1592,3831,3832,1593,3833,3834,3835,3836, 3837,3838,3839,3840,3841,3842,3843,3844,1349,3845,3846,3847,3848,3849,3850,3851, 3852,3853,3854,3855,3856,3857,3858,1594,3859,3860,3861,3862,3863,3864,3865,3866, 3867,3868,3869,1595,3870,3871,3872,3873,1596,3874,3875,3876,3877,3878,3879,3880, 3881,3882,3883,3884,3885,3886,1597,3887,3888,3889,3890,3891,3892,3893,3894,3895, 1598,3896,3897,3898,1599,1600,3899,1350,3900,1351,3901,3902,1352,3903,3904,3905, 3906,3907,3908,3909,3910,3911,3912,3913,3914,3915,3916,3917,3918,3919,3920,3921, 3922,3923,3924,1258,3925,3926,3927,3928,3929,3930,3931,1193,3932,1601,3933,3934, 3935,3936,3937,3938,3939,3940,3941,3942,3943,1602,3944,3945,3946,3947,3948,1603, 3949,3950,3951,3952,3953,3954,3955,3956,3957,3958,3959,3960,3961,3962,3963,3964, 3965,1604,3966,3967,3968,3969,3970,3971,3972,3973,3974,3975,3976,3977,1353,3978, 3979,3980,3981,3982,3983,3984,3985,3986,3987,3988,3989,3990,3991,1354,3992,3993, 3994,3995,3996,3997,3998,3999,4000,4001,4002,4003,4004,4005,4006,4007,4008,4009, 4010,4011,4012,4013,4014,4015,4016,4017,4018,4019,4020,4021,4022,4023,1355,4024, 4025,4026,4027,4028,4029,4030,4031,4032,4033,4034,4035,4036,4037,4038,4039,4040, 1605,4041,4042,4043,4044,4045,4046,4047,4048,4049,4050,4051,4052,4053,4054,4055, 4056,4057,4058,4059,4060,1606,4061,4062,4063,4064,1607,4065,4066,4067,4068,4069, 4070,4071,4072,4073,4074,4075,4076,1194,4077,4078,1608,4079,4080,4081,4082,4083, 4084,4085,4086,4087,1609,4088,4089,4090,4091,4092,4093,4094,4095,4096,4097,4098, 4099,4100,4101,4102,4103,4104,4105,4106,4107,4108,1259,4109,4110,4111,4112,4113, 4114,4115,4116,4117,4118,4119,4120,4121,4122,4123,4124,1195,4125,4126,4127,1610, 4128,4129,4130,4131,4132,4133,4134,4135,4136,4137,1356,4138,4139,4140,4141,4142, 4143,4144,1611,4145,4146,4147,4148,4149,4150,4151,4152,4153,4154,4155,4156,4157, 4158,4159,4160,4161,4162,4163,4164,4165,4166,4167,4168,4169,4170,4171,4172,4173, 4174,4175,4176,4177,4178,4179,4180,4181,4182,4183,4184,4185,4186,4187,4188,4189, 4190,4191,4192,4193,4194,4195,4196,4197,4198,4199,4200,4201,4202,4203,4204,4205, 4206,4207,4208,4209,4210,4211,4212,4213,4214,4215,4216,4217,4218,4219,1612,4220, 4221,4222,4223,4224,4225,4226,4227,1357,4228,1613,4229,4230,4231,4232,4233,4234, 4235,4236,4237,4238,4239,4240,4241,4242,4243,1614,4244,4245,4246,4247,4248,4249, 4250,4251,4252,4253,4254,4255,4256,4257,4258,4259,4260,4261,4262,4263,4264,4265, 4266,4267,4268,4269,4270,1196,1358,4271,4272,4273,4274,4275,4276,4277,4278,4279, 4280,4281,4282,4283,4284,4285,4286,4287,1615,4288,4289,4290,4291,4292,4293,4294, 4295,4296,4297,4298,4299,4300,4301,4302,4303,4304,4305,4306,4307,4308,4309,4310, 4311,4312,4313,4314,4315,4316,4317,4318,4319,4320,4321,4322,4323,4324,4325,4326, 4327,4328,4329,4330,4331,4332,4333,4334,1616,4335,4336,4337,4338,4339,4340,4341, 4342,4343,4344,4345,4346,4347,4348,4349,4350,4351,4352,4353,4354,4355,4356,4357, 4358,4359,4360,1617,4361,4362,4363,4364,4365,1618,4366,4367,4368,4369,4370,4371, 4372,4373,4374,4375,4376,4377,4378,4379,4380,4381,4382,4383,4384,4385,4386,4387, 4388,4389,4390,4391,4392,4393,4394,4395,4396,4397,4398,4399,4400,4401,4402,4403, 4404,4405,4406,4407,4408,4409,4410,4411,4412,4413,4414,4415,4416,1619,4417,4418, 4419,4420,4421,4422,4423,4424,4425,1112,4426,4427,4428,4429,4430,1620,4431,4432, 4433,4434,4435,4436,4437,4438,4439,4440,4441,4442,1260,1261,4443,4444,4445,4446, 4447,4448,4449,4450,4451,4452,4453,4454,4455,1359,4456,4457,4458,4459,4460,4461, 4462,4463,4464,4465,1621,4466,4467,4468,4469,4470,4471,4472,4473,4474,4475,4476, 4477,4478,4479,4480,4481,4482,4483,4484,4485,4486,4487,4488,4489,1055,4490,4491, 4492,4493,4494,4495,4496,4497,4498,4499,4500,4501,4502,4503,4504,4505,4506,4507, 4508,4509,4510,4511,4512,4513,4514,4515,4516,4517,4518,1622,4519,4520,4521,1623, 4522,4523,4524,4525,4526,4527,4528,4529,4530,4531,4532,4533,4534,4535,1360,4536, 4537,4538,4539,4540,4541,4542,4543, 975,4544,4545,4546,4547,4548,4549,4550,4551, 4552,4553,4554,4555,4556,4557,4558,4559,4560,4561,4562,4563,4564,4565,4566,4567, 4568,4569,4570,4571,1624,4572,4573,4574,4575,4576,1625,4577,4578,4579,4580,4581, 4582,4583,4584,1626,4585,4586,4587,4588,4589,4590,4591,4592,4593,4594,4595,1627, 4596,4597,4598,4599,4600,4601,4602,4603,4604,4605,4606,4607,4608,4609,4610,4611, 4612,4613,4614,4615,1628,4616,4617,4618,4619,4620,4621,4622,4623,4624,4625,4626, 4627,4628,4629,4630,4631,4632,4633,4634,4635,4636,4637,4638,4639,4640,4641,4642, 4643,4644,4645,4646,4647,4648,4649,1361,4650,4651,4652,4653,4654,4655,4656,4657, 4658,4659,4660,4661,1362,4662,4663,4664,4665,4666,4667,4668,4669,4670,4671,4672, 4673,4674,4675,4676,4677,4678,4679,4680,4681,4682,1629,4683,4684,4685,4686,4687, 1630,4688,4689,4690,4691,1153,4692,4693,4694,1113,4695,4696,4697,4698,4699,4700, 4701,4702,4703,4704,4705,4706,4707,4708,4709,4710,4711,1197,4712,4713,4714,4715, 4716,4717,4718,4719,4720,4721,4722,4723,4724,4725,4726,4727,4728,4729,4730,4731, 4732,4733,4734,4735,1631,4736,1632,4737,4738,4739,4740,4741,4742,4743,4744,1633, 4745,4746,4747,4748,4749,1262,4750,4751,4752,4753,4754,1363,4755,4756,4757,4758, 4759,4760,4761,4762,4763,4764,4765,4766,4767,4768,1634,4769,4770,4771,4772,4773, 4774,4775,4776,4777,4778,1635,4779,4780,4781,4782,4783,4784,4785,4786,4787,4788, 4789,1636,4790,4791,4792,4793,4794,4795,4796,4797,4798,4799,4800,4801,4802,4803, 4804,4805,4806,1637,4807,4808,4809,1638,4810,4811,4812,4813,4814,4815,4816,4817, 4818,1639,4819,4820,4821,4822,4823,4824,4825,4826,4827,4828,4829,4830,4831,4832, 4833,1077,4834,4835,4836,4837,4838,4839,4840,4841,4842,4843,4844,4845,4846,4847, 4848,4849,4850,4851,4852,4853,4854,4855,4856,4857,4858,4859,4860,4861,4862,4863, 4864,4865,4866,4867,4868,4869,4870,4871,4872,4873,4874,4875,4876,4877,4878,4879, 4880,4881,4882,4883,1640,4884,4885,1641,4886,4887,4888,4889,4890,4891,4892,4893, 4894,4895,4896,4897,4898,4899,4900,4901,4902,4903,4904,4905,4906,4907,4908,4909, 4910,4911,1642,4912,4913,4914,1364,4915,4916,4917,4918,4919,4920,4921,4922,4923, 4924,4925,4926,4927,4928,4929,4930,4931,1643,4932,4933,4934,4935,4936,4937,4938, 4939,4940,4941,4942,4943,4944,4945,4946,4947,4948,4949,4950,4951,4952,4953,4954, 4955,4956,4957,4958,4959,4960,4961,4962,4963,4964,4965,4966,4967,4968,4969,4970, 4971,4972,4973,4974,4975,4976,4977,4978,4979,4980,1644,4981,4982,4983,4984,1645, 4985,4986,1646,4987,4988,4989,4990,4991,4992,4993,4994,4995,4996,4997,4998,4999, 5000,5001,5002,5003,5004,5005,1647,5006,1648,5007,5008,5009,5010,5011,5012,1078, 5013,5014,5015,5016,5017,5018,5019,5020,5021,5022,5023,5024,5025,5026,5027,5028, 1365,5029,5030,5031,5032,5033,5034,5035,5036,5037,5038,5039,1649,5040,5041,5042, 5043,5044,5045,1366,5046,5047,5048,5049,5050,5051,5052,5053,5054,5055,1650,5056, 5057,5058,5059,5060,5061,5062,5063,5064,5065,5066,5067,5068,5069,5070,5071,5072, 5073,5074,5075,5076,5077,1651,5078,5079,5080,5081,5082,5083,5084,5085,5086,5087, 5088,5089,5090,5091,5092,5093,5094,5095,5096,5097,5098,5099,5100,5101,5102,5103, 5104,5105,5106,5107,5108,5109,5110,1652,5111,5112,5113,5114,5115,5116,5117,5118, 1367,5119,5120,5121,5122,5123,5124,5125,5126,5127,5128,5129,1653,5130,5131,5132, 5133,5134,5135,5136,5137,5138,5139,5140,5141,5142,5143,5144,5145,5146,5147,5148, 5149,1368,5150,1654,5151,1369,5152,5153,5154,5155,5156,5157,5158,5159,5160,5161, 5162,5163,5164,5165,5166,5167,5168,5169,5170,5171,5172,5173,5174,5175,5176,5177, 5178,1370,5179,5180,5181,5182,5183,5184,5185,5186,5187,5188,5189,5190,5191,5192, 5193,5194,5195,5196,5197,5198,1655,5199,5200,5201,5202,1656,5203,5204,5205,5206, 1371,5207,1372,5208,5209,5210,5211,1373,5212,5213,1374,5214,5215,5216,5217,5218, 5219,5220,5221,5222,5223,5224,5225,5226,5227,5228,5229,5230,5231,5232,5233,5234, 5235,5236,5237,5238,5239,5240,5241,5242,5243,5244,5245,5246,5247,1657,5248,5249, 5250,5251,1658,1263,5252,5253,5254,5255,5256,1375,5257,5258,5259,5260,5261,5262, 5263,5264,5265,5266,5267,5268,5269,5270,5271,5272,5273,5274,5275,5276,5277,5278, 5279,5280,5281,5282,5283,1659,5284,5285,5286,5287,5288,5289,5290,5291,5292,5293, 5294,5295,5296,5297,5298,5299,5300,1660,5301,5302,5303,5304,5305,5306,5307,5308, 5309,5310,5311,5312,5313,5314,5315,5316,5317,5318,5319,5320,5321,1376,5322,5323, 5324,5325,5326,5327,5328,5329,5330,5331,5332,5333,1198,5334,5335,5336,5337,5338, 5339,5340,5341,5342,5343,1661,5344,5345,5346,5347,5348,5349,5350,5351,5352,5353, 5354,5355,5356,5357,5358,5359,5360,5361,5362,5363,5364,5365,5366,5367,5368,5369, 5370,5371,5372,5373,5374,5375,5376,5377,5378,5379,5380,5381,5382,5383,5384,5385, 5386,5387,5388,5389,5390,5391,5392,5393,5394,5395,5396,5397,5398,1264,5399,5400, 5401,5402,5403,5404,5405,5406,5407,5408,5409,5410,5411,5412,1662,5413,5414,5415, 5416,1663,5417,5418,5419,5420,5421,5422,5423,5424,5425,5426,5427,5428,5429,5430, 5431,5432,5433,5434,5435,5436,5437,5438,1664,5439,5440,5441,5442,5443,5444,5445, 5446,5447,5448,5449,5450,5451,5452,5453,5454,5455,5456,5457,5458,5459,5460,5461, 5462,5463,5464,5465,5466,5467,5468,5469,5470,5471,5472,5473,5474,5475,5476,5477, 5478,1154,5479,5480,5481,5482,5483,5484,5485,1665,5486,5487,5488,5489,5490,5491, 5492,5493,5494,5495,5496,5497,5498,5499,5500,5501,5502,5503,5504,5505,5506,5507, 5508,5509,5510,5511,5512,5513,5514,5515,5516,5517,5518,5519,5520,5521,5522,5523, 5524,5525,5526,5527,5528,5529,5530,5531,5532,5533,5534,5535,5536,5537,5538,5539, 5540,5541,5542,5543,5544,5545,5546,5547,5548,1377,5549,5550,5551,5552,5553,5554, 5555,5556,5557,5558,5559,5560,5561,5562,5563,5564,5565,5566,5567,5568,5569,5570, 1114,5571,5572,5573,5574,5575,5576,5577,5578,5579,5580,5581,5582,5583,5584,5585, 5586,5587,5588,5589,5590,5591,5592,1378,5593,5594,5595,5596,5597,5598,5599,5600, 5601,5602,5603,5604,5605,5606,5607,5608,5609,5610,5611,5612,5613,5614,1379,5615, 5616,5617,5618,5619,5620,5621,5622,5623,5624,5625,5626,5627,5628,5629,5630,5631, 5632,5633,5634,1380,5635,5636,5637,5638,5639,5640,5641,5642,5643,5644,5645,5646, 5647,5648,5649,1381,1056,5650,5651,5652,5653,5654,5655,5656,5657,5658,5659,5660, 1666,5661,5662,5663,5664,5665,5666,5667,5668,1667,5669,1668,5670,5671,5672,5673, 5674,5675,5676,5677,5678,1155,5679,5680,5681,5682,5683,5684,5685,5686,5687,5688, 5689,5690,5691,5692,5693,5694,5695,5696,5697,5698,1669,5699,5700,5701,5702,5703, 5704,5705,1670,5706,5707,5708,5709,5710,1671,5711,5712,5713,5714,1382,5715,5716, 5717,5718,5719,5720,5721,5722,5723,5724,5725,1672,5726,5727,1673,1674,5728,5729, 5730,5731,5732,5733,5734,5735,5736,1675,5737,5738,5739,5740,5741,5742,5743,5744, 1676,5745,5746,5747,5748,5749,5750,5751,1383,5752,5753,5754,5755,5756,5757,5758, 5759,5760,5761,5762,5763,5764,5765,5766,5767,5768,1677,5769,5770,5771,5772,5773, 1678,5774,5775,5776, 998,5777,5778,5779,5780,5781,5782,5783,5784,5785,1384,5786, 5787,5788,5789,5790,5791,5792,5793,5794,5795,5796,5797,5798,5799,5800,1679,5801, 5802,5803,1115,1116,5804,5805,5806,5807,5808,5809,5810,5811,5812,5813,5814,5815, 5816,5817,5818,5819,5820,5821,5822,5823,5824,5825,5826,5827,5828,5829,5830,5831, 5832,5833,5834,5835,5836,5837,5838,5839,5840,5841,5842,5843,5844,5845,5846,5847, 5848,5849,5850,5851,5852,5853,5854,5855,1680,5856,5857,5858,5859,5860,5861,5862, 5863,5864,1681,5865,5866,5867,1682,5868,5869,5870,5871,5872,5873,5874,5875,5876, 5877,5878,5879,1683,5880,1684,5881,5882,5883,5884,1685,5885,5886,5887,5888,5889, 5890,5891,5892,5893,5894,5895,5896,5897,5898,5899,5900,5901,5902,5903,5904,5905, 5906,5907,1686,5908,5909,5910,5911,5912,5913,5914,5915,5916,5917,5918,5919,5920, 5921,5922,5923,5924,5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,1687, 5936,5937,5938,5939,5940,5941,5942,5943,5944,5945,5946,5947,5948,5949,5950,5951, 5952,1688,1689,5953,1199,5954,5955,5956,5957,5958,5959,5960,5961,1690,5962,5963, 5964,5965,5966,5967,5968,5969,5970,5971,5972,5973,5974,5975,5976,5977,5978,5979, 5980,5981,1385,5982,1386,5983,5984,5985,5986,5987,5988,5989,5990,5991,5992,5993, 5994,5995,5996,5997,5998,5999,6000,6001,6002,6003,6004,6005,6006,6007,6008,6009, 6010,6011,6012,6013,6014,6015,6016,6017,6018,6019,6020,6021,6022,6023,6024,6025, 6026,6027,1265,6028,6029,1691,6030,6031,6032,6033,6034,6035,6036,6037,6038,6039, 6040,6041,6042,6043,6044,6045,6046,6047,6048,6049,6050,6051,6052,6053,6054,6055, 6056,6057,6058,6059,6060,6061,6062,6063,6064,6065,6066,6067,6068,6069,6070,6071, 6072,6073,6074,6075,6076,6077,6078,6079,6080,6081,6082,6083,6084,1692,6085,6086, 6087,6088,6089,6090,6091,6092,6093,6094,6095,6096,6097,6098,6099,6100,6101,6102, 6103,6104,6105,6106,6107,6108,6109,6110,6111,6112,6113,6114,6115,6116,6117,6118, 6119,6120,6121,6122,6123,6124,6125,6126,6127,6128,6129,6130,6131,1693,6132,6133, 6134,6135,6136,1694,6137,6138,6139,6140,6141,1695,6142,6143,6144,6145,6146,6147, 6148,6149,6150,6151,6152,6153,6154,6155,6156,6157,6158,6159,6160,6161,6162,6163, 6164,6165,6166,6167,6168,6169,6170,6171,6172,6173,6174,6175,6176,6177,6178,6179, 6180,6181,6182,6183,6184,6185,1696,6186,6187,6188,6189,6190,6191,6192,6193,6194, 6195,6196,6197,6198,6199,6200,6201,6202,6203,6204,6205,6206,6207,6208,6209,6210, 6211,6212,6213,6214,6215,6216,6217,6218,6219,1697,6220,6221,6222,6223,6224,6225, 6226,6227,6228,6229,6230,6231,6232,6233,6234,6235,6236,6237,6238,6239,6240,6241, 6242,6243,6244,6245,6246,6247,6248,6249,6250,6251,6252,6253,1698,6254,6255,6256, 6257,6258,6259,6260,6261,6262,6263,1200,6264,6265,6266,6267,6268,6269,6270,6271, #1024 6272,6273,6274,6275,6276,6277,6278,6279,6280,6281,6282,6283,6284,6285,6286,6287, 6288,6289,6290,6291,6292,6293,6294,6295,6296,6297,6298,6299,6300,6301,6302,1699, 6303,6304,1700,6305,6306,6307,6308,6309,6310,6311,6312,6313,6314,6315,6316,6317, 6318,6319,6320,6321,6322,6323,6324,6325,6326,6327,6328,6329,6330,6331,6332,6333, 6334,6335,6336,6337,6338,6339,1701,6340,6341,6342,6343,6344,1387,6345,6346,6347, 6348,6349,6350,6351,6352,6353,6354,6355,6356,6357,6358,6359,6360,6361,6362,6363, 6364,6365,6366,6367,6368,6369,6370,6371,6372,6373,6374,6375,6376,6377,6378,6379, 6380,6381,6382,6383,6384,6385,6386,6387,6388,6389,6390,6391,6392,6393,6394,6395, 6396,6397,6398,6399,6400,6401,6402,6403,6404,6405,6406,6407,6408,6409,6410,6411, 6412,6413,1702,6414,6415,6416,6417,6418,6419,6420,6421,6422,1703,6423,6424,6425, 6426,6427,6428,6429,6430,6431,6432,6433,6434,6435,6436,6437,6438,1704,6439,6440, 6441,6442,6443,6444,6445,6446,6447,6448,6449,6450,6451,6452,6453,6454,6455,6456, 6457,6458,6459,6460,6461,6462,6463,6464,6465,6466,6467,6468,6469,6470,6471,6472, 6473,6474,6475,6476,6477,6478,6479,6480,6481,6482,6483,6484,6485,6486,6487,6488, 6489,6490,6491,6492,6493,6494,6495,6496,6497,6498,6499,6500,6501,6502,6503,1266, 6504,6505,6506,6507,6508,6509,6510,6511,6512,6513,6514,6515,6516,6517,6518,6519, 6520,6521,6522,6523,6524,6525,6526,6527,6528,6529,6530,6531,6532,6533,6534,6535, 6536,6537,6538,6539,6540,6541,6542,6543,6544,6545,6546,6547,6548,6549,6550,6551, 1705,1706,6552,6553,6554,6555,6556,6557,6558,6559,6560,6561,6562,6563,6564,6565, 6566,6567,6568,6569,6570,6571,6572,6573,6574,6575,6576,6577,6578,6579,6580,6581, 6582,6583,6584,6585,6586,6587,6588,6589,6590,6591,6592,6593,6594,6595,6596,6597, 6598,6599,6600,6601,6602,6603,6604,6605,6606,6607,6608,6609,6610,6611,6612,6613, 6614,6615,6616,6617,6618,6619,6620,6621,6622,6623,6624,6625,6626,6627,6628,6629, 6630,6631,6632,6633,6634,6635,6636,6637,1388,6638,6639,6640,6641,6642,6643,6644, 1707,6645,6646,6647,6648,6649,6650,6651,6652,6653,6654,6655,6656,6657,6658,6659, 6660,6661,6662,6663,1708,6664,6665,6666,6667,6668,6669,6670,6671,6672,6673,6674, 1201,6675,6676,6677,6678,6679,6680,6681,6682,6683,6684,6685,6686,6687,6688,6689, 6690,6691,6692,6693,6694,6695,6696,6697,6698,6699,6700,6701,6702,6703,6704,6705, 6706,6707,6708,6709,6710,6711,6712,6713,6714,6715,6716,6717,6718,6719,6720,6721, 6722,6723,6724,6725,1389,6726,6727,6728,6729,6730,6731,6732,6733,6734,6735,6736, 1390,1709,6737,6738,6739,6740,6741,6742,1710,6743,6744,6745,6746,1391,6747,6748, 6749,6750,6751,6752,6753,6754,6755,6756,6757,1392,6758,6759,6760,6761,6762,6763, 6764,6765,6766,6767,6768,6769,6770,6771,6772,6773,6774,6775,6776,6777,6778,6779, 6780,1202,6781,6782,6783,6784,6785,6786,6787,6788,6789,6790,6791,6792,6793,6794, 6795,6796,6797,6798,6799,6800,6801,6802,6803,6804,6805,6806,6807,6808,6809,1711, 6810,6811,6812,6813,6814,6815,6816,6817,6818,6819,6820,6821,6822,6823,6824,6825, 6826,6827,6828,6829,6830,6831,6832,6833,6834,6835,6836,1393,6837,6838,6839,6840, 6841,6842,6843,6844,6845,6846,6847,6848,6849,6850,6851,6852,6853,6854,6855,6856, 6857,6858,6859,6860,6861,6862,6863,6864,6865,6866,6867,6868,6869,6870,6871,6872, 6873,6874,6875,6876,6877,6878,6879,6880,6881,6882,6883,6884,6885,6886,6887,6888, 6889,6890,6891,6892,6893,6894,6895,6896,6897,6898,6899,6900,6901,6902,1712,6903, 6904,6905,6906,6907,6908,6909,6910,1713,6911,6912,6913,6914,6915,6916,6917,6918, 6919,6920,6921,6922,6923,6924,6925,6926,6927,6928,6929,6930,6931,6932,6933,6934, 6935,6936,6937,6938,6939,6940,6941,6942,6943,6944,6945,6946,6947,6948,6949,6950, 6951,6952,6953,6954,6955,6956,6957,6958,6959,6960,6961,6962,6963,6964,6965,6966, 6967,6968,6969,6970,6971,6972,6973,6974,1714,6975,6976,6977,6978,6979,6980,6981, 6982,6983,6984,6985,6986,6987,6988,1394,6989,6990,6991,6992,6993,6994,6995,6996, 6997,6998,6999,7000,1715,7001,7002,7003,7004,7005,7006,7007,7008,7009,7010,7011, 7012,7013,7014,7015,7016,7017,7018,7019,7020,7021,7022,7023,7024,7025,7026,7027, 7028,1716,7029,7030,7031,7032,7033,7034,7035,7036,7037,7038,7039,7040,7041,7042, 7043,7044,7045,7046,7047,7048,7049,7050,7051,7052,7053,7054,7055,7056,7057,7058, 7059,7060,7061,7062,7063,7064,7065,7066,7067,7068,7069,7070,7071,7072,7073,7074, 7075,7076,7077,7078,7079,7080,7081,7082,7083,7084,7085,7086,7087,7088,7089,7090, 7091,7092,7093,7094,7095,7096,7097,7098,7099,7100,7101,7102,7103,7104,7105,7106, 7107,7108,7109,7110,7111,7112,7113,7114,7115,7116,7117,7118,7119,7120,7121,7122, 7123,7124,7125,7126,7127,7128,7129,7130,7131,7132,7133,7134,7135,7136,7137,7138, 7139,7140,7141,7142,7143,7144,7145,7146,7147,7148,7149,7150,7151,7152,7153,7154, 7155,7156,7157,7158,7159,7160,7161,7162,7163,7164,7165,7166,7167,7168,7169,7170, 7171,7172,7173,7174,7175,7176,7177,7178,7179,7180,7181,7182,7183,7184,7185,7186, 7187,7188,7189,7190,7191,7192,7193,7194,7195,7196,7197,7198,7199,7200,7201,7202, 7203,7204,7205,7206,7207,1395,7208,7209,7210,7211,7212,7213,1717,7214,7215,7216, 7217,7218,7219,7220,7221,7222,7223,7224,7225,7226,7227,7228,7229,7230,7231,7232, 7233,7234,7235,7236,7237,7238,7239,7240,7241,7242,7243,7244,7245,7246,7247,7248, 7249,7250,7251,7252,7253,7254,7255,7256,7257,7258,7259,7260,7261,7262,7263,7264, 7265,7266,7267,7268,7269,7270,7271,7272,7273,7274,7275,7276,7277,7278,7279,7280, 7281,7282,7283,7284,7285,7286,7287,7288,7289,7290,7291,7292,7293,7294,7295,7296, 7297,7298,7299,7300,7301,7302,7303,7304,7305,7306,7307,7308,7309,7310,7311,7312, 7313,1718,7314,7315,7316,7317,7318,7319,7320,7321,7322,7323,7324,7325,7326,7327, 7328,7329,7330,7331,7332,7333,7334,7335,7336,7337,7338,7339,7340,7341,7342,7343, 7344,7345,7346,7347,7348,7349,7350,7351,7352,7353,7354,7355,7356,7357,7358,7359, 7360,7361,7362,7363,7364,7365,7366,7367,7368,7369,7370,7371,7372,7373,7374,7375, 7376,7377,7378,7379,7380,7381,7382,7383,7384,7385,7386,7387,7388,7389,7390,7391, 7392,7393,7394,7395,7396,7397,7398,7399,7400,7401,7402,7403,7404,7405,7406,7407, 7408,7409,7410,7411,7412,7413,7414,7415,7416,7417,7418,7419,7420,7421,7422,7423, 7424,7425,7426,7427,7428,7429,7430,7431,7432,7433,7434,7435,7436,7437,7438,7439, 7440,7441,7442,7443,7444,7445,7446,7447,7448,7449,7450,7451,7452,7453,7454,7455, 7456,7457,7458,7459,7460,7461,7462,7463,7464,7465,7466,7467,7468,7469,7470,7471, 7472,7473,7474,7475,7476,7477,7478,7479,7480,7481,7482,7483,7484,7485,7486,7487, 7488,7489,7490,7491,7492,7493,7494,7495,7496,7497,7498,7499,7500,7501,7502,7503, 7504,7505,7506,7507,7508,7509,7510,7511,7512,7513,7514,7515,7516,7517,7518,7519, 7520,7521,7522,7523,7524,7525,7526,7527,7528,7529,7530,7531,7532,7533,7534,7535, 7536,7537,7538,7539,7540,7541,7542,7543,7544,7545,7546,7547,7548,7549,7550,7551, 7552,7553,7554,7555,7556,7557,7558,7559,7560,7561,7562,7563,7564,7565,7566,7567, 7568,7569,7570,7571,7572,7573,7574,7575,7576,7577,7578,7579,7580,7581,7582,7583, 7584,7585,7586,7587,7588,7589,7590,7591,7592,7593,7594,7595,7596,7597,7598,7599, 7600,7601,7602,7603,7604,7605,7606,7607,7608,7609,7610,7611,7612,7613,7614,7615, 7616,7617,7618,7619,7620,7621,7622,7623,7624,7625,7626,7627,7628,7629,7630,7631, 7632,7633,7634,7635,7636,7637,7638,7639,7640,7641,7642,7643,7644,7645,7646,7647, 7648,7649,7650,7651,7652,7653,7654,7655,7656,7657,7658,7659,7660,7661,7662,7663, 7664,7665,7666,7667,7668,7669,7670,7671,7672,7673,7674,7675,7676,7677,7678,7679, 7680,7681,7682,7683,7684,7685,7686,7687,7688,7689,7690,7691,7692,7693,7694,7695, 7696,7697,7698,7699,7700,7701,7702,7703,7704,7705,7706,7707,7708,7709,7710,7711, 7712,7713,7714,7715,7716,7717,7718,7719,7720,7721,7722,7723,7724,7725,7726,7727, 7728,7729,7730,7731,7732,7733,7734,7735,7736,7737,7738,7739,7740,7741,7742,7743, 7744,7745,7746,7747,7748,7749,7750,7751,7752,7753,7754,7755,7756,7757,7758,7759, 7760,7761,7762,7763,7764,7765,7766,7767,7768,7769,7770,7771,7772,7773,7774,7775, 7776,7777,7778,7779,7780,7781,7782,7783,7784,7785,7786,7787,7788,7789,7790,7791, 7792,7793,7794,7795,7796,7797,7798,7799,7800,7801,7802,7803,7804,7805,7806,7807, 7808,7809,7810,7811,7812,7813,7814,7815,7816,7817,7818,7819,7820,7821,7822,7823, 7824,7825,7826,7827,7828,7829,7830,7831,7832,7833,7834,7835,7836,7837,7838,7839, 7840,7841,7842,7843,7844,7845,7846,7847,7848,7849,7850,7851,7852,7853,7854,7855, 7856,7857,7858,7859,7860,7861,7862,7863,7864,7865,7866,7867,7868,7869,7870,7871, 7872,7873,7874,7875,7876,7877,7878,7879,7880,7881,7882,7883,7884,7885,7886,7887, 7888,7889,7890,7891,7892,7893,7894,7895,7896,7897,7898,7899,7900,7901,7902,7903, 7904,7905,7906,7907,7908,7909,7910,7911,7912,7913,7914,7915,7916,7917,7918,7919, 7920,7921,7922,7923,7924,7925,7926,7927,7928,7929,7930,7931,7932,7933,7934,7935, 7936,7937,7938,7939,7940,7941,7942,7943,7944,7945,7946,7947,7948,7949,7950,7951, 7952,7953,7954,7955,7956,7957,7958,7959,7960,7961,7962,7963,7964,7965,7966,7967, 7968,7969,7970,7971,7972,7973,7974,7975,7976,7977,7978,7979,7980,7981,7982,7983, 7984,7985,7986,7987,7988,7989,7990,7991,7992,7993,7994,7995,7996,7997,7998,7999, 8000,8001,8002,8003,8004,8005,8006,8007,8008,8009,8010,8011,8012,8013,8014,8015, 8016,8017,8018,8019,8020,8021,8022,8023,8024,8025,8026,8027,8028,8029,8030,8031, 8032,8033,8034,8035,8036,8037,8038,8039,8040,8041,8042,8043,8044,8045,8046,8047, 8048,8049,8050,8051,8052,8053,8054,8055,8056,8057,8058,8059,8060,8061,8062,8063, 8064,8065,8066,8067,8068,8069,8070,8071,8072,8073,8074,8075,8076,8077,8078,8079, 8080,8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8091,8092,8093,8094,8095, 8096,8097,8098,8099,8100,8101,8102,8103,8104,8105,8106,8107,8108,8109,8110,8111, 8112,8113,8114,8115,8116,8117,8118,8119,8120,8121,8122,8123,8124,8125,8126,8127, 8128,8129,8130,8131,8132,8133,8134,8135,8136,8137,8138,8139,8140,8141,8142,8143, 8144,8145,8146,8147,8148,8149,8150,8151,8152,8153,8154,8155,8156,8157,8158,8159, 8160,8161,8162,8163,8164,8165,8166,8167,8168,8169,8170,8171,8172,8173,8174,8175, 8176,8177,8178,8179,8180,8181,8182,8183,8184,8185,8186,8187,8188,8189,8190,8191, 8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8203,8204,8205,8206,8207, 8208,8209,8210,8211,8212,8213,8214,8215,8216,8217,8218,8219,8220,8221,8222,8223, 8224,8225,8226,8227,8228,8229,8230,8231,8232,8233,8234,8235,8236,8237,8238,8239, 8240,8241,8242,8243,8244,8245,8246,8247,8248,8249,8250,8251,8252,8253,8254,8255, 8256,8257,8258,8259,8260,8261,8262,8263,8264,8265,8266,8267,8268,8269,8270,8271, 8272,8273,8274,8275,8276,8277,8278,8279,8280,8281,8282,8283,8284,8285,8286,8287, 8288,8289,8290,8291,8292,8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303, 8304,8305,8306,8307,8308,8309,8310,8311,8312,8313,8314,8315,8316,8317,8318,8319, 8320,8321,8322,8323,8324,8325,8326,8327,8328,8329,8330,8331,8332,8333,8334,8335, 8336,8337,8338,8339,8340,8341,8342,8343,8344,8345,8346,8347,8348,8349,8350,8351, 8352,8353,8354,8355,8356,8357,8358,8359,8360,8361,8362,8363,8364,8365,8366,8367, 8368,8369,8370,8371,8372,8373,8374,8375,8376,8377,8378,8379,8380,8381,8382,8383, 8384,8385,8386,8387,8388,8389,8390,8391,8392,8393,8394,8395,8396,8397,8398,8399, 8400,8401,8402,8403,8404,8405,8406,8407,8408,8409,8410,8411,8412,8413,8414,8415, 8416,8417,8418,8419,8420,8421,8422,8423,8424,8425,8426,8427,8428,8429,8430,8431, 8432,8433,8434,8435,8436,8437,8438,8439,8440,8441,8442,8443,8444,8445,8446,8447, 8448,8449,8450,8451,8452,8453,8454,8455,8456,8457,8458,8459,8460,8461,8462,8463, 8464,8465,8466,8467,8468,8469,8470,8471,8472,8473,8474,8475,8476,8477,8478,8479, 8480,8481,8482,8483,8484,8485,8486,8487,8488,8489,8490,8491,8492,8493,8494,8495, 8496,8497,8498,8499,8500,8501,8502,8503,8504,8505,8506,8507,8508,8509,8510,8511, 8512,8513,8514,8515,8516,8517,8518,8519,8520,8521,8522,8523,8524,8525,8526,8527, 8528,8529,8530,8531,8532,8533,8534,8535,8536,8537,8538,8539,8540,8541,8542,8543, 8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,8554,8555,8556,8557,8558,8559, 8560,8561,8562,8563,8564,8565,8566,8567,8568,8569,8570,8571,8572,8573,8574,8575, 8576,8577,8578,8579,8580,8581,8582,8583,8584,8585,8586,8587,8588,8589,8590,8591, 8592,8593,8594,8595,8596,8597,8598,8599,8600,8601,8602,8603,8604,8605,8606,8607, 8608,8609,8610,8611,8612,8613,8614,8615,8616,8617,8618,8619,8620,8621,8622,8623, 8624,8625,8626,8627,8628,8629,8630,8631,8632,8633,8634,8635,8636,8637,8638,8639, 8640,8641,8642,8643,8644,8645,8646,8647,8648,8649,8650,8651,8652,8653,8654,8655, 8656,8657,8658,8659,8660,8661,8662,8663,8664,8665,8666,8667,8668,8669,8670,8671, 8672,8673,8674,8675,8676,8677,8678,8679,8680,8681,8682,8683,8684,8685,8686,8687, 8688,8689,8690,8691,8692,8693,8694,8695,8696,8697,8698,8699,8700,8701,8702,8703, 8704,8705,8706,8707,8708,8709,8710,8711,8712,8713,8714,8715,8716,8717,8718,8719, 8720,8721,8722,8723,8724,8725,8726,8727,8728,8729,8730,8731,8732,8733,8734,8735, 8736,8737,8738,8739,8740,8741) # flake8: noqa
abhidrona/gn-osc-custom
refs/heads/master
oscar/apps/offer/custom.py
6
from django.core import exceptions from oscar.apps.offer.models import Range, Condition, Benefit def _class_path(klass): return '%s.%s' % (klass.__module__, klass.__name__) def create_range(range_class): """ Create a custom range instance """ if not hasattr(range_class, 'name'): raise exceptions.ValidationError( "A custom range must have a name attribute") return Range.objects.create( name=range_class.name, proxy_class=_class_path(range_class)) def create_condition(condition_class): """ Create a custom condition instance """ return Condition.objects.create( proxy_class=_class_path(condition_class)) def create_benefit(benefit_class): """ Create a custom benefit instance """ # The custom benefit_class must override __unicode__ and description to # avoid a recursion error if benefit_class.description is Benefit.description: raise RuntimeError("Your custom benefit must implement its own " "'description' property") return Benefit.objects.create( proxy_class=_class_path(benefit_class))
nelmiux/CarnotKE
refs/heads/master
jyhton/lib-python/2.7/lib-tk/tkFileDialog.py
196
# # Instant Python # $Id: tkFileDialog.py 36560 2004-07-18 06:16:08Z tim_one $ # # tk common file dialogues # # this module provides interfaces to the native file dialogues # available in Tk 4.2 and newer, and the directory dialogue available # in Tk 8.3 and newer. # # written by Fredrik Lundh, May 1997. # # # options (all have default values): # # - defaultextension: added to filename if not explicitly given # # - filetypes: sequence of (label, pattern) tuples. the same pattern # may occur with several patterns. use "*" as pattern to indicate # all files. # # - initialdir: initial directory. preserved by dialog instance. # # - initialfile: initial file (ignored by the open dialog). preserved # by dialog instance. # # - parent: which window to place the dialog on top of # # - title: dialog title # # - multiple: if true user may select more than one file # # options for the directory chooser: # # - initialdir, parent, title: see above # # - mustexist: if true, user must pick an existing directory # # from tkCommonDialog import Dialog class _Dialog(Dialog): def _fixoptions(self): try: # make sure "filetypes" is a tuple self.options["filetypes"] = tuple(self.options["filetypes"]) except KeyError: pass def _fixresult(self, widget, result): if result: # keep directory and filename until next time import os # convert Tcl path objects to strings try: result = result.string except AttributeError: # it already is a string pass path, file = os.path.split(result) self.options["initialdir"] = path self.options["initialfile"] = file self.filename = result # compatibility return result # # file dialogs class Open(_Dialog): "Ask for a filename to open" command = "tk_getOpenFile" def _fixresult(self, widget, result): if isinstance(result, tuple): # multiple results: result = tuple([getattr(r, "string", r) for r in result]) if result: import os path, file = os.path.split(result[0]) self.options["initialdir"] = path # don't set initialfile or filename, as we have multiple of these return result if not widget.tk.wantobjects() and "multiple" in self.options: # Need to split result explicitly return self._fixresult(widget, widget.tk.splitlist(result)) return _Dialog._fixresult(self, widget, result) class SaveAs(_Dialog): "Ask for a filename to save as" command = "tk_getSaveFile" # the directory dialog has its own _fix routines. class Directory(Dialog): "Ask for a directory" command = "tk_chooseDirectory" def _fixresult(self, widget, result): if result: # convert Tcl path objects to strings try: result = result.string except AttributeError: # it already is a string pass # keep directory until next time self.options["initialdir"] = result self.directory = result # compatibility return result # # convenience stuff def askopenfilename(**options): "Ask for a filename to open" return Open(**options).show() def asksaveasfilename(**options): "Ask for a filename to save as" return SaveAs(**options).show() def askopenfilenames(**options): """Ask for multiple filenames to open Returns a list of filenames or empty list if cancel button selected """ options["multiple"]=1 return Open(**options).show() # FIXME: are the following perhaps a bit too convenient? def askopenfile(mode = "r", **options): "Ask for a filename to open, and returned the opened file" filename = Open(**options).show() if filename: return open(filename, mode) return None def askopenfiles(mode = "r", **options): """Ask for multiple filenames and return the open file objects returns a list of open file objects or an empty list if cancel selected """ files = askopenfilenames(**options) if files: ofiles=[] for filename in files: ofiles.append(open(filename, mode)) files=ofiles return files def asksaveasfile(mode = "w", **options): "Ask for a filename to save as, and returned the opened file" filename = SaveAs(**options).show() if filename: return open(filename, mode) return None def askdirectory (**options): "Ask for a directory, and return the file name" return Directory(**options).show() # -------------------------------------------------------------------- # test stuff if __name__ == "__main__": # Since the file name may contain non-ASCII characters, we need # to find an encoding that likely supports the file name, and # displays correctly on the terminal. # Start off with UTF-8 enc = "utf-8" import sys # See whether CODESET is defined try: import locale locale.setlocale(locale.LC_ALL,'') enc = locale.nl_langinfo(locale.CODESET) except (ImportError, AttributeError): pass # dialog for openening files openfilename=askopenfilename(filetypes=[("all files", "*")]) try: fp=open(openfilename,"r") fp.close() except: print "Could not open File: " print sys.exc_info()[1] print "open", openfilename.encode(enc) # dialog for saving files saveasfilename=asksaveasfilename() print "saveas", saveasfilename.encode(enc)
hgl888/chromium-crosswalk
refs/heads/master
chrome/test/chromedriver/client/webelement.py
15
# 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. from command_executor import Command class WebElement(object): """Represents an HTML element.""" def __init__(self, chromedriver, id_): self._chromedriver = chromedriver self._id = id_ def _Execute(self, command, params=None): if params is None: params = {} params['id'] = self._id; return self._chromedriver.ExecuteCommand(command, params) def FindElement(self, strategy, target): return self._Execute( Command.FIND_CHILD_ELEMENT, {'using': strategy, 'value': target}) def FindElements(self, strategy, target): return self._Execute( Command.FIND_CHILD_ELEMENTS, {'using': strategy, 'value': target}) def GetText(self): return self._Execute(Command.GET_ELEMENT_TEXT) def HoverOver(self): self._Execute(Command.HOVER_OVER_ELEMENT) def Click(self): self._Execute(Command.CLICK_ELEMENT) def SingleTap(self): self._Execute(Command.TOUCH_SINGLE_TAP) def DoubleTap(self): self._Execute(Command.TOUCH_DOUBLE_TAP) def LongPress(self): self._Execute(Command.TOUCH_LONG_PRESS) def Clear(self): self._Execute(Command.CLEAR_ELEMENT) def SendKeys(self, *values): typing = [] for value in values: if isinstance(value, int): value = str(value) for i in range(len(value)): typing.append(value[i]) self._Execute(Command.SEND_KEYS_TO_ELEMENT, {'value': typing}) def GetLocation(self): return self._Execute(Command.GET_ELEMENT_LOCATION) def IsDisplayed(self): return self._Execute(Command.IS_ELEMENT_DISPLAYED)
sinpantuflas/aubio
refs/heads/master
python.old/aubio/task/task.py
13
from aubio.aubioclass import * from params import taskparams class task(taskparams): """ default template class to apply tasks on a stream """ def __init__(self,input,output=None,params=None): """ open the input file and initialize default argument parameters should be set *before* calling this method. """ import time self.tic = time.time() if params == None: self.params = taskparams() else: self.params = params self.frameread = 0 self.readsize = self.params.hopsize self.input = input self.filei = sndfile(self.input) self.srate = self.filei.samplerate() self.params.step = float(self.params.hopsize)/float(self.srate) self.myvec = fvec(self.params.hopsize) self.output = output def __call__(self): self.readsize = self.filei.read(self.params.hopsize,self.myvec) self.frameread += 1 def compute_all(self): """ Compute data """ mylist = [] while(self.readsize==self.params.hopsize): tmp = self() if tmp: mylist.append(tmp) if self.params.verbose: self.fprint(tmp) return mylist def fprint(self,foo): print foo def eval(self,results): """ Eval data """ pass def plot(self): """ Plot data """ pass def time(self): import time #print "CPU time is now %f seconds," % time.clock(), #print "task execution took %f seconds" % (time.time() - self.tic) return time.time() - self.tic
babraham123/deepdriving
refs/heads/master
alexnet_reduced.py
1
from keras.models import Sequential, Model from keras.layers import Flatten, Dense, Dropout, Reshape, Permute, Activation, Input #, merge from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D from keras.layers.normalization import LRN2D from keras.optimizers import SGD import numpy as np from scipy.misc import imread, imresize, imsave from keras import backend as K # from convnetskeras.customlayers import crosschannelnormalization #, convolution2Dgroup, splittensor, Softmax4D # from convnetskeras.imagenet_tool import synset_to_id, id_to_synset,synset_to_dfs_ids """ Returns a keras model for a CNN. input data are of the shape (227,227), and the colors in the RGB order (default) model: The keras model for this convnet output_dict: Dict of feature layers, asked for in output_layers. """ #bias_initializer='ones' def AlexNet(weights_path=None): if K.image_dim_ordering() == 'tf': inputs = Input(shape=(64, 64, 3)) else: inputs = Input(shape=(3, 64, 64)) conv_1 = Convolution2D(32, (11, 11), subsample=(4,4), activation='relu', kernel_initializer='normal', bias_initializer='zeros', name='conv_1')(inputs) # initial weights filler? gaussian, std 0.01 conv_2 = MaxPooling2D((3, 3), strides=(2,2))(conv_1) conv_2 = LRN2D(alpha=1e-4, beta=0.75, n=5)(conv_2) #conv_2 = crosschannelnormalization(name="convpool_1")(conv_2) # in caffe: Local Response Normalization (LRN) # alpha = 1e-4, k=2, beta=0.75, n=5, conv_2 = ZeroPadding2D((2,2))(conv_2) # split unnecessary on modern GPUs, no stride conv_2 = Convolution2D(32, 5, 5, activation="relu",kernel_initializer='normal', bias_initializer='ones',name='conv_2')(conv_2) conv_3 = MaxPooling2D((3, 3), strides=(2, 2))(conv_2) conv_3 = LRN2D(alpha=1e-4, beta=0.75, n=5)(conv_3) #conv_3 = crosschannelnormalization()(conv_3) conv_3 = ZeroPadding2D((1, 1))(conv_3) conv_3 = Convolution2D(384, 3, 3, activation='relu', kernel_initializer='normal', bias_initializer='zeros', name='conv_3')(conv_3) conv_4 = ZeroPadding2D((1,1))(conv_3) # split unnecessary on modern GPUs, no stride # bias_filler constant value changes to 1 here in the actual code conv_4 = Convolution2D(384, 3, 3, activation="relu", kernel_initializer='normal', bias_initializer='ones', name='conv_4')(conv_4) conv_5 = ZeroPadding2D((1,1))(conv_4) # split unnecessary on modern GPUs, no stride # bias_filler constant value changes to 1 here in the actual code conv_5 = Convolution2D(256, 3, 3, activation="relu", kernel_initializer='normal', bias_initializer='ones', name='conv_5')(conv_5) # dense_1 = MaxPooling2D((3, 3), strides=(2,2), name="convpool_5")(conv_5) dense_1 = Flatten(name="flatten")(conv_5) # initial weights filler? gaussian, std 0.005 dense_1 = Dense(4096, activation='relu', kernel_initializer='normal',bias_initializer='ones',name='dense_1')(dense_1) dense_2 = Dropout(0.5)(dense_1) dense_2 = Dense(4096, activation='relu',kernel_initializer='normal',bias_initializer='ones', name='dense_2')(dense_2) dense_3 = Dropout(0.5)(dense_2) # initial weights filler? gaussian, std 0.01 dense_3 = Dense(256, activation='relu',kernel_initializer='normal', bias_initializer='zeros',name='dense_3')(dense_3) dense_4 = Dropout(0.5)(dense_3) # output: 14 affordances, gaussian std 0.01 dense_4 = Dense(14, activation='sigmoid',kernel_initializer='normal', bias_initializer='zeros', name='dense_4')(dense_4) model = Model(input=inputs, output=dense_4) if weights_path: model.load_weights(weights_path) sgd = SGD(lr=0.01, decay=0.0005, momentum=0.9) # nesterov=True) # caffe: euclidean loss model.compile(optimizer=sgd, loss='mean_squared_error') return model
edulramirez/nova
refs/heads/master
nova/scheduler/filters/num_instances_filter.py
56
# Copyright (c) 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 oslo_config import cfg from oslo_log import log as logging from nova.i18n import _LW from nova.scheduler import filters from nova.scheduler.filters import utils LOG = logging.getLogger(__name__) max_instances_per_host_opt = cfg.IntOpt("max_instances_per_host", default=50, help="Ignore hosts that have too many instances") CONF = cfg.CONF CONF.register_opt(max_instances_per_host_opt) class NumInstancesFilter(filters.BaseHostFilter): """Filter out hosts with too many instances.""" def _get_max_instances_per_host(self, host_state, filter_properties): return CONF.max_instances_per_host def host_passes(self, host_state, filter_properties): num_instances = host_state.num_instances max_instances = self._get_max_instances_per_host( host_state, filter_properties) passes = num_instances < max_instances if not passes: LOG.debug("%(host_state)s fails num_instances check: Max " "instances per host is set to %(max_instances)s", {'host_state': host_state, 'max_instances': max_instances}) return passes class AggregateNumInstancesFilter(NumInstancesFilter): """AggregateNumInstancesFilter with per-aggregate the max num instances. Fall back to global max_num_instances_per_host if no per-aggregate setting found. """ def _get_max_instances_per_host(self, host_state, filter_properties): aggregate_vals = utils.aggregate_values_from_key( host_state, 'max_instances_per_host') try: value = utils.validate_num_values( aggregate_vals, CONF.max_instances_per_host, cast_to=int) except ValueError as e: LOG.warning(_LW("Could not decode max_instances_per_host: '%s'"), e) value = CONF.max_instances_per_host return value
hottwaj/django
refs/heads/master
tests/gis_tests/geos_tests/test_mutable_list.py
173
# Copyright (c) 2008-2009 Aryeh Leib Taurog, http://www.aryehleib.com # All rights reserved. # # Modified from original contribution by Aryeh Leib Taurog, which was # released under the New BSD license. import unittest from django.contrib.gis.geos.mutable_list import ListMixin from django.utils import six class UserListA(ListMixin): _mytype = tuple def __init__(self, i_list, *args, **kwargs): self._list = self._mytype(i_list) super(UserListA, self).__init__(*args, **kwargs) def __len__(self): return len(self._list) def __str__(self): return str(self._list) def __repr__(self): return repr(self._list) def _set_list(self, length, items): # this would work: # self._list = self._mytype(items) # but then we wouldn't be testing length parameter itemList = ['x'] * length for i, v in enumerate(items): itemList[i] = v self._list = self._mytype(itemList) def _get_single_external(self, index): return self._list[index] class UserListB(UserListA): _mytype = list def _set_single(self, index, value): self._list[index] = value def nextRange(length): nextRange.start += 100 return range(nextRange.start, nextRange.start + length) nextRange.start = 0 class ListMixinTest(unittest.TestCase): """ Tests base class ListMixin by comparing a list clone which is a ListMixin subclass with a real Python list. """ limit = 3 listType = UserListA def lists_of_len(self, length=None): if length is None: length = self.limit pl = list(range(length)) return pl, self.listType(pl) def limits_plus(self, b): return range(-self.limit - b, self.limit + b) def step_range(self): return list(range(-1 - self.limit, 0)) + list(range(1, 1 + self.limit)) def test01_getslice(self): 'Slice retrieval' pl, ul = self.lists_of_len() for i in self.limits_plus(1): self.assertEqual(pl[i:], ul[i:], 'slice [%d:]' % (i)) self.assertEqual(pl[:i], ul[:i], 'slice [:%d]' % (i)) for j in self.limits_plus(1): self.assertEqual(pl[i:j], ul[i:j], 'slice [%d:%d]' % (i, j)) for k in self.step_range(): self.assertEqual(pl[i:j:k], ul[i:j:k], 'slice [%d:%d:%d]' % (i, j, k)) for k in self.step_range(): self.assertEqual(pl[i::k], ul[i::k], 'slice [%d::%d]' % (i, k)) self.assertEqual(pl[:i:k], ul[:i:k], 'slice [:%d:%d]' % (i, k)) for k in self.step_range(): self.assertEqual(pl[::k], ul[::k], 'slice [::%d]' % (k)) def test02_setslice(self): 'Slice assignment' def setfcn(x, i, j, k, L): x[i:j:k] = range(L) pl, ul = self.lists_of_len() for slen in range(self.limit + 1): ssl = nextRange(slen) ul[:] = ssl pl[:] = ssl self.assertEqual(pl, ul[:], 'set slice [:]') for i in self.limits_plus(1): ssl = nextRange(slen) ul[i:] = ssl pl[i:] = ssl self.assertEqual(pl, ul[:], 'set slice [%d:]' % (i)) ssl = nextRange(slen) ul[:i] = ssl pl[:i] = ssl self.assertEqual(pl, ul[:], 'set slice [:%d]' % (i)) for j in self.limits_plus(1): ssl = nextRange(slen) ul[i:j] = ssl pl[i:j] = ssl self.assertEqual(pl, ul[:], 'set slice [%d:%d]' % (i, j)) for k in self.step_range(): ssl = nextRange(len(ul[i:j:k])) ul[i:j:k] = ssl pl[i:j:k] = ssl self.assertEqual(pl, ul[:], 'set slice [%d:%d:%d]' % (i, j, k)) sliceLen = len(ul[i:j:k]) self.assertRaises(ValueError, setfcn, ul, i, j, k, sliceLen + 1) if sliceLen > 2: self.assertRaises(ValueError, setfcn, ul, i, j, k, sliceLen - 1) for k in self.step_range(): ssl = nextRange(len(ul[i::k])) ul[i::k] = ssl pl[i::k] = ssl self.assertEqual(pl, ul[:], 'set slice [%d::%d]' % (i, k)) ssl = nextRange(len(ul[:i:k])) ul[:i:k] = ssl pl[:i:k] = ssl self.assertEqual(pl, ul[:], 'set slice [:%d:%d]' % (i, k)) for k in self.step_range(): ssl = nextRange(len(ul[::k])) ul[::k] = ssl pl[::k] = ssl self.assertEqual(pl, ul[:], 'set slice [::%d]' % (k)) def test03_delslice(self): 'Delete slice' for Len in range(self.limit): pl, ul = self.lists_of_len(Len) del pl[:] del ul[:] self.assertEqual(pl[:], ul[:], 'del slice [:]') for i in range(-Len - 1, Len + 1): pl, ul = self.lists_of_len(Len) del pl[i:] del ul[i:] self.assertEqual(pl[:], ul[:], 'del slice [%d:]' % (i)) pl, ul = self.lists_of_len(Len) del pl[:i] del ul[:i] self.assertEqual(pl[:], ul[:], 'del slice [:%d]' % (i)) for j in range(-Len - 1, Len + 1): pl, ul = self.lists_of_len(Len) del pl[i:j] del ul[i:j] self.assertEqual(pl[:], ul[:], 'del slice [%d:%d]' % (i, j)) for k in list(range(-Len - 1, 0)) + list(range(1, Len)): pl, ul = self.lists_of_len(Len) del pl[i:j:k] del ul[i:j:k] self.assertEqual(pl[:], ul[:], 'del slice [%d:%d:%d]' % (i, j, k)) for k in list(range(-Len - 1, 0)) + list(range(1, Len)): pl, ul = self.lists_of_len(Len) del pl[:i:k] del ul[:i:k] self.assertEqual(pl[:], ul[:], 'del slice [:%d:%d]' % (i, k)) pl, ul = self.lists_of_len(Len) del pl[i::k] del ul[i::k] self.assertEqual(pl[:], ul[:], 'del slice [%d::%d]' % (i, k)) for k in list(range(-Len - 1, 0)) + list(range(1, Len)): pl, ul = self.lists_of_len(Len) del pl[::k] del ul[::k] self.assertEqual(pl[:], ul[:], 'del slice [::%d]' % (k)) def test04_get_set_del_single(self): 'Get/set/delete single item' pl, ul = self.lists_of_len() for i in self.limits_plus(0): self.assertEqual(pl[i], ul[i], 'get single item [%d]' % i) for i in self.limits_plus(0): pl, ul = self.lists_of_len() pl[i] = 100 ul[i] = 100 self.assertEqual(pl[:], ul[:], 'set single item [%d]' % i) for i in self.limits_plus(0): pl, ul = self.lists_of_len() del pl[i] del ul[i] self.assertEqual(pl[:], ul[:], 'del single item [%d]' % i) def test05_out_of_range_exceptions(self): 'Out of range exceptions' def setfcn(x, i): x[i] = 20 def getfcn(x, i): return x[i] def delfcn(x, i): del x[i] pl, ul = self.lists_of_len() for i in (-1 - self.limit, self.limit): self.assertRaises(IndexError, setfcn, ul, i) # 'set index %d' % i) self.assertRaises(IndexError, getfcn, ul, i) # 'get index %d' % i) self.assertRaises(IndexError, delfcn, ul, i) # 'del index %d' % i) def test06_list_methods(self): 'List methods' pl, ul = self.lists_of_len() pl.append(40) ul.append(40) self.assertEqual(pl[:], ul[:], 'append') pl.extend(range(50, 55)) ul.extend(range(50, 55)) self.assertEqual(pl[:], ul[:], 'extend') pl.reverse() ul.reverse() self.assertEqual(pl[:], ul[:], 'reverse') for i in self.limits_plus(1): pl, ul = self.lists_of_len() pl.insert(i, 50) ul.insert(i, 50) self.assertEqual(pl[:], ul[:], 'insert at %d' % i) for i in self.limits_plus(0): pl, ul = self.lists_of_len() self.assertEqual(pl.pop(i), ul.pop(i), 'popped value at %d' % i) self.assertEqual(pl[:], ul[:], 'after pop at %d' % i) pl, ul = self.lists_of_len() self.assertEqual(pl.pop(), ul.pop(i), 'popped value') self.assertEqual(pl[:], ul[:], 'after pop') pl, ul = self.lists_of_len() def popfcn(x, i): x.pop(i) self.assertRaises(IndexError, popfcn, ul, self.limit) self.assertRaises(IndexError, popfcn, ul, -1 - self.limit) pl, ul = self.lists_of_len() for val in range(self.limit): self.assertEqual(pl.index(val), ul.index(val), 'index of %d' % val) for val in self.limits_plus(2): self.assertEqual(pl.count(val), ul.count(val), 'count %d' % val) for val in range(self.limit): pl, ul = self.lists_of_len() pl.remove(val) ul.remove(val) self.assertEqual(pl[:], ul[:], 'after remove val %d' % val) def indexfcn(x, v): return x.index(v) def removefcn(x, v): return x.remove(v) self.assertRaises(ValueError, indexfcn, ul, 40) self.assertRaises(ValueError, removefcn, ul, 40) def test07_allowed_types(self): 'Type-restricted list' pl, ul = self.lists_of_len() ul._allowed = six.integer_types ul[1] = 50 ul[:2] = [60, 70, 80] def setfcn(x, i, v): x[i] = v self.assertRaises(TypeError, setfcn, ul, 2, 'hello') self.assertRaises(TypeError, setfcn, ul, slice(0, 3, 2), ('hello', 'goodbye')) def test08_min_length(self): 'Length limits' pl, ul = self.lists_of_len() ul._minlength = 1 def delfcn(x, i): del x[:i] def setfcn(x, i): x[:i] = [] for i in range(self.limit - ul._minlength + 1, self.limit + 1): self.assertRaises(ValueError, delfcn, ul, i) self.assertRaises(ValueError, setfcn, ul, i) del ul[:ul._minlength] ul._maxlength = 4 for i in range(0, ul._maxlength - len(ul)): ul.append(i) self.assertRaises(ValueError, ul.append, 10) def test09_iterable_check(self): 'Error on assigning non-iterable to slice' pl, ul = self.lists_of_len(self.limit + 1) def setfcn(x, i, v): x[i] = v self.assertRaises(TypeError, setfcn, ul, slice(0, 3, 2), 2) def test10_checkindex(self): 'Index check' pl, ul = self.lists_of_len() for i in self.limits_plus(0): if i < 0: self.assertEqual(ul._checkindex(i), i + self.limit, '_checkindex(neg index)') else: self.assertEqual(ul._checkindex(i), i, '_checkindex(pos index)') for i in (-self.limit - 1, self.limit): self.assertRaises(IndexError, ul._checkindex, i) def test_11_sorting(self): 'Sorting' pl, ul = self.lists_of_len() pl.insert(0, pl.pop()) ul.insert(0, ul.pop()) pl.sort() ul.sort() self.assertEqual(pl[:], ul[:], 'sort') mid = pl[len(pl) // 2] pl.sort(key=lambda x: (mid - x) ** 2) ul.sort(key=lambda x: (mid - x) ** 2) self.assertEqual(pl[:], ul[:], 'sort w/ key') pl.insert(0, pl.pop()) ul.insert(0, ul.pop()) pl.sort(reverse=True) ul.sort(reverse=True) self.assertEqual(pl[:], ul[:], 'sort w/ reverse') mid = pl[len(pl) // 2] pl.sort(key=lambda x: (mid - x) ** 2) ul.sort(key=lambda x: (mid - x) ** 2) self.assertEqual(pl[:], ul[:], 'sort w/ key') def test_12_arithmetic(self): 'Arithmetic' pl, ul = self.lists_of_len() al = list(range(10, 14)) self.assertEqual(list(pl + al), list(ul + al), 'add') self.assertEqual(type(ul), type(ul + al), 'type of add result') self.assertEqual(list(al + pl), list(al + ul), 'radd') self.assertEqual(type(al), type(al + ul), 'type of radd result') objid = id(ul) pl += al ul += al self.assertEqual(pl[:], ul[:], 'in-place add') self.assertEqual(objid, id(ul), 'in-place add id') for n in (-1, 0, 1, 3): pl, ul = self.lists_of_len() self.assertEqual(list(pl * n), list(ul * n), 'mul by %d' % n) self.assertEqual(type(ul), type(ul * n), 'type of mul by %d result' % n) self.assertEqual(list(n * pl), list(n * ul), 'rmul by %d' % n) self.assertEqual(type(ul), type(n * ul), 'type of rmul by %d result' % n) objid = id(ul) pl *= n ul *= n self.assertEqual(pl[:], ul[:], 'in-place mul by %d' % n) self.assertEqual(objid, id(ul), 'in-place mul by %d id' % n) pl, ul = self.lists_of_len() self.assertEqual(pl, ul, 'cmp for equal') self.assertNotEqual(ul, pl + [2], 'cmp for not equal') self.assertGreaterEqual(pl, ul, 'cmp for gte self') self.assertLessEqual(pl, ul, 'cmp for lte self') self.assertGreaterEqual(ul, pl, 'cmp for self gte') self.assertLessEqual(ul, pl, 'cmp for self lte') self.assertGreater(pl + [5], ul, 'cmp') self.assertGreaterEqual(pl + [5], ul, 'cmp') self.assertLess(pl, ul + [2], 'cmp') self.assertLessEqual(pl, ul + [2], 'cmp') self.assertGreater(ul + [5], pl, 'cmp') self.assertGreaterEqual(ul + [5], pl, 'cmp') self.assertLess(ul, pl + [2], 'cmp') self.assertLessEqual(ul, pl + [2], 'cmp') # Also works with a custom IndexError ul_longer = ul + [2] ul_longer._IndexError = TypeError ul._IndexError = TypeError self.assertNotEqual(ul_longer, pl) self.assertGreater(ul_longer, ul) pl[1] = 20 self.assertGreater(pl, ul, 'cmp for gt self') self.assertLess(ul, pl, 'cmp for self lt') pl[1] = -20 self.assertLess(pl, ul, 'cmp for lt self') self.assertGreater(ul, pl, 'cmp for gt self') class ListMixinTestSingle(ListMixinTest): listType = UserListB
davecranwell/wagtail
refs/heads/master
wagtail/wagtailembeds/embeds.py
4
from datetime import datetime from wagtail.wagtailembeds.models import Embed from wagtail.wagtailembeds.finders import get_default_finder def get_embed(url, max_width=None, finder=None): # Check database try: return Embed.objects.get(url=url, max_width=max_width) except Embed.DoesNotExist: pass # Get/Call finder if not finder: finder = get_default_finder() embed_dict = finder(url, max_width) # Make sure width and height are valid integers before inserting into database try: embed_dict['width'] = int(embed_dict['width']) except (TypeError, ValueError): embed_dict['width'] = None try: embed_dict['height'] = int(embed_dict['height']) except (TypeError, ValueError): embed_dict['height'] = None # Make sure html field is valid if 'html' not in embed_dict or not embed_dict['html']: embed_dict['html'] = '' # Create database record embed, created = Embed.objects.get_or_create( url=url, max_width=max_width, defaults=embed_dict, ) # Save embed.last_updated = datetime.now() embed.save() return embed
vktr/CouchPotatoServer
refs/heads/master
couchpotato/core/media/movie/providers/nzb/newznab.py
73
from couchpotato.core.helpers.encoding import tryUrlencode from couchpotato.core.helpers.variable import getIdentifier from couchpotato.core.logger import CPLog from couchpotato.core.media._base.providers.nzb.newznab import Base from couchpotato.core.media.movie.providers.base import MovieProvider log = CPLog(__name__) autoload = 'Newznab' class Newznab(MovieProvider, Base): def buildUrl(self, media, host): query = tryUrlencode({ 't': 'movie', 'imdbid': getIdentifier(media).replace('tt', ''), 'apikey': host['api_key'], 'extended': 1 }) if len(host.get('custom_tag', '')) > 0: query = '%s&%s' % (query, host.get('custom_tag')) return query
sYnfo/samba-1
refs/heads/master
python/samba/tests/ntacls.py
32
# Unix SMB/CIFS implementation. Tests for ntacls manipulation # Copyright (C) Matthieu Patou <mat@matws.net> 2009-2010 # Copyright (C) Andrew Bartlett 2012 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """Tests for samba.ntacls.""" from samba.ntacls import setntacl, getntacl, XattrBackendError from samba.param import LoadParm from samba.dcerpc import security from samba.tests import TestCaseInTempDir, SkipTest import os class NtaclsTests(TestCaseInTempDir): def test_setntacl(self): lp = LoadParm() acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)" open(self.tempf, 'w').write("empty") lp.set("posix:eadb",os.path.join(self.tempdir,"eadbtest.tdb")) setntacl(lp, self.tempf, acl, "S-1-5-21-2212615479-2695158682-2101375467") os.unlink(os.path.join(self.tempdir,"eadbtest.tdb")) def test_setntacl_getntacl(self): lp = LoadParm() acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)" open(self.tempf, 'w').write("empty") lp.set("posix:eadb",os.path.join(self.tempdir,"eadbtest.tdb")) setntacl(lp,self.tempf,acl,"S-1-5-21-2212615479-2695158682-2101375467") facl = getntacl(lp,self.tempf) anysid = security.dom_sid(security.SID_NT_SELF) self.assertEquals(facl.as_sddl(anysid),acl) os.unlink(os.path.join(self.tempdir,"eadbtest.tdb")) def test_setntacl_getntacl_param(self): lp = LoadParm() acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)" open(self.tempf, 'w').write("empty") setntacl(lp,self.tempf,acl,"S-1-5-21-2212615479-2695158682-2101375467","tdb",os.path.join(self.tempdir,"eadbtest.tdb")) facl=getntacl(lp,self.tempf,"tdb",os.path.join(self.tempdir,"eadbtest.tdb")) domsid=security.dom_sid(security.SID_NT_SELF) self.assertEquals(facl.as_sddl(domsid),acl) os.unlink(os.path.join(self.tempdir,"eadbtest.tdb")) def test_setntacl_invalidbackend(self): lp = LoadParm() acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)" open(self.tempf, 'w').write("empty") self.assertRaises(XattrBackendError, setntacl, lp, self.tempf, acl, "S-1-5-21-2212615479-2695158682-2101375467","ttdb", os.path.join(self.tempdir,"eadbtest.tdb")) def test_setntacl_forcenative(self): if os.getuid() == 0: raise SkipTest("Running test as root, test skipped") lp = LoadParm() acl = "O:S-1-5-21-2212615479-2695158682-2101375467-512G:S-1-5-21-2212615479-2695158682-2101375467-513D:(A;OICI;0x001f01ff;;;S-1-5-21-2212615479-2695158682-2101375467-512)" open(self.tempf, 'w').write("empty") lp.set("posix:eadb", os.path.join(self.tempdir,"eadbtest.tdb")) self.assertRaises(Exception, setntacl, lp, self.tempf ,acl, "S-1-5-21-2212615479-2695158682-2101375467","native") def setUp(self): super(NtaclsTests, self).setUp() self.tempf = os.path.join(self.tempdir, "test") open(self.tempf, 'w').write("empty") def tearDown(self): os.unlink(self.tempf) super(NtaclsTests, self).tearDown()
jk1/intellij-community
refs/heads/master
python/testData/inspections/PyCompatibilityInspection/noWarningAboutStarredExpressionsInFunctionTypeComments.py
30
def create_instance(self, task_config, **kwargs): # type: (TaskConfig, **Text) -> TaskInstance pass
alexlo03/ansible
refs/heads/devel
lib/ansible/modules/cloud/amazon/dynamodb_table.py
15
#!/usr/bin/python # Copyright: 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 ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = """ --- module: dynamodb_table short_description: Create, update or delete AWS Dynamo DB tables. version_added: "2.0" description: - Create or delete AWS Dynamo DB tables. - Can update the provisioned throughput on existing tables. - Returns the status of the specified table. author: Alan Loi (@loia) requirements: - "boto >= 2.37.0" - "boto3 >= 1.4.4 (for tagging)" options: state: description: - Create or delete the table choices: ['present', 'absent'] default: 'present' name: description: - Name of the table. required: true hash_key_name: description: - Name of the hash key. - Required when C(state=present). hash_key_type: description: - Type of the hash key. choices: ['STRING', 'NUMBER', 'BINARY'] default: 'STRING' range_key_name: description: - Name of the range key. range_key_type: description: - Type of the range key. choices: ['STRING', 'NUMBER', 'BINARY'] default: 'STRING' read_capacity: description: - Read throughput capacity (units) to provision. default: 1 write_capacity: description: - Write throughput capacity (units) to provision. default: 1 indexes: description: - list of dictionaries describing indexes to add to the table. global indexes can be updated. local indexes don't support updates or have throughput. - "required options: ['name', 'type', 'hash_key_name']" - "valid types: ['all', 'global_all', 'global_include', 'global_keys_only', 'include', 'keys_only']" - "other options: ['hash_key_type', 'range_key_name', 'range_key_type', 'includes', 'read_capacity', 'write_capacity']" default: [] version_added: "2.1" tags: version_added: "2.4" description: - a hash/dictionary of tags to add to the new instance or for starting/stopping instance by tag; '{"key":"value"}' and '{"key":"value","key":"value"}' wait_for_active_timeout: version_added: "2.4" description: - how long before wait gives up, in seconds. only used when tags is set default: 60 extends_documentation_fragment: - aws - ec2 """ EXAMPLES = ''' # Create dynamo table with hash and range primary key - dynamodb_table: name: my-table region: us-east-1 hash_key_name: id hash_key_type: STRING range_key_name: create_time range_key_type: NUMBER read_capacity: 2 write_capacity: 2 tags: tag_name: tag_value # Update capacity on existing dynamo table - dynamodb_table: name: my-table region: us-east-1 read_capacity: 10 write_capacity: 10 # set index on existing dynamo table - dynamodb_table: name: my-table region: us-east-1 indexes: - name: NamedIndex type: global_include hash_key_name: id range_key_name: create_time includes: - other_field - other_field2 read_capacity: 10 write_capacity: 10 # Delete dynamo table - dynamodb_table: name: my-table region: us-east-1 state: absent ''' RETURN = ''' table_status: description: The current status of the table. returned: success type: string sample: ACTIVE ''' import time import traceback try: import boto import boto.dynamodb2 from boto.dynamodb2.table import Table from boto.dynamodb2.fields import HashKey, RangeKey, AllIndex, GlobalAllIndex, GlobalIncludeIndex, GlobalKeysOnlyIndex, IncludeIndex, KeysOnlyIndex from boto.dynamodb2.types import STRING, NUMBER, BINARY from boto.exception import BotoServerError, NoAuthHandlerFound, JSONResponseError from boto.dynamodb2.exceptions import ValidationException HAS_BOTO = True DYNAMO_TYPE_MAP = { 'STRING': STRING, 'NUMBER': NUMBER, 'BINARY': BINARY } except ImportError: HAS_BOTO = False try: import botocore from ansible.module_utils.ec2 import ansible_dict_to_boto3_tag_list, boto3_conn HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import AnsibleAWSError, connect_to_aws, ec2_argument_spec, get_aws_connection_info DYNAMO_TYPE_DEFAULT = 'STRING' INDEX_REQUIRED_OPTIONS = ['name', 'type', 'hash_key_name'] INDEX_OPTIONS = INDEX_REQUIRED_OPTIONS + ['hash_key_type', 'range_key_name', 'range_key_type', 'includes', 'read_capacity', 'write_capacity'] INDEX_TYPE_OPTIONS = ['all', 'global_all', 'global_include', 'global_keys_only', 'include', 'keys_only'] def create_or_update_dynamo_table(connection, module, boto3_dynamodb=None, boto3_sts=None, region=None): table_name = module.params.get('name') hash_key_name = module.params.get('hash_key_name') hash_key_type = module.params.get('hash_key_type') range_key_name = module.params.get('range_key_name') range_key_type = module.params.get('range_key_type') read_capacity = module.params.get('read_capacity') write_capacity = module.params.get('write_capacity') all_indexes = module.params.get('indexes') tags = module.params.get('tags') wait_for_active_timeout = module.params.get('wait_for_active_timeout') for index in all_indexes: validate_index(index, module) schema = get_schema_param(hash_key_name, hash_key_type, range_key_name, range_key_type) throughput = { 'read': read_capacity, 'write': write_capacity } indexes, global_indexes = get_indexes(all_indexes) result = dict( region=region, table_name=table_name, hash_key_name=hash_key_name, hash_key_type=hash_key_type, range_key_name=range_key_name, range_key_type=range_key_type, read_capacity=read_capacity, write_capacity=write_capacity, indexes=all_indexes, ) try: table = Table(table_name, connection=connection) if dynamo_table_exists(table): result['changed'] = update_dynamo_table(table, throughput=throughput, check_mode=module.check_mode, global_indexes=global_indexes) else: if not module.check_mode: Table.create(table_name, connection=connection, schema=schema, throughput=throughput, indexes=indexes, global_indexes=global_indexes) result['changed'] = True if not module.check_mode: result['table_status'] = table.describe()['Table']['TableStatus'] if tags: # only tables which are active can be tagged wait_until_table_active(module, table, wait_for_active_timeout) account_id = get_account_id(boto3_sts) boto3_dynamodb.tag_resource( ResourceArn='arn:aws:dynamodb:' + region + ':' + account_id + ':table/' + table_name, Tags=ansible_dict_to_boto3_tag_list(tags)) result['tags'] = tags except BotoServerError: result['msg'] = 'Failed to create/update dynamo table due to error: ' + traceback.format_exc() module.fail_json(**result) else: module.exit_json(**result) def get_account_id(boto3_sts): return boto3_sts.get_caller_identity()["Account"] def wait_until_table_active(module, table, wait_timeout): max_wait_time = time.time() + wait_timeout while (max_wait_time > time.time()) and (table.describe()['Table']['TableStatus'] != 'ACTIVE'): time.sleep(5) if max_wait_time <= time.time(): # waiting took too long module.fail_json(msg="timed out waiting for table to exist") def delete_dynamo_table(connection, module): table_name = module.params.get('name') result = dict( region=module.params.get('region'), table_name=table_name, ) try: table = Table(table_name, connection=connection) if dynamo_table_exists(table): if not module.check_mode: table.delete() result['changed'] = True else: result['changed'] = False except BotoServerError: result['msg'] = 'Failed to delete dynamo table due to error: ' + traceback.format_exc() module.fail_json(**result) else: module.exit_json(**result) def dynamo_table_exists(table): try: table.describe() return True except JSONResponseError as e: if e.message and e.message.startswith('Requested resource not found'): return False else: raise e def update_dynamo_table(table, throughput=None, check_mode=False, global_indexes=None): table.describe() # populate table details throughput_changed = False global_indexes_changed = False if has_throughput_changed(table, throughput): if not check_mode: throughput_changed = table.update(throughput=throughput) else: throughput_changed = True removed_indexes, added_indexes, index_throughput_changes = get_changed_global_indexes(table, global_indexes) if removed_indexes: if not check_mode: for name, index in removed_indexes.items(): global_indexes_changed = table.delete_global_secondary_index(name) or global_indexes_changed else: global_indexes_changed = True if added_indexes: if not check_mode: for name, index in added_indexes.items(): global_indexes_changed = table.create_global_secondary_index(global_index=index) or global_indexes_changed else: global_indexes_changed = True if index_throughput_changes: if not check_mode: # todo: remove try once boto has https://github.com/boto/boto/pull/3447 fixed try: global_indexes_changed = table.update_global_secondary_index(global_indexes=index_throughput_changes) or global_indexes_changed except ValidationException: pass else: global_indexes_changed = True return throughput_changed or global_indexes_changed def has_throughput_changed(table, new_throughput): if not new_throughput: return False return new_throughput['read'] != table.throughput['read'] or \ new_throughput['write'] != table.throughput['write'] def get_schema_param(hash_key_name, hash_key_type, range_key_name, range_key_type): if range_key_name: schema = [ HashKey(hash_key_name, DYNAMO_TYPE_MAP.get(hash_key_type, DYNAMO_TYPE_MAP[DYNAMO_TYPE_DEFAULT])), RangeKey(range_key_name, DYNAMO_TYPE_MAP.get(range_key_type, DYNAMO_TYPE_MAP[DYNAMO_TYPE_DEFAULT])) ] else: schema = [ HashKey(hash_key_name, DYNAMO_TYPE_MAP.get(hash_key_type, DYNAMO_TYPE_MAP[DYNAMO_TYPE_DEFAULT])) ] return schema def get_changed_global_indexes(table, global_indexes): table.describe() table_index_info = dict((index.name, index.schema()) for index in table.global_indexes) table_index_objects = dict((index.name, index) for index in table.global_indexes) set_index_info = dict((index.name, index.schema()) for index in global_indexes) set_index_objects = dict((index.name, index) for index in global_indexes) removed_indexes = dict((name, index) for name, index in table_index_info.items() if name not in set_index_info) added_indexes = dict((name, set_index_objects[name]) for name, index in set_index_info.items() if name not in table_index_info) # todo: uncomment once boto has https://github.com/boto/boto/pull/3447 fixed # for name, index in set_index_objects.items(): # if (name not in added_indexes and # (index.throughput['read'] != str(table_index_objects[name].throughput['read']) or # index.throughput['write'] != str(table_index_objects[name].throughput['write']))): # index_throughput_changes[name] = index.throughput # todo: remove once boto has https://github.com/boto/boto/pull/3447 fixed index_throughput_changes = dict((name, index.throughput) for name, index in set_index_objects.items() if name not in added_indexes) return removed_indexes, added_indexes, index_throughput_changes def validate_index(index, module): for key, val in index.items(): if key not in INDEX_OPTIONS: module.fail_json(msg='%s is not a valid option for an index' % key) for required_option in INDEX_REQUIRED_OPTIONS: if required_option not in index: module.fail_json(msg='%s is a required option for an index' % required_option) if index['type'] not in INDEX_TYPE_OPTIONS: module.fail_json(msg='%s is not a valid index type, must be one of %s' % (index['type'], INDEX_TYPE_OPTIONS)) def get_indexes(all_indexes): indexes = [] global_indexes = [] for index in all_indexes: name = index['name'] schema = get_schema_param(index.get('hash_key_name'), index.get('hash_key_type'), index.get('range_key_name'), index.get('range_key_type')) throughput = { 'read': index.get('read_capacity', 1), 'write': index.get('write_capacity', 1) } if index['type'] == 'all': indexes.append(AllIndex(name, parts=schema)) elif index['type'] == 'global_all': global_indexes.append(GlobalAllIndex(name, parts=schema, throughput=throughput)) elif index['type'] == 'global_include': global_indexes.append(GlobalIncludeIndex(name, parts=schema, throughput=throughput, includes=index['includes'])) elif index['type'] == 'global_keys_only': global_indexes.append(GlobalKeysOnlyIndex(name, parts=schema, throughput=throughput)) elif index['type'] == 'include': indexes.append(IncludeIndex(name, parts=schema, includes=index['includes'])) elif index['type'] == 'keys_only': indexes.append(KeysOnlyIndex(name, parts=schema)) return indexes, global_indexes def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( state=dict(default='present', choices=['present', 'absent']), name=dict(required=True, type='str'), hash_key_name=dict(type='str'), hash_key_type=dict(default='STRING', type='str', choices=['STRING', 'NUMBER', 'BINARY']), range_key_name=dict(type='str'), range_key_type=dict(default='STRING', type='str', choices=['STRING', 'NUMBER', 'BINARY']), read_capacity=dict(default=1, type='int'), write_capacity=dict(default=1, type='int'), indexes=dict(default=[], type='list'), tags=dict(type='dict'), wait_for_active_timeout=dict(default=60, type='int'), )) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True) if not HAS_BOTO: module.fail_json(msg='boto required for this module') if not HAS_BOTO3 and module.params.get('tags'): module.fail_json(msg='boto3 required when using tags for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module) if not region: module.fail_json(msg='region must be specified') try: connection = connect_to_aws(boto.dynamodb2, region, **aws_connect_params) except (NoAuthHandlerFound, AnsibleAWSError) as e: module.fail_json(msg=str(e)) if module.params.get('tags'): try: region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) boto3_dynamodb = boto3_conn(module, conn_type='client', resource='dynamodb', region=region, endpoint=ec2_url, **aws_connect_kwargs) if not hasattr(boto3_dynamodb, 'tag_resource'): module.fail_json(msg='boto3 connection does not have tag_resource(), likely due to using an old version') boto3_sts = boto3_conn(module, conn_type='client', resource='sts', region=region, endpoint=ec2_url, **aws_connect_kwargs) except botocore.exceptions.NoCredentialsError as e: module.fail_json(msg='cannot connect to AWS', exception=traceback.format_exc()) else: boto3_dynamodb = None boto3_sts = None state = module.params.get('state') if state == 'present': create_or_update_dynamo_table(connection, module, boto3_dynamodb, boto3_sts, region) elif state == 'absent': delete_dynamo_table(connection, module) if __name__ == '__main__': main()
ranog/simplemooc
refs/heads/master
simplemooc/accounts/views.py
1
from django.shortcuts import render, redirect # Create your views here. from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm from django.conf import settings from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from .forms import RegisterForm, EditAccountForm @login_required def dashboard(request): template_name = 'dashboard.html' return render(request, template_name) def register(request): template_name = 'register.html' if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect(settings.LOGIN_URL) else: form = RegisterForm() context = { 'form':form } return render(request, template_name, context) @login_required def edit(request): template_name = 'edit.html' context = {} if request.method == 'POST': form = EditAccountForm(request.POST, instance=request.user) if form.is_valid(): form.save() form = EditAccountForm(instance=request.user) context['success'] = True else: form = EditAccountForm(instance=request.user) context['form'] = form return render(request, template_name, context) @login_required def edit_password(request): template_name = 'edit_password.html' context = {} if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() context['success'] = True else: form = PasswordChangeForm(user=request.user) context['form'] = form return render(request, template_name, context)
vinegret/youtube-dl
refs/heads/master
youtube_dl/extractor/drtuber.py
20
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( int_or_none, NO_DEFAULT, parse_duration, str_to_int, ) class DrTuberIE(InfoExtractor): _VALID_URL = r'https?://(?:(?:www|m)\.)?drtuber\.com/(?:video|embed)/(?P<id>\d+)(?:/(?P<display_id>[\w-]+))?' _TESTS = [{ 'url': 'http://www.drtuber.com/video/1740434/hot-perky-blonde-naked-golf', 'md5': '93e680cf2536ad0dfb7e74d94a89facd', 'info_dict': { 'id': '1740434', 'display_id': 'hot-perky-blonde-naked-golf', 'ext': 'mp4', 'title': 'hot perky blonde naked golf', 'like_count': int, 'comment_count': int, 'categories': ['Babe', 'Blonde', 'Erotic', 'Outdoor', 'Softcore', 'Solo'], 'thumbnail': r're:https?://.*\.jpg$', 'age_limit': 18, } }, { 'url': 'http://www.drtuber.com/embed/489939', 'only_matching': True, }, { 'url': 'http://m.drtuber.com/video/3893529/lingerie-blowjob-from-beautiful-teen', 'only_matching': True, }] @staticmethod def _extract_urls(webpage): return re.findall( r'<iframe[^>]+?src=["\'](?P<url>(?:https?:)?//(?:www\.)?drtuber\.com/embed/\d+)', webpage) def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') display_id = mobj.group('display_id') or video_id webpage = self._download_webpage( 'http://www.drtuber.com/video/%s' % video_id, display_id) video_data = self._download_json( 'http://www.drtuber.com/player_config_json/', video_id, query={ 'vid': video_id, 'embed': 0, 'aid': 0, 'domain_id': 0, }) formats = [] for format_id, video_url in video_data['files'].items(): if video_url: formats.append({ 'format_id': format_id, 'quality': 2 if format_id == 'hq' else 1, 'url': video_url }) self._sort_formats(formats) duration = int_or_none(video_data.get('duration')) or parse_duration( video_data.get('duration_format')) title = self._html_search_regex( (r'<h1[^>]+class=["\']title[^>]+>([^<]+)', r'<title>([^<]+)\s*@\s+DrTuber', r'class="title_watch"[^>]*><(?:p|h\d+)[^>]*>([^<]+)<', r'<p[^>]+class="title_substrate">([^<]+)</p>', r'<title>([^<]+) - \d+'), webpage, 'title') thumbnail = self._html_search_regex( r'poster="([^"]+)"', webpage, 'thumbnail', fatal=False) def extract_count(id_, name, default=NO_DEFAULT): return str_to_int(self._html_search_regex( r'<span[^>]+(?:class|id)="%s"[^>]*>([\d,\.]+)</span>' % id_, webpage, '%s count' % name, default=default, fatal=False)) like_count = extract_count('rate_likes', 'like') dislike_count = extract_count('rate_dislikes', 'dislike', default=None) comment_count = extract_count('comments_count', 'comment') cats_str = self._search_regex( r'<div[^>]+class="categories_list">(.+?)</div>', webpage, 'categories', fatal=False) categories = [] if not cats_str else re.findall( r'<a title="([^"]+)"', cats_str) return { 'id': video_id, 'display_id': display_id, 'formats': formats, 'title': title, 'thumbnail': thumbnail, 'like_count': like_count, 'dislike_count': dislike_count, 'comment_count': comment_count, 'categories': categories, 'age_limit': self._rta_search(webpage), 'duration': duration, }
nzjrs/cerbero
refs/heads/binary-windows
cerbero/commands/package.py
15
# cerbero - a multi-platform build system for Open Source software # Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. import os from cerbero.config import Platform from cerbero.commands import Command, register_command, build from cerbero.utils import _, N_, ArgparseArgument from cerbero.utils import messages as m from cerbero.errors import PackageNotFoundError, UsageError from cerbero.packages.packager import Packager from cerbero.packages.packagesstore import PackagesStore from cerbero.packages.disttarball import DistTarball from cerbero.packages.linux_bundle import LinuxBundler class Package(Command): doc = N_('Creates a distribution package') name = 'package' def __init__(self): Command.__init__(self, [ArgparseArgument('package', nargs=1, help=_('name of the package to create')), ArgparseArgument('-o', '--output-dir', default='.', help=_('Output directory for the tarball file')), ArgparseArgument('-t', '--tarball', action='store_true', default=False, help=_('Creates a tarball instead of a native package')), ArgparseArgument('-n', '--no-split', action='store_true', default=False, help=_('(only meaningfull when --tarball is set) Create one single ' 'tarball with devel and runtime files')), ArgparseArgument('-l', '--linux-bundle', action='store_true', default=False, help=_('Creates a tarball instead of a native package')), ArgparseArgument('-f', '--force', action='store_true', default=False, help=_('Delete any existing package file')), ArgparseArgument('-d', '--no-devel', action='store_false', default=True, help=_('Do not create the development version ' 'of this package')), ArgparseArgument('-s', '--skip-deps-build', action='store_true', default=False, help=_('Do not build the recipes needed to ' 'create this package (conflicts with --only-build-deps)')), ArgparseArgument('-b', '--only-build-deps', action='store_true', default=False, help=_('Only build the recipes needed to ' 'create this package (conflicts with --skip-deps-build)')), ArgparseArgument('-k', '--keep-temp', action='store_true', default=False, help=_('Keep temporary files for debug')), ]) def run(self, config, args): self.store = PackagesStore(config) p = self.store.get_package(args.package[0]) if args.skip_deps_build and args.only_build_deps: raise UsageError(_("Cannot use --skip-deps-build together with " "--only-build-deps")) if not args.skip_deps_build: self._build_deps(config, p, args.no_devel) if args.only_build_deps: return if p is None: raise PackageNotFoundError(args.package[0]) if args.tarball: pkg = DistTarball(config, p, self.store) elif args.linux_bundle: if config.target_platform != Platform.LINUX: UsageError("Linux bundler is usable only for linux platforms") pkg = LinuxBundler(config, p, self.store) else: pkg = Packager(config, p, self.store) m.action(_("Creating package for %s") % p.name) if args.tarball: paths = pkg.pack(os.path.abspath(args.output_dir), args.no_devel, args.force, args.keep_temp, split=not args.no_split) else: paths = pkg.pack(os.path.abspath(args.output_dir), args.no_devel, args.force, args.keep_temp) if None in paths: paths.remove(None) p.post_install(paths) m.action(_("Package successfully created in %s") % ' '.join([os.path.abspath(x) for x in paths])) def _build_deps(self, config, package, has_devel): build_command = build.Build() build_command.runargs(config, package.recipes_dependencies(has_devel), cookbook=self.store.cookbook) register_command(Package)
syhpoon/xyzcmd
refs/heads/master
plugins/ui/vixyz/main.py
1
#-*- coding: utf8 -* # # Max E. Kuznecov <mek@mek.uz.ua> 2010 # from libxyz.core.utils import is_func from libxyz.core.plugins import BasePlugin from libxyz.ui import Shortcut from libxyz.core.dsl import XYZ class XYZPlugin(BasePlugin): "Plugin vixyz" NAME = u"vixyz" AUTHOR = u"Max E. Kuznecov <mek@mek.uz.ua>" VERSION = u"0.1" BRIEF_DESCRIPTION = _(u"Vi-like navigation mode") FULL_DESCRIPTION = _(u"") NAMESPACE = u"ui" MIN_XYZ_VERSION = 6 DOC = _(u"Available commands:\n"\ u"j - move cursor one entry down\n"\ u"k - move cursor one entry up\n"\ u"l - perform an action on selected object\n"\ u"h - step to the parent directory\n"\ u"gg - move to the first entry\n"\ u"G - move to the last entry\n"\ u"Ctrl-G - show VFS object information\n"\ u"m[a-z][A-Z][0-9] - set a mark to the current file\n"\ u"'[a-z][A-Z][0-9] - jump to the marked file\n"\ u"/ - search for object\n"\ u"? - search for object backwards\n"\ u"dd - remove object\n"\ u"yy - copy object\n"\ u"t - toggle tag\n"\ u"i, I - switch to insert mode\n"\ u"ESC - switch to command command mode") HOMEPAGE = u"http://xyzcmd.syhpoon.name/" EVENTS = None PALETTES = { 'command_mode': { 'monochrome': { 'foreground': 'BLACK', 'background': 'LIGHT_GRAY' }, 'seablue': { 'foreground': 'DARK_BLUE', 'background': 'LIGHT_GRAY' }, 'grass': { 'foreground': 'DARK_GREEN', 'background': 'LIGHT_GRAY' }, 'glamour': { 'foreground': 'DARK_MAGENTA', 'background': 'LIGHT_GRAY' }, 'lighty': { "foreground": "DEFAULT", "background": "DEFAULT", 'foreground_high': '#ffd', "background_high": '#008' }, None: { 'foreground': 'DEFAULT', 'background': 'DEFAULT' } } } def __init__(self, xyz): super(XYZPlugin, self).__init__(xyz) # Insert mode flag self._insert = False self._esc = Shortcut(sc=['ESCAPE']) self._marks = {} self._empty = lambda: None #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def prepare(self): self.panel = self.xyz.pm.load(":sys:panel") self.vfs = self.xyz.pm.load(":vfs:vfsutils") self.cmd = self.xyz.pm.load(":sys:cmd") cmd_mode_attr = self.xyz.skin.attr((self.ns.pfull,), "command_mode") self.insert_mode_attrf = self.cmd.get_attr_f() self.cmd_mode_attrf = lambda _: cmd_mode_attr self.toggle_insert_mode(False) def cd_parent(): self.panel.chdir(XYZ.macro("ACT_BASE")) return self._empty self.keys = [ (XYZ.kbd("i"), lambda _: self.toggle_insert_mode), (XYZ.kbd("I"), lambda _: self.toggle_insert_mode), (XYZ.kbd("j"), lambda _: self.panel.entry_next), (XYZ.kbd("l"), lambda _: self.panel.action), (XYZ.kbd("h"), lambda _: cd_parent), (XYZ.kbd("k"), lambda _: self.panel.entry_prev), (XYZ.kbd("/"), lambda _: self.panel.search_cycle), (XYZ.kbd("?"), lambda _: self.panel.search_backward), (XYZ.kbd("t"), lambda _: self.panel.toggle_tag), (XYZ.kbd("CTRL-g"), lambda _: self.xyz.pm.from_load(":vfs:fileinfo", "fileinfo")), (XYZ.kbd("d"), [ (XYZ.kbd("d"), lambda _: self.vfs.remove) ]), (XYZ.kbd("y"), [ (XYZ.kbd("y"), lambda _: self.vfs.copy) ]), (XYZ.kbd("G"), lambda _: self.panel.entry_bottom), (XYZ.kbd("g"), [ (XYZ.kbd("g"), lambda _: self.panel.entry_top) ]), (XYZ.kbd("m"), [ (lambda x: x.raw[0].isalpha(), lambda k: self.set_mark(k, self.panel.get_selected())) ]), (XYZ.kbd("`"), [ (lambda x: x.raw[0].isalpha(), lambda k: self.goto_mark(k)) ]) ] self.xyz.km.reader = self.reader #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def finalize(self): self.cmd.set_attr_f(self.insert_mode_attrf) self.xyz.km.reset_reader() #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def reader(self, raw, context=None, keys=None): """ Custom reader """ keys = keys or self.keys key = Shortcut(raw=raw) # Break insert mode if any if key == self._esc and self._insert: self.toggle_insert_mode(False) return self.reader(self.xyz.input.get(), context) # In non-insert treat keys as commands elif not self._insert: for k, v in keys: if (is_func(k) and k(key)) or k == key: if isinstance(v, list): return self.reader(self.xyz.input.get(), context, keys=v) else: return v(key) if not key.composite: return self._empty return self.xyz.km.default_reader(raw, context) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def toggle_insert_mode(self, value=None): """ Toggle insert mode """ # Toggle if value is None: self._insert = not self._insert else: self._insert = value if self._insert: self.cmd.set_attr_f(self.insert_mode_attrf) else: self.cmd.set_attr_f(self.cmd_mode_attrf) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def set_mark(self, sc, selected): """ Set current object path as mark """ self._marks[sc] = (XYZ.macro("ACT_CWD"), selected.name) return self._empty #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def goto_mark(self, sc): """ Chdir to mark """ path = self._marks.get(sc, None) if path is not None: dir, file = path try: self.panel.chdir(dir) self.panel.select(file) except Exception: pass return self._empty
Bawhoppen/-tg-station
refs/heads/master
tools/midi2piano/pyperclip/__init__.py
110
""" Pyperclip A cross-platform clipboard module for Python. (only handles plain text for now) By Al Sweigart al@inventwithpython.com BSD License Usage: import pyperclip pyperclip.copy('The text to be copied to the clipboard.') spam = pyperclip.paste() if not pyperclip.copy: print("Copy functionality unavailable!") On Windows, no additional modules are needed. On Mac, the module uses pbcopy and pbpaste, which should come with the os. On Linux, install xclip or xsel via package manager. For example, in Debian: sudo apt-get install xclip Otherwise on Linux, you will need the gtk or PyQt4 modules installed. gtk and PyQt4 modules are not available for Python 3, and this module does not work with PyGObject yet. """ __version__ = '1.5.27' import platform import os import subprocess from .clipboards import (init_osx_clipboard, init_gtk_clipboard, init_qt_clipboard, init_xclip_clipboard, init_xsel_clipboard, init_klipper_clipboard, init_no_clipboard) from .windows import init_windows_clipboard # `import PyQt4` sys.exit()s if DISPLAY is not in the environment. # Thus, we need to detect the presence of $DISPLAY manually # and not load PyQt4 if it is absent. HAS_DISPLAY = os.getenv("DISPLAY", False) CHECK_CMD = "where" if platform.system() == "Windows" else "which" def _executable_exists(name): return subprocess.call([CHECK_CMD, name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0 def determine_clipboard(): # Determine the OS/platform and set # the copy() and paste() functions accordingly. if 'cygwin' in platform.system().lower(): # FIXME: pyperclip currently does not support Cygwin, # see https://github.com/asweigart/pyperclip/issues/55 pass elif os.name == 'nt' or platform.system() == 'Windows': return init_windows_clipboard() if os.name == 'mac' or platform.system() == 'Darwin': return init_osx_clipboard() if HAS_DISPLAY: # Determine which command/module is installed, if any. try: import gtk # check if gtk is installed except ImportError: pass else: return init_gtk_clipboard() try: import PyQt4 # check if PyQt4 is installed except ImportError: pass else: return init_qt_clipboard() if _executable_exists("xclip"): return init_xclip_clipboard() if _executable_exists("xsel"): return init_xsel_clipboard() if _executable_exists("klipper") and _executable_exists("qdbus"): return init_klipper_clipboard() return init_no_clipboard() def set_clipboard(clipboard): global copy, paste clipboard_types = {'osx': init_osx_clipboard, 'gtk': init_gtk_clipboard, 'qt': init_qt_clipboard, 'xclip': init_xclip_clipboard, 'xsel': init_xsel_clipboard, 'klipper': init_klipper_clipboard, 'windows': init_windows_clipboard, 'no': init_no_clipboard} copy, paste = clipboard_types[clipboard]() copy, paste = determine_clipboard() __all__ = ["copy", "paste"]
nickpack/django-oscar
refs/heads/master
src/oscar/apps/analytics/models.py
27
from oscar.core.loading import is_model_registered from oscar.apps.analytics.abstract_models import ( AbstractProductRecord, AbstractUserRecord, AbstractUserProductView, AbstractUserSearch) __all__ = [] if not is_model_registered('analytics', 'ProductRecord'): class ProductRecord(AbstractProductRecord): pass __all__.append('ProductRecord') if not is_model_registered('analytics', 'UserRecord'): class UserRecord(AbstractUserRecord): pass __all__.append('UserRecord') if not is_model_registered('analytics', 'UserProductView'): class UserProductView(AbstractUserProductView): pass __all__.append('UserProductView') if not is_model_registered('analytics', 'UserSearch'): class UserSearch(AbstractUserSearch): pass __all__.append('UserSearch')
friedrich420/S4-GPE-AEL-Kernel-4.4.3
refs/heads/master
scripts/gcc-wrapper.py
364
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2011-2012, The Linux Foundation. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of The Linux Foundation 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, FITNESS FOR A PARTICULAR PURPOSE AND # NON-INFRINGEMENT 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. # Invoke gcc, looking for warnings, and causing a failure if there are # non-whitelisted warnings. import errno import re import os import sys import subprocess # Note that gcc uses unicode, which may depend on the locale. TODO: # force LANG to be set to en_US.UTF-8 to get consistent warnings. allowed_warnings = set([ "alignment.c:327", "mmu.c:602", "return_address.c:62", "swab.h:49", "SemaLambda.cpp:946", "CGObjCGNU.cpp:1414", "BugReporter.h:146", "RegionStore.cpp:1904", "SymbolManager.cpp:484", "RewriteObjCFoundationAPI.cpp:737", "RewriteObjCFoundationAPI.cpp:696", "CommentParser.cpp:394", "CommentParser.cpp:391", "CommentParser.cpp:356", "LegalizeDAG.cpp:3646", "IRBuilder.h:844", "DataLayout.cpp:193", "transport.c:653", "xt_socket.c:307", "xt_socket.c:161", "inet_hashtables.h:356", "xc4000.c:1049", "xc4000.c:1063", ]) # Capture the name of the object file, can find it. ofile = None warning_re = re.compile(r'''(.*/|)([^/]+\.[a-z]+:\d+):(\d+:)? warning:''') def interpret_warning(line): """Decode the message from gcc. The messages we care about have a filename, and a warning""" line = line.rstrip('\n') m = warning_re.match(line) if m and m.group(2) not in allowed_warnings: print "error, forbidden warning:", m.group(2) # If there is a warning, remove any object if it exists. if ofile: try: os.remove(ofile) except OSError: pass sys.exit(1) def run_gcc(): args = sys.argv[1:] # Look for -o try: i = args.index('-o') global ofile ofile = args[i+1] except (ValueError, IndexError): pass compiler = sys.argv[0] try: proc = subprocess.Popen(args, stderr=subprocess.PIPE) for line in proc.stderr: print line, interpret_warning(line) result = proc.wait() except OSError as e: result = e.errno if result == errno.ENOENT: print args[0] + ':',e.strerror print 'Is your PATH set correctly?' else: print ' '.join(args), str(e) return result if __name__ == '__main__': status = run_gcc() sys.exit(status)
dpac-vlsi/SynchroTrace
refs/heads/master
src/python/m5/util/terminal.py
83
# Copyright (c) 2011 Advanced Micro Devices, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of 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. # # Author: Steve Reinhardt import sys # Intended usage example: # # if force_colors: # from m5.util.terminal import termcap # elif no_colors: # from m5.util.terminal import no_termcap as termcap # else: # from m5.util.terminal import tty_termcap as termcap # print termcap.Blue + "This could be blue!" + termcap.Normal # ANSI color names in index order color_names = "Black Red Green Yellow Blue Magenta Cyan".split() # Character attribute capabilities. Note that not all terminals # support all of these capabilities, or support them # differently/meaningfully. For example: # # - In PuTTY (with the default settings), Dim has no effect, Standout # is the same as Reverse, and Blink does not blink but switches to a # gray background. # # Please feel free to add information about other terminals here. # capability_map = { 'Bold': 'bold', 'Dim': 'dim', 'Blink': 'blink', 'Underline': 'smul', 'Reverse': 'rev', 'Standout': 'smso', 'Normal': 'sgr0' } capability_names = capability_map.keys() def null_cap_string(s, *args): return '' try: import curses curses.setupterm() def cap_string(s, *args): cap = curses.tigetstr(s) if cap: return curses.tparm(cap, *args) else: return '' except: cap_string = null_cap_string class ColorStrings(object): def __init__(self, cap_string): for i, c in enumerate(color_names): setattr(self, c, cap_string('setaf', i)) for name, cap in capability_map.iteritems(): setattr(self, name, cap_string(cap)) termcap = ColorStrings(cap_string) no_termcap = ColorStrings(null_cap_string) if sys.stdout.isatty(): tty_termcap = termcap else: tty_termcap = no_termcap def get_termcap(use_colors = None): if use_colors: return termcap elif use_colors is None: # option unspecified; default behavior is to use colors iff isatty return tty_termcap else: return no_termcap def test_termcap(obj): for c_name in color_names: c_str = getattr(obj, c_name) print c_str + c_name + obj.Normal for attr_name in capability_names: if attr_name == 'Normal': continue attr_str = getattr(obj, attr_name) print attr_str + c_str + attr_name + " " + c_name + obj.Normal print obj.Bold + obj.Underline + \ c_name + "Bold Underline " + c + obj.Normal if __name__ == '__main__': print "=== termcap enabled ===" test_termcap(termcap) print termcap.Normal print "=== termcap disabled ===" test_termcap(no_termcap)
xmission/d-note
refs/heads/master
venv/lib/python2.7/site-packages/Naked/commands/locate.py
1
#!/usr/bin/env python # encoding: utf-8 import os from Naked.toolshed.system import stderr, exit_success class Locator: def __init__(self, needle): self.needle = needle self.location = self._display_location() def _display_location(self): if self.needle == 'main': main_path = os.path.join('<PROJECT>', 'lib', '<PROJECT>', 'app.py') print("app.py : " + main_path) exit_success() elif self.needle == "settings": settings_path = os.path.join('<PROJECT>', 'lib', '<PROJECT>','settings.py') print("settings.py : " + settings_path) exit_success() elif self.needle == "setup": setup_path = os.path.join('<PROJECT>', 'setup.py') print("setup.py : " + setup_path) exit_success() else: stderr("Unable to process the command. Use 'naked locate help' for more information.", 1) def help(): help_string = """ Naked locate Command Help ========================= The locate command identifies the file path to commonly used files in your project directory. USAGE naked locate <argument> SECONDARY COMMANDS main - the main application script file, app.py setup - the setup.py file settings - the project settings files, settings.py OPTIONS none EXAMPLE naked locate main""" print(help_string) exit_success() if __name__ == '__main__': pass
shumik/skencil-c
refs/heads/master
Sketch/UI/palette.py
1
# Sketch - A Python-based interactive drawing program # Copyright (C) 1997, 1998, 2001, 2003 by Bernhard Herzog # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import operator, os from types import StringType, TupleType, IntType from string import strip, split, atof, atoi import X from Sketch.const import CHANGED, COLOR1, COLOR2, CHANGED, VIEW, \ DROP_COLOR, CurDragColor from Sketch.warn import warn, INTERNAL, USER, pdebug, warn_tb from Sketch import Publisher, config, SketchError, _ from Sketch import CreateRGBColor, StandardColors, GraphicsDevice, Identity from tkext import PyWidget class NameInUse(SketchError): pass class RGBAlreadyStored(SketchError): pass class RGBPalette(Publisher): ignore_issue = 1 def __init__(self): self.entries = [] self.name_to_entry = {} self.rgb_to_entry = {} def Subscribe(self, channel, func, *args): apply(Publisher.Subscribe, (self, channel, func) + args) self.ignore_issue = 0 def update_dicts(self): self.name_to_entry = {} self.rgb_to_entry = {} for entry in self.entries: rgb, name = entry self.name_to_entry[name] = entry self.rgb_to_entry[rgb] = entry def AddEntry(self, rgb, name = None, rename = 0): if name: if self.name_to_entry.has_key(name): if self.name_to_entry[name] != (rgb, name): raise NameInUse if self.rgb_to_entry.has_key(rgb): if self.rgb_to_entry[rgb] != (rgb, name) and not rename: raise RGBAlreadyStored if not name: i = 0 base = 'Color ' name = base + `i` known = self.name_to_entry.has_key while known(name): i = i + 1 name = base + `i` entry = (rgb, name) self.entries.append(entry) self.name_to_entry[name] = entry self.rgb_to_entry[rgb] = entry self.issue(CHANGED) def __getitem__(self, idx): if type(idx) == StringType: return self.name_to_entry[idx] if type(idx) == TupleType: return self.rgb_to_entry[idx] if type(idx) == IntType: return self.entries[idx] def GetRGB(self, idx): return self[idx][0] def Colors(self): return map(operator.getitem, self.entries, [0] * len(self.entries)) def WriteFile(self, file): for entry in self.entries: (r, g, b), name = entry file.write('%g %g %g\t%s\n' % (r, g, b, name)) def __len__(self): return len(self.entries) # # Get the standard palette. User settable. # def read_standard_palette(filename): filename = os.path.join(config.std_res_dir, filename) return read_palette_file(filename) #minimalistic fallback: _mini_pal = [(0, 0, 0, 'Black'), (1, 1, 1, 'White')] def GetStandardPalette(): palette = read_standard_palette(config.preferences.palette) if not palette: warn(USER, _("Could not load palette %s; trying mini.spl..."), config.preferences.palette) palette = read_standard_palette('mini.spl') if not palette: warn(USER, _("Could not load palette mini.spl; reverting to black&white")) palette = RGBPalette() for r, g, b, name in _mini_pal: palette.AddEntry((r, g, b), name) return palette def LoadPalette(filename): return read_palette_file(filename) file_types = ((_("Skencil/Sketch Palette"), '.spl'), (_("All Files"), '*')) magic_rgb_palette = '##Sketch RGBPalette 0' magic_gimp_palette = 'GIMP Palette' def read_palette_file(filename): """Read the palette file filename""" file = open(filename) line = file.readline() line = strip(line) palette = None try: if line == magic_rgb_palette: palette = ReadRGBPaletteFile(filename) elif line == magic_gimp_palette: palette = Read_X_RGB_TXT(filename) except: warn_tb(USER) return palette def ReadRGBPaletteFile(filename): file = open(filename) line = file.readline() if line != magic_rgb_palette + '\n': file.close() raise ValueError, 'Invalid file type' palette = RGBPalette() linenr = 1 for line in file.readlines(): line = strip(line) linenr = linenr + 1 if not line or line[0] == '#': continue line = split(line, None, 3) if len(line) != 4: warn(INTERNAL, '%s:%d: wrong number of fields', filename, linenr) continue try: rgb = tuple(map(atof, line[:3])) except: warn(INTERNAL, '%s:%d: cannot parse rgb values', filename, linenr) continue for value in rgb: if value < 0 or value > 1.0: warn(INTERNAL, '%s:%d: value out of range', filename, linenr) continue name = strip(line[-1]) try: palette.AddEntry(rgb, name) except NameInUse: warn(INTERNAL, '%s:%d: color name already used', filename, linenr) continue except RGBAlreadyStored: warn(INTERNAL, '%s:%d: color already stored', filename, linenr) continue file.close() return palette def Read_X_RGB_TXT(filename): file = open(filename) palette = RGBPalette() linenr = 0 color_num = 0 for line in file.readlines(): line = strip(line) linenr = linenr + 1 if not line or line[0] in ('#', '!'): # an empty line or an X-style comment (!) or a GIMP comment (#) # GIMP's palette files have practically the same format as rgb.txt continue line = split(line, None, 3) if len(line) == 3: # the name is missing while 1: name = 'color ' + str(color_num) try: palette[name] used = 1 except KeyError: used = 0 if not used: line.append(name) break color_num = color_num + 1 if len(line) != 4: warn(INTERNAL, '%s:%d: wrong number of fields', filename, linenr) continue try: values = map(atoi, line[:3]) except: warn(INTERNAL, '%s:%d: cannot parse rgb values', filename, linenr) continue rgb = [] for value in values: value = round(value / 255.0, 3) if value < 0: value = 0.0 elif value > 1.0: value = 1.0 rgb.append(value) rgb = tuple(rgb) name = strip(line[-1]) try: palette.AddEntry(rgb, name) except NameInUse: warn(INTERNAL, '%s:%d: color name already used', filename, linenr) continue except RGBAlreadyStored: warn(INTERNAL, '%s:%d: color already stored', filename, linenr) continue file.close() return palette class PaletteWidget(PyWidget, Publisher): def __init__(self, master=None, palette = None, cell_size = 16, **kw): if not kw.has_key('height'): kw['height'] = cell_size apply(PyWidget.__init__, (self, master), kw) self.cell_size = cell_size self.num_cells = 0 self.gc_initialized = 0 self.gc = GraphicsDevice() self.gc.SetViewportTransform(1.0, Identity, Identity) self.start_idx = 0 self.palette = None if palette is None: palette = RGBPalette() self.SetPalette(palette) self.dragging = 0 self.bind('<ButtonPress-1>', self.press_1) self.bind('<Motion>', self.move_1) self.bind('<ButtonRelease-1>', self.release_1) self.bind('<ButtonRelease-2>', self.apply_color_2) def DestroyMethod(self): self.palette.Unsubscribe(CHANGED, self.palette_changed) Publisher.Destroy(self) def compute_num_cells(self): self.num_cells = self.tkwin.width / self.cell_size def MapMethod(self): self.compute_num_cells() self.issue(VIEW) if not self.gc_initialized: self.init_gc() self.gc_initialized = 1 def init_gc(self): self.gc.init_gc(self.tkwin) def get_color(self, x, y): if 0 <= x < self.tkwin.width and 0 <= y < self.tkwin.height: i = self.start_idx + x / self.cell_size if i < len(self.palette): return apply(CreateRGBColor, self.palette.GetRGB(i)) def release_1(self, event): try: if self.dragging: self.drop_color(event) else: self.apply_color_1(event) finally: self.dragging = 0 def drop_color(self, event): self['cursor'] = self.drag_old_cursor w = self.winfo_containing(event.x_root, event.y_root) while w and w != self: if __debug__: pdebug('DND', 'trying to drop on', w) try: accepts = w.accept_drop except AttributeError: accepts = () if DROP_COLOR in accepts: x = event.x_root - w.winfo_rootx() y = event.y_root - w.winfo_rooty() w.DropAt(x, y, DROP_COLOR, self.drag_start) break if w != w.winfo_toplevel(): parent = self.tk.call('winfo', 'parent', w._w) w = self.nametowidget(parent) else: break def apply_color_1(self, event): c = self.get_color(event.x, event.y) if c: self.issue(COLOR1, c) def apply_color_2(self, event): c = self.get_color(event.x, event.y) if c: self.issue(COLOR2, c) drag_start = (0, 0, 0) def press_1(self, event): self.drag_start = self.get_color(event.x, event.y) def move_1(self, event): if event.state & X.Button1Mask: if not self.dragging: self.dragging = 1 self.drag_old_cursor = self['cursor'] self['cursor'] = CurDragColor w = self.winfo_containing(event.x_root, event.y_root) def Palette(self): return self.palette def SetPalette(self, palette): if self.palette is not None: self.palette.Unsubscribe(CHANGED, self.palette_changed) self.palette = palette self.palette.Subscribe(CHANGED, self.palette_changed) self.palette_changed() def palette_changed(self): self.compute_num_cells() self.normalize_start() self.issue(VIEW) self.UpdateWhenIdle() def RedrawMethod(self, region = None): win = self.tkwin width = win.width height = win.height self.gc.StartDblBuffer() self.gc.SetFillColor(StandardColors.white) self.gc.FillRectangle(0, 0, width, height) x = 0 FillRectangle = self.gc.FillRectangle SetFillColor = self.gc.SetFillColor create_color = CreateRGBColor rgbs = self.palette.Colors() rgbs = rgbs[self.start_idx:self.start_idx + self.num_cells] for rgb in rgbs: SetFillColor(apply(create_color, rgb)) FillRectangle(x, 0, x + height, height) x = x + height self.gc.EndDblBuffer() def ResizedMethod(self, width, height): self.compute_num_cells() self.gc.WindowResized(width, height) self.normalize_start() self.UpdateWhenIdle() def normalize_start(self): length = len(self.palette) if self.start_idx < 0: self.start_idx = 0 if length < self.num_cells: self.start_idx = 0 elif length - self.start_idx < self.num_cells: self.start_idx = length - self.num_cells def CanScrollLeft(self): return self.start_idx > 0 def CanScrollRight(self): return len(self.palette) - self.start_idx > self.num_cells def ScrollXPages(self, count): length = self.tkwin.width / self.cell_size start = self.start_idx self.start_idx = self.start_idx + count * length self.normalize_start() if start != self.start_idx: self.UpdateWhenIdle() self.issue(VIEW) def ScrollXUnits(self, count): start = self.start_idx self.start_idx = self.start_idx + count self.normalize_start() if start != self.start_idx: self.UpdateWhenIdle() self.issue(VIEW)
buskjan/inetradio
refs/heads/master
lib/python3.5/site-packages/pip/_vendor/requests/packages/urllib3/util/connection.py
365
from __future__ import absolute_import import socket try: from select import poll, POLLIN except ImportError: # `poll` doesn't exist on OSX and other platforms poll = False try: from select import select except ImportError: # `select` doesn't exist on AppEngine. select = False def is_connection_dropped(conn): # Platform-specific """ Returns True if the connection is dropped and should be closed. :param conn: :class:`httplib.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us. """ sock = getattr(conn, 'sock', False) if sock is False: # Platform-specific: AppEngine return False if sock is None: # Connection already closed (such as by httplib). return True if not poll: if not select: # Platform-specific: AppEngine return False try: return select([sock], [], [], 0.0)[0] except socket.error: return True # This version is better on platforms that support it. p = poll() p.register(sock, POLLIN) for (fno, ev) in p.poll(0.0): if fno == sock.fileno(): # Either data is buffered (bad), or the connection is dropped. return True # This function is copied from socket.py in the Python 2.7 standard # library test suite. Added to its signature is only `socket_options`. # One additional modification is that we avoid binding to IPv6 servers # discovered in DNS if the system doesn't have IPv6 functionality. def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, socket_options=None): """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket instance before attempting to connect. If no *timeout* is supplied, the global default timeout setting returned by :func:`getdefaulttimeout` is used. If *source_address* is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of '' or port 0 tells the OS to use the default. """ host, port = address if host.startswith('['): host = host.strip('[]') err = None # Using the value from allowed_gai_family() in the context of getaddrinfo lets # us select whether to work with IPv4 DNS records, IPv6 records, or both. # The original create_connection function always returns all records. family = allowed_gai_family() for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket.socket(af, socktype, proto) # If provided, set socket level options before connecting. _set_socket_options(sock, socket_options) if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(sa) return sock except socket.error as e: err = e if sock is not None: sock.close() sock = None if err is not None: raise err raise socket.error("getaddrinfo returns an empty list") def _set_socket_options(sock, options): if options is None: return for opt in options: sock.setsockopt(*opt) def allowed_gai_family(): """This function is designed to work in the context of getaddrinfo, where family=socket.AF_UNSPEC is the default and will perform a DNS search for both IPv6 and IPv4 records.""" family = socket.AF_INET if HAS_IPV6: family = socket.AF_UNSPEC return family def _has_ipv6(host): """ Returns True if the system can bind an IPv6 address. """ sock = None has_ipv6 = False if socket.has_ipv6: # has_ipv6 returns true if cPython was compiled with IPv6 support. # It does not tell us if the system has IPv6 support enabled. To # determine that we must bind to an IPv6 address. # https://github.com/shazow/urllib3/pull/611 # https://bugs.python.org/issue658327 try: sock = socket.socket(socket.AF_INET6) sock.bind((host, 0)) has_ipv6 = True except Exception: pass if sock: sock.close() return has_ipv6 HAS_IPV6 = _has_ipv6('::1')
TRex22/Sick-Beard
refs/heads/master
sickbeard/version.py
17
SICKBEARD_VERSION = "master"