<commit_before># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright (c) 2010-2011, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# only, as published by the Free Software Foundation.
#
# OpenQuake 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 version 3 for more details
# (a copy is included in the LICENSE file that accompanied this code).
#
# You should have received a copy of the GNU Lesser General Public License
# version 3 along with OpenQuake.  If not, see
# <http://www.gnu.org/licenses/lgpl-3.0.txt> for a copy of the LGPLv3 License.

"""
Test related to code in openquake/utils/config.py
"""

import os
import unittest

from openquake.utils import config

class ConfigTestCase(unittest.TestCase):
    """Tests the behaviour of the utils.config.Config class."""

    def setUp(self):
        self.orig_env = os.environ.copy()
        os.environ.clear()

    def tearDown(self):
        os.environ.clear()
        os.environ.update(self.orig_env)

    def test_get_paths_with_global_env_var_set(self):
        """
        _get_paths() will honour the OQ_SITE_CFG_PATH environment
        variable.
        """
        os.environ["OQ_SITE_CFG_PATH"] = "/a/b/c/d"
        self.assertEqual(
            ["/a/b/c/d", "%s/openquake.cfg" % os.path.abspath(os.getcwd())],
            config.Config()._get_paths())

    def test_get_paths_with_local_env_var_set(self):
        """
        _get_paths() will honour the OQ_LOCAL_CFG_PATH
        variable.
        """
        os.environ["OQ_LOCAL_CFG_PATH"] = "/e/f/g/h"
        self.assertEqual(
            ["/etc/openquake/openquake.cfg", "/e/f/g/h"],
            config.Config()._get_paths())

    def test_get_paths_with_no_environ(self):
        """
        _get_paths() will return the hard-coded paths if the OQ_SITE_CFG_PATH
        and the OQ_LOCAL_CFG_PATH variables are not set.
        """
        self.assertEqual(
            ["/etc/openquake/openquake.cfg",
             "%s/openquake.cfg" % os.path.abspath(os.getcwd())],
            config.Config()._get_paths())
<commit_msg>added tests for Config()._load_from_file()<commit_after># -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright (c) 2010-2011, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# only, as published by the Free Software Foundation.
#
# OpenQuake 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 version 3 for more details
# (a copy is included in the LICENSE file that accompanied this code).
#
# You should have received a copy of the GNU Lesser General Public License
# version 3 along with OpenQuake.  If not, see
# <http://www.gnu.org/licenses/lgpl-3.0.txt> for a copy of the LGPLv3 License.

"""
Test related to code in openquake/utils/config.py
"""

import os
import textwrap
import unittest

from openquake.utils import config

from tests.helpers import TestMixin

class ConfigTestCase(TestMixin, unittest.TestCase):
    """Tests the behaviour of the utils.config.Config class."""

    def setUp(self):
        self.orig_env = os.environ.copy()
        os.environ.clear()

    def tearDown(self):
        os.environ.clear()
        os.environ.update(self.orig_env)

    def test_get_paths_with_global_env_var_set(self):
        """
        _get_paths() will honour the OQ_SITE_CFG_PATH environment
        variable.
        """
        os.environ["OQ_SITE_CFG_PATH"] = "/a/b/c/d"
        self.assertEqual(
            ["/a/b/c/d", "%s/openquake.cfg" % os.path.abspath(os.getcwd())],
            config.Config()._get_paths())

    def test_get_paths_with_local_env_var_set(self):
        """
        _get_paths() will honour the OQ_LOCAL_CFG_PATH
        variable.
        """
        os.environ["OQ_LOCAL_CFG_PATH"] = "/e/f/g/h"
        self.assertEqual(
            ["/etc/openquake/openquake.cfg", "/e/f/g/h"],
            config.Config()._get_paths())

    def test_get_paths_with_no_environ(self):
        """
        _get_paths() will return the hard-coded paths if the OQ_SITE_CFG_PATH
        and the OQ_LOCAL_CFG_PATH variables are not set.
        """
        self.assertEqual(
            ["/etc/openquake/openquake.cfg",
             "%s/openquake.cfg" % os.path.abspath(os.getcwd())],
            config.Config()._get_paths())

    def test_load_from_file_with_no_config_files(self):
        """In the absence of config files the `cfg` dict will be empty."""
        config.Config().cfg.clear()
        config.Config()._load_from_file()
        self.assertEqual([], config.Config().cfg.keys())

    def test_load_from_file_with_global(self):
        """The config data in the global file is loaded correctly."""
        content='''
            [A]
            a=1
            b=c

            [B]
            b=2'''
        site_path = self.touch(content=textwrap.dedent(content))
        os.environ["OQ_SITE_CFG_PATH"] = site_path
        config.Config().cfg.clear()
        config.Config()._load_from_file()
        self.assertEqual(["A", "B"], sorted(config.Config().cfg.keys()))
        self.assertEqual({"a": "1", "b": "c"}, config.Config().cfg.get("A"))
        self.assertEqual({"b": "2"}, config.Config().cfg.get("B"))

    def test_load_from_file_with_local(self):
        """The config data in the local file is loaded correctly."""
        content='''
            [C]
            c=3
            d=e

            [D]
            d=4'''
        local_path = self.touch(content=textwrap.dedent(content))
        os.environ["OQ_LOCAL_CFG_PATH"] = local_path
        config.Config().cfg.clear()
        config.Config()._load_from_file()
        self.assertEqual(["C", "D"], sorted(config.Config().cfg.keys()))
        self.assertEqual({"c": "3", "d": "e"}, config.Config().cfg.get("C"))
        self.assertEqual({"d": "4"}, config.Config().cfg.get("D"))

    def test_load_from_file_with_local_and_global(self):
        """
        The config data in the local and global files is loaded correctly.
        """
        content='''
            [A]
            a=1
            b=c

            [B]
            b=2'''
        site_path = self.touch(content=textwrap.dedent(content))
        os.environ["OQ_SITE_CFG_PATH"] = site_path
        content='''
            [C]
            c=3
            d=e

            [D]
            d=4'''
        local_path = self.touch(content=textwrap.dedent(content))
        os.environ["OQ_LOCAL_CFG_PATH"] = local_path
        config.Config().cfg.clear()
        config.Config()._load_from_file()
        self.assertEqual(["A", "B", "C", "D"],
                         sorted(config.Config().cfg.keys()))
        self.assertEqual({"a": "1", "b": "c"}, config.Config().cfg.get("A"))
        self.assertEqual({"b": "2"}, config.Config().cfg.get("B"))
        self.assertEqual({"c": "3", "d": "e"}, config.Config().cfg.get("C"))
        self.assertEqual({"d": "4"}, config.Config().cfg.get("D"))

    def test_load_from_file_with_local_overriding_global(self):
        """
        The config data in the local and global files is loaded correctly.
        The local data will override the global one.
        """
        content='''
            [A]
            a=1
            b=c

            [B]
            b=2'''
        site_path = self.touch(content=textwrap.dedent(content))
        os.environ["OQ_SITE_CFG_PATH"] = site_path
        content='''
            [A]
            a=2
            d=e

            [D]
            c=d-1
            d=4'''
        local_path = self.touch(content=textwrap.dedent(content))
        os.environ["OQ_LOCAL_CFG_PATH"] = local_path
        config.Config().cfg.clear()
        config.Config()._load_from_file()
        self.assertEqual(["A", "B", "D"],
                         sorted(config.Config().cfg.keys()))
        self.assertEqual({"a": "2", "b": "c", "d": "e"},
                         config.Config().cfg.get("A"))
        self.assertEqual({"b": "2"}, config.Config().cfg.get("B"))
        self.assertEqual({"c": "d-1", "d": "4"}, config.Config().cfg.get("D"))
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from datetime import datetime
import os

from django.utils import html
from django.utils._os import upath
from django.utils.encoding import force_text
from django.utils.unittest import TestCase

class TestUtilsHtml(TestCase):

    def check_output(self, function, value, output=None):
        """
        Check that function(value) equals output.  If output is None,
        check that function(value) equals value.
        """
        if output is None:
            output = value
        self.assertEqual(function(value), output)

    def test_escape(self):
        f = html.escape
        items = (
            ('&','&'),
            ('<', '<'),
            ('>', '>'),
            ('"', '"'),
            ("'", '''),
        )
        # Substitution patterns for testing the above items.
        patterns = ("%s", "asdf%sfdsa", "%s1", "1%sb")
        for value, output in items:
            for pattern in patterns:
                self.check_output(f, pattern % value, pattern % output)
            # Check repeated values.
            self.check_output(f, value * 2, output * 2)
        # Verify it doesn't double replace &.
        self.check_output(f, '<&', '<&')

    def test_format_html(self):
        self.assertEqual(
            html.format_html("{0} {1} {third} {fourth}",
                             "< Dangerous >",
                             html.mark_safe("safe"),
                             third="< dangerous again",
                             fourth=html.mark_safe("safe again")
                             ),
            "< Dangerous > safe < dangerous again safe again"
            )

    def test_linebreaks(self):
        f = html.linebreaks
        items = (
            ("para1\n\npara2\r\rpara3", "
para1
\n\n
para2
\n\n
para3
"),
            ("para1\nsub1\rsub2\n\npara2", "
para1
sub1
sub2
\n\n
para2
"),
            ("para1\r\n\r\npara2\rsub1\r\rpara4", "
para1
\n\n
para2
sub1
\n\n
para4
"),
            ("para1\tmore\n\npara2", "
para1\tmore
\n\n
para2
"),
        )
        for value, output in items:
            self.check_output(f, value, output)

    def test_strip_tags(self):
        f = html.strip_tags
        items = (
            ('
See: 'é is an apostrophe followed by e acute
',
             'See: 'é is an apostrophe followed by e acute'),
            ('<adf>a', 'a'),
            ('</adf>a', 'a'),
            ('<asdf><asdf>e', 'e'),
            ('hi, <f x', 'hi, <f x'),
            ('234<235, right?', '234<235, right?'),
            ('a4<a5 right?', 'a4<a5 right?'),
            ('b7>b2!', 'b7>b2!'),
            ('</fe', '</fe'),
            ('<x>b<y>', 'b'),
            ('a<p onclick="alert(\'<test>\')">b
c', 'abc'),
            ('a
b
c', 'abc'),
            ('de
f', 'def'),
            ('foobar', 'foobar'),
            ('<script>test</script>', 'test'),
            ('&h', 'alert()&h'),
        )
        for value, output in items:
            self.check_output(f, value, output)

        # Test with more lengthy content (also catching performance regressions)
        for filename in ('strip_tags1.html', 'strip_tags2.txt'):
            path = os.path.join(os.path.dirname(upath(__file__)), 'files', filename)
            with open(path, 'r') as fp:
                content = force_text(fp.read())
                start = datetime.now()
                stripped = html.strip_tags(content)
                elapsed = datetime.now() - start
            self.assertEqual(elapsed.seconds, 0)
            self.assertIn("Please try again.", stripped)
            self.assertNotIn('<', stripped)

    def test_strip_spaces_between_tags(self):
        f = html.strip_spaces_between_tags
        # Strings that should come out untouched.
        items = (' <adf>', '<adf> ', ' </adf> ', ' <f> x</f>')
        for value in items:
            self.check_output(f, value)
        # Strings that have spaces to strip.
        items = (
            ('<d> </d>', '<d></d>'),
            ('
hello
\n
 world
', '
hello

 world
'),
            ('\n
\t
\n

\n', '\n

\n'),
        )
        for value, output in items:
            self.check_output(f, value, output)

    def test_strip_entities(self):
        f = html.strip_entities
        # Strings that should come out untouched.
        values = ("&", "&a", "&a", "a&#a")
        for value in values:
            self.check_output(f, value)
        # Valid entities that should be stripped from the patterns.
        entities = ("", "�", "&a;", "&fdasdfasdfasdf;")
        patterns = (
            ("asdf %(entity)s ", "asdf  "),
            ("%(entity)s%(entity)s", ""),
            ("&%(entity)s%(entity)s", "&"),
            ("%(entity)s3", "3"),
        )
        for entity in entities:
            for in_pattern, output in patterns:
                self.check_output(f, in_pattern % {'entity': entity}, output)

    def test_fix_ampersands(self):
        f = html.fix_ampersands
        # Strings without ampersands or with ampersands already encoded.
        values = ("a", "b", "&a;", "& &x; ", "asdf")
        patterns = (
            ("%s", "%s"),
            ("&%s", "&%s"),
            ("&%s&", "&%s&"),
        )
        for value in values:
            for in_pattern, out_pattern in patterns:
                self.check_output(f, in_pattern % value, out_pattern % value)
        # Strings with ampersands that need encoding.
        items = (
            ("&#;", "&#;"),
            ("&#875 ;", "&#875 ;"),
            ("&#4abc;", "&#4abc;"),
        )
        for value, output in items:
            self.check_output(f, value, output)

    def test_escapejs(self):
        f = html.escapejs
        items = (
            ('"double quotes" and \'single quotes\'', '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027'),
            (r'\ : backslashes, too', '\\u005C : backslashes, too'),
            ('and lots of whitespace: \r\n\t\v\f\b', 'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008'),
            (r'', '\\u003Cscript\\u003Eand this\\u003C/script\\u003E'),
            ('paragraph separator:\u2029and line separator:\u2028', 'paragraph separator:\\u2029and line separator:\\u2028'),
        )
        for value, output in items:
            self.check_output(f, value, output)

    def test_clean_html(self):
        f = html.clean_html
        items = (
            ('
I believe in semantic markup!
', '
I believe in semantic markup!
'),
            ('I escape & I don\'t target', 'I escape & I don\'t target'),
            ('
I kill whitespace

', '
I kill whitespace
'),
            # also a regression test for #7267: this used to raise an UnicodeDecodeError
            ('
* foo

* bar
', '
\n
 foo

 bar
\n
'),
        )
        for value, output in items:
            self.check_output(f, value, output)

    def test_remove_tags(self):
        f = html.remove_tags
        items = (
            ("Yes", "b i", "Yes"),
            ("x
y
", "a b", "x
y
"),
        )
        for value, tags, output in items:
            self.assertEqual(f(value, tags), output)

    def test_smart_urlquote(self):
        quote = html.smart_urlquote
        # Ensure that IDNs are properly quoted
        self.assertEqual(quote('http://öäü.com/'), 'http://xn--4ca9at.com/')
        self.assertEqual(quote('http://öäü.com/öäü/'), 'http://xn--4ca9at.com/%C3%B6%C3%A4%C3%BC/')
        # Ensure that everything unsafe is quoted, !*'();:@&=+$,/?#[]~ is considered safe as per RFC
        self.assertEqual(quote('http://example.com/path/öäü/'), 'http://example.com/path/%C3%B6%C3%A4%C3%BC/')
        self.assertEqual(quote('http://example.com/%C3%B6/ä/'), 'http://example.com/%C3%B6/%C3%A4/')
        self.assertEqual(quote('http://example.com/?x=1&y=2'), 'http://example.com/?x=1&y=2')
<commit_msg>[1.6.x] Removed a strip_tags test for older Python versions<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from datetime import datetime
import os

from django.utils import html
from django.utils._os import upath
from django.utils.encoding import force_text
from django.utils.unittest import TestCase

class TestUtilsHtml(TestCase):

    def check_output(self, function, value, output=None):
        """
        Check that function(value) equals output.  If output is None,
        check that function(value) equals value.
        """
        if output is None:
            output = value
        self.assertEqual(function(value), output)

    def test_escape(self):
        f = html.escape
        items = (
            ('&','&'),
            ('<', '<'),
            ('>', '>'),
            ('"', '"'),
            ("'", '''),
        )
        # Substitution patterns for testing the above items.
        patterns = ("%s", "asdf%sfdsa", "%s1", "1%sb")
        for value, output in items:
            for pattern in patterns:
                self.check_output(f, pattern % value, pattern % output)
            # Check repeated values.
            self.check_output(f, value * 2, output * 2)
        # Verify it doesn't double replace &.
        self.check_output(f, '<&', '<&')

    def test_format_html(self):
        self.assertEqual(
            html.format_html("{0} {1} {third} {fourth}",
                             "< Dangerous >",
                             html.mark_safe("safe"),
                             third="< dangerous again",
                             fourth=html.mark_safe("safe again")
                             ),
            "< Dangerous > safe < dangerous again safe again"
            )

    def test_linebreaks(self):
        f = html.linebreaks
        items = (
            ("para1\n\npara2\r\rpara3", "
para1
\n\n
para2
\n\n
para3
"),
            ("para1\nsub1\rsub2\n\npara2", "
para1
sub1
sub2
\n\n
para2
"),
            ("para1\r\n\r\npara2\rsub1\r\rpara4", "
para1
\n\n
para2
sub1
\n\n
para4
"),
            ("para1\tmore\n\npara2", "
para1\tmore
\n\n
para2
"),
        )
        for value, output in items:
            self.check_output(f, value, output)

    def test_strip_tags(self):
        from django.utils.html_parser import use_workaround
        f = html.strip_tags
        items = (
            ('
See: 'é is an apostrophe followed by e acute
',
             'See: 'é is an apostrophe followed by e acute'),
            ('<adf>a', 'a'),
            ('</adf>a', 'a'),
            ('<asdf><asdf>e', 'e'),
            ('hi, <f x', 'hi, <f x'),
            ('234<235, right?', '234<235, right?'),
            ('a4<a5 right?', 'a4<a5 right?'),
            ('b7>b2!', 'b7>b2!'),
            ('</fe', '</fe'),
            ('<x>b<y>', 'b'),
            ('a<p onclick="alert(\'<test>\')">b
c', 'abc'),
            ('a
b
c', 'abc'),
            ('de
f', 'def'),
            ('foobar', 'foobar'),
            ('&h', 'alert()&h'),
        )
        if not use_workaround:
            items += (('<script>test</script>', 'test'),)
        for value, output in items:
            self.check_output(f, value, output)

        # Test with more lengthy content (also catching performance regressions)
        for filename in ('strip_tags1.html', 'strip_tags2.txt'):
            path = os.path.join(os.path.dirname(upath(__file__)), 'files', filename)
            with open(path, 'r') as fp:
                content = force_text(fp.read())
                start = datetime.now()
                stripped = html.strip_tags(content)
                elapsed = datetime.now() - start
            self.assertEqual(elapsed.seconds, 0)
            self.assertIn("Please try again.", stripped)
            self.assertNotIn('<', stripped)

    def test_strip_spaces_between_tags(self):
        f = html.strip_spaces_between_tags
        # Strings that should come out untouched.
        items = (' <adf>', '<adf> ', ' </adf> ', ' <f> x</f>')
        for value in items:
            self.check_output(f, value)
        # Strings that have spaces to strip.
        items = (
            ('<d> </d>', '<d></d>'),
            ('
hello
\n
 world
', '
hello

 world
'),
            ('\n
\t
\n

\n', '\n

\n'),
        )
        for value, output in items:
            self.check_output(f, value, output)

    def test_strip_entities(self):
        f = html.strip_entities
        # Strings that should come out untouched.
        values = ("&", "&a", "&a", "a&#a")
        for value in values:
            self.check_output(f, value)
        # Valid entities that should be stripped from the patterns.
        entities = ("", "�", "&a;", "&fdasdfasdfasdf;")
        patterns = (
            ("asdf %(entity)s ", "asdf  "),
            ("%(entity)s%(entity)s", ""),
            ("&%(entity)s%(entity)s", "&"),
            ("%(entity)s3", "3"),
        )
        for entity in entities:
            for in_pattern, output in patterns:
                self.check_output(f, in_pattern % {'entity': entity}, output)

    def test_fix_ampersands(self):
        f = html.fix_ampersands
        # Strings without ampersands or with ampersands already encoded.
        values = ("a", "b", "&a;", "& &x; ", "asdf")
        patterns = (
            ("%s", "%s"),
            ("&%s", "&%s"),
            ("&%s&", "&%s&"),
        )
        for value in values:
            for in_pattern, out_pattern in patterns:
                self.check_output(f, in_pattern % value, out_pattern % value)
        # Strings with ampersands that need encoding.
        items = (
            ("&#;", "&#;"),
            ("&#875 ;", "&#875 ;"),
            ("&#4abc;", "&#4abc;"),
        )
        for value, output in items:
            self.check_output(f, value, output)

    def test_escapejs(self):
        f = html.escapejs
        items = (
            ('"double quotes" and \'single quotes\'', '\\u0022double quotes\\u0022 and \\u0027single quotes\\u0027'),
            (r'\ : backslashes, too', '\\u005C : backslashes, too'),
            ('and lots of whitespace: \r\n\t\v\f\b', 'and lots of whitespace: \\u000D\\u000A\\u0009\\u000B\\u000C\\u0008'),
            (r'', '\\u003Cscript\\u003Eand this\\u003C/script\\u003E'),
            ('paragraph separator:\u2029and line separator:\u2028', 'paragraph separator:\\u2029and line separator:\\u2028'),
        )
        for value, output in items:
            self.check_output(f, value, output)

    def test_clean_html(self):
        f = html.clean_html
        items = (
            ('
I believe in semantic markup!
', '
I believe in semantic markup!
'),
            ('I escape & I don\'t target', 'I escape & I don\'t target'),
            ('
I kill whitespace

', '
I kill whitespace
'),
            # also a regression test for #7267: this used to raise an UnicodeDecodeError
            ('
* foo

* bar
', '
\n
 foo

 bar
\n
'),
        )
        for value, output in items:
            self.check_output(f, value, output)

    def test_remove_tags(self):
        f = html.remove_tags
        items = (
            ("Yes", "b i", "Yes"),
            ("x
y
", "a b", "x
y
"),
        )
        for value, tags, output in items:
            self.assertEqual(f(value, tags), output)

    def test_smart_urlquote(self):
        quote = html.smart_urlquote
        # Ensure that IDNs are properly quoted
        self.assertEqual(quote('http://öäü.com/'), 'http://xn--4ca9at.com/')
        self.assertEqual(quote('http://öäü.com/öäü/'), 'http://xn--4ca9at.com/%C3%B6%C3%A4%C3%BC/')
        # Ensure that everything unsafe is quoted, !*'();:@&=+$,/?#[]~ is considered safe as per RFC
        self.assertEqual(quote('http://example.com/path/öäü/'), 'http://example.com/path/%C3%B6%C3%A4%C3%BC/')
        self.assertEqual(quote('http://example.com/%C3%B6/ä/'), 'http://example.com/%C3%B6/%C3%A4/')
        self.assertEqual(quote('http://example.com/?x=1&y=2'), 'http://example.com/?x=1&y=2')
<|endoftext|>


<commit_before>import unittest
import sys
import os
import _testcapi
from test import test_support
from subprocess import Popen, PIPE

# Skip this test if the _tkinter module wasn't built.
_tkinter = test_support.import_module('_tkinter')

from Tkinter import Tcl
from _tkinter import TclError

tcl_version = _tkinter.TCL_VERSION.split('.')
try:
    for i in range(len(tcl_version)):
        tcl_version[i] = int(tcl_version[i])
except ValueError:
    pass
tcl_version = tuple(tcl_version)

class TkinterTest(unittest.TestCase):

    def testFlattenLen(self):
        # flatten(<object with no length>)
        self.assertRaises(TypeError, _tkinter._flatten, True)

class TclTest(unittest.TestCase):

    def setUp(self):
        self.interp = Tcl()
        self.wantobjects = self.interp.tk.wantobjects()

    def testEval(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.eval('set a'),'1')

    def testEvalException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'set a')

    def testEvalException2(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'this is wrong')

    def testCall(self):
        tcl = self.interp
        tcl.call('set','a','1')
        self.assertEqual(tcl.call('set','a'),'1')

    def testCallException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.call,'set','a')

    def testCallException2(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.call,'this','is','wrong')

    def testSetVar(self):
        tcl = self.interp
        tcl.setvar('a','1')
        self.assertEqual(tcl.eval('set a'),'1')

    def testSetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)','1')
        self.assertEqual(tcl.eval('set a(1)'),'1')

    def testGetVar(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.getvar('a'),'1')

    def testGetVarArray(self):
        tcl = self.interp
        tcl.eval('set a(1) 1')
        self.assertEqual(tcl.getvar('a(1)'),'1')

    def testGetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.getvar,'a')

    def testGetVarArrayException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.getvar,'a(1)')

    def testUnsetVar(self):
        tcl = self.interp
        tcl.setvar('a',1)
        self.assertEqual(tcl.eval('info exists a'),'1')
        tcl.unsetvar('a')
        self.assertEqual(tcl.eval('info exists a'),'0')

    def testUnsetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)',1)
        tcl.setvar('a(2)',2)
        self.assertEqual(tcl.eval('info exists a(1)'),'1')
        self.assertEqual(tcl.eval('info exists a(2)'),'1')
        tcl.unsetvar('a(1)')
        self.assertEqual(tcl.eval('info exists a(1)'),'0')
        self.assertEqual(tcl.eval('info exists a(2)'),'1')

    def testUnsetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.unsetvar,'a')

    def testEvalFile(self):
        tcl = self.interp
        filename = "testEvalFile.tcl"
        fd = open(filename,'w')
        script = """set a 1
        set b 2
        set c [ expr $a + $b ]
        """
        fd.write(script)
        fd.close()
        tcl.evalfile(filename)
        os.remove(filename)
        self.assertEqual(tcl.eval('set a'),'1')
        self.assertEqual(tcl.eval('set b'),'2')
        self.assertEqual(tcl.eval('set c'),'3')

    def testEvalFileException(self):
        tcl = self.interp
        filename = "doesnotexists"
        try:
            os.remove(filename)
        except Exception,e:
            pass
        self.assertRaises(TclError,tcl.evalfile,filename)

    def testPackageRequireException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'package require DNE')

    @unittest.skipUnless(sys.platform == 'win32', "only applies to Windows")
    def testLoadWithUNC(self):
        # Build a UNC path from the regular path.
        # Something like
        #   \\%COMPUTERNAME%\c$\python27\python.exe

        fullname = os.path.abspath(sys.executable)
        if fullname[1] != ':':
            self.skipTest('unusable path: %r' % fullname)
        unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'],
                                    fullname[0],
                                    fullname[3:])

        with test_support.EnvironmentVarGuard() as env:
            env.unset("TCL_LIBRARY")
            cmd = '%s -c "import Tkinter; print Tkinter"' % (unc_name,)

            try:
                p = Popen(cmd, stdout=PIPE, stderr=PIPE)
            except WindowsError as e:
                if e.winerror == 5:
                    self.skipTest('Not permitted to start the child process')
                else:
                    raise

            out_data, err_data = p.communicate()

            msg = '\n\n'.join(['"Tkinter.py" not in output',
                               'Command:', cmd,
                               'stdout:', out_data,
                               'stderr:', err_data])

            self.assertIn('Tkinter.py', out_data, msg)

            self.assertEqual(p.wait(), 0, 'Non-zero exit code')

    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True if self.wantobjects else '1')
        self.assertEqual(passValue(False), False if self.wantobjects else '0')
        self.assertEqual(passValue(u'string'), u'string')
        self.assertEqual(passValue(u'string\u20ac'), u'string\u20ac')
        for i in (0, 1, -1, int(2**31-1), int(-2**31)):
            self.assertEqual(passValue(i), i if self.wantobjects else str(i))
        for f in (0.0, 1.0, -1.0, 1//3, 1/3.0,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            if self.wantobjects:
                self.assertEqual(passValue(f), f)
            else:
                self.assertEqual(float(passValue(f)), f)
        if self.wantobjects:
            f = passValue(float('nan'))
            self.assertNotEqual(f, f)
            self.assertEqual(passValue(float('inf')), float('inf'))
            self.assertEqual(passValue(-float('inf')), -float('inf'))
        else:
            f = float(passValue(float('nan')))
            self.assertNotEqual(f, f)
            self.assertEqual(float(passValue(float('inf'))), float('inf'))
            self.assertEqual(float(passValue(-float('inf'))), -float('inf'))
        self.assertEqual(passValue((1, '2', (3.4,))),
                         (1, '2', (3.4,)) if self.wantobjects else '1 2 3.4')

    def test_user_command(self):
        result = []
        def testfunc(arg):
            result.append(arg)
            return arg
        self.interp.createcommand('testfunc', testfunc)
        def check(value, expected):
            del result[:]
            self.assertEqual(self.interp.call('testfunc', value), expected)
            self.assertEqual(result, [expected])

        check(True, '1')
        check(False, '0')
        check('string', 'string')
        check('string\xbd', 'string\xbd')
        check('string\u20ac', 'string\u20ac')
        for i in (0, 1, -1, 2**31-1, -2**31):
            check(i, str(i))
        for f in (0.0, 1.0, -1.0, 1/3,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            check(f, repr(f))
        check(float('nan'), 'NaN')
        check(float('inf'), 'Inf')
        check(-float('inf'), '-Inf')
        check((), '')
        check((1, (2,), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}')

    def test_splitlist(self):
        splitlist = self.interp.tk.splitlist
        call = self.interp.tk.call
        self.assertRaises(TypeError, splitlist)
        self.assertRaises(TypeError, splitlist, 'a', 'b')
        self.assertRaises(TypeError, splitlist, 2)
        testcases = [
            ('2', ('2',)),
            ('', ()),
            ('{}', ('',)),
            ('""', ('',)),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (u'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \xe2\x82\xac', ('a', '\xe2\x82\xac')),
            (u'a \u20ac', ('a', '\xe2\x82\xac')),
            ('a {b c}', ('a', 'b c')),
            (r'a b\ c', ('a', 'b c')),
            (('a', 'b c'), ('a', 'b c')),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            ((), ()),
            (call('list', 1, '2', (3.4,)),
                (1, '2', (3.4,)) if self.wantobjects else
                ('1', '2', '3.4')),
        ]
        if tcl_version >= (8, 5):
            testcases += [
                (call('dict', 'create', 1, u'\u20ac', '\xe2\x82\xac', (3.4,)),
                    (1, u'\u20ac', u'\u20ac', (3.4,)) if self.wantobjects else
                    ('1', '\xe2\x82\xac', '\xe2\x82\xac', '3.4')),
            ]
        for arg, res in testcases:
            self.assertEqual(splitlist(arg), res)
        self.assertRaises(TclError, splitlist, '{')

    def test_split(self):
        split = self.interp.tk.split
        call = self.interp.tk.call
        self.assertRaises(TypeError, split)
        self.assertRaises(TypeError, split, 'a', 'b')
        self.assertRaises(TypeError, split, 2)
        testcases = [
            ('2', '2'),
            ('', ''),
            ('{}', ''),
            ('""', ''),
            ('{', '{'),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (u'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \xe2\x82\xac', ('a', '\xe2\x82\xac')),
            (u'a \u20ac', ('a', '\xe2\x82\xac')),
            ('a {b c}', ('a', ('b', 'c'))),
            (r'a b\ c', ('a', ('b', 'c'))),
            (('a', 'b c'), ('a', ('b', 'c'))),
            (('a', u'b c'), ('a', ('b', 'c'))),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            (('a', (2, 3.4)), ('a', (2, 3.4))),
            ((), ()),
            (call('list', 1, '2', (3.4,)),
                (1, '2', (3.4,)) if self.wantobjects else
                ('1', '2', '3.4')),
        ]
        if tcl_version >= (8, 5):
            testcases += [
                (call('dict', 'create', 12, u'\u20ac', '\xe2\x82\xac', (3.4,)),
                    (12, u'\u20ac', u'\u20ac', (3.4,)) if self.wantobjects else
                    ('12', '\xe2\x82\xac', '\xe2\x82\xac', '3.4')),
            ]
        for arg, res in testcases:
            self.assertEqual(split(arg), res)

class BigmemTclTest(unittest.TestCase):

    def setUp(self):
        self.interp = Tcl()

    @unittest.skipUnless(_testcapi.INT_MAX < _testcapi.PY_SSIZE_T_MAX,
                         "needs UINT_MAX < SIZE_MAX")
    @test_support.precisionbigmemtest(size=_testcapi.INT_MAX + 1, memuse=5,
                                      dry_run=False)
    def test_huge_string(self, size):
        value = ' ' * size
        self.assertRaises(OverflowError, self.interp.call, 'set', '_', value)

def setUpModule():
    if test_support.verbose:
        tcl = Tcl()
        print 'patchlevel =', tcl.call('info', 'patchlevel')

def test_main():
    test_support.run_unittest(TclTest, TkinterTest, BigmemTclTest)

if __name__ == "__main__":
    test_main()
<commit_msg>Try to fix test_user_command on OpenSolaris where floats can have different string representation in Tcl and Python.<commit_after>import unittest
import sys
import os
import _testcapi
from test import test_support
from subprocess import Popen, PIPE

# Skip this test if the _tkinter module wasn't built.
_tkinter = test_support.import_module('_tkinter')

from Tkinter import Tcl
from _tkinter import TclError

tcl_version = _tkinter.TCL_VERSION.split('.')
try:
    for i in range(len(tcl_version)):
        tcl_version[i] = int(tcl_version[i])
except ValueError:
    pass
tcl_version = tuple(tcl_version)

class TkinterTest(unittest.TestCase):

    def testFlattenLen(self):
        # flatten(<object with no length>)
        self.assertRaises(TypeError, _tkinter._flatten, True)

class TclTest(unittest.TestCase):

    def setUp(self):
        self.interp = Tcl()
        self.wantobjects = self.interp.tk.wantobjects()

    def testEval(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.eval('set a'),'1')

    def testEvalException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'set a')

    def testEvalException2(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'this is wrong')

    def testCall(self):
        tcl = self.interp
        tcl.call('set','a','1')
        self.assertEqual(tcl.call('set','a'),'1')

    def testCallException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.call,'set','a')

    def testCallException2(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.call,'this','is','wrong')

    def testSetVar(self):
        tcl = self.interp
        tcl.setvar('a','1')
        self.assertEqual(tcl.eval('set a'),'1')

    def testSetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)','1')
        self.assertEqual(tcl.eval('set a(1)'),'1')

    def testGetVar(self):
        tcl = self.interp
        tcl.eval('set a 1')
        self.assertEqual(tcl.getvar('a'),'1')

    def testGetVarArray(self):
        tcl = self.interp
        tcl.eval('set a(1) 1')
        self.assertEqual(tcl.getvar('a(1)'),'1')

    def testGetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.getvar,'a')

    def testGetVarArrayException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.getvar,'a(1)')

    def testUnsetVar(self):
        tcl = self.interp
        tcl.setvar('a',1)
        self.assertEqual(tcl.eval('info exists a'),'1')
        tcl.unsetvar('a')
        self.assertEqual(tcl.eval('info exists a'),'0')

    def testUnsetVarArray(self):
        tcl = self.interp
        tcl.setvar('a(1)',1)
        tcl.setvar('a(2)',2)
        self.assertEqual(tcl.eval('info exists a(1)'),'1')
        self.assertEqual(tcl.eval('info exists a(2)'),'1')
        tcl.unsetvar('a(1)')
        self.assertEqual(tcl.eval('info exists a(1)'),'0')
        self.assertEqual(tcl.eval('info exists a(2)'),'1')

    def testUnsetVarException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.unsetvar,'a')

    def testEvalFile(self):
        tcl = self.interp
        filename = "testEvalFile.tcl"
        fd = open(filename,'w')
        script = """set a 1
        set b 2
        set c [ expr $a + $b ]
        """
        fd.write(script)
        fd.close()
        tcl.evalfile(filename)
        os.remove(filename)
        self.assertEqual(tcl.eval('set a'),'1')
        self.assertEqual(tcl.eval('set b'),'2')
        self.assertEqual(tcl.eval('set c'),'3')

    def testEvalFileException(self):
        tcl = self.interp
        filename = "doesnotexists"
        try:
            os.remove(filename)
        except Exception,e:
            pass
        self.assertRaises(TclError,tcl.evalfile,filename)

    def testPackageRequireException(self):
        tcl = self.interp
        self.assertRaises(TclError,tcl.eval,'package require DNE')

    @unittest.skipUnless(sys.platform == 'win32', "only applies to Windows")
    def testLoadWithUNC(self):
        # Build a UNC path from the regular path.
        # Something like
        #   \\%COMPUTERNAME%\c$\python27\python.exe

        fullname = os.path.abspath(sys.executable)
        if fullname[1] != ':':
            self.skipTest('unusable path: %r' % fullname)
        unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'],
                                    fullname[0],
                                    fullname[3:])

        with test_support.EnvironmentVarGuard() as env:
            env.unset("TCL_LIBRARY")
            cmd = '%s -c "import Tkinter; print Tkinter"' % (unc_name,)

            try:
                p = Popen(cmd, stdout=PIPE, stderr=PIPE)
            except WindowsError as e:
                if e.winerror == 5:
                    self.skipTest('Not permitted to start the child process')
                else:
                    raise

            out_data, err_data = p.communicate()

            msg = '\n\n'.join(['"Tkinter.py" not in output',
                               'Command:', cmd,
                               'stdout:', out_data,
                               'stderr:', err_data])

            self.assertIn('Tkinter.py', out_data, msg)

            self.assertEqual(p.wait(), 0, 'Non-zero exit code')

    def test_passing_values(self):
        def passValue(value):
            return self.interp.call('set', '_', value)

        self.assertEqual(passValue(True), True if self.wantobjects else '1')
        self.assertEqual(passValue(False), False if self.wantobjects else '0')
        self.assertEqual(passValue(u'string'), u'string')
        self.assertEqual(passValue(u'string\u20ac'), u'string\u20ac')
        for i in (0, 1, -1, int(2**31-1), int(-2**31)):
            self.assertEqual(passValue(i), i if self.wantobjects else str(i))
        for f in (0.0, 1.0, -1.0, 1//3, 1/3.0,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            if self.wantobjects:
                self.assertEqual(passValue(f), f)
            else:
                self.assertEqual(float(passValue(f)), f)
        if self.wantobjects:
            f = passValue(float('nan'))
            self.assertNotEqual(f, f)
            self.assertEqual(passValue(float('inf')), float('inf'))
            self.assertEqual(passValue(-float('inf')), -float('inf'))
        else:
            f = float(passValue(float('nan')))
            self.assertNotEqual(f, f)
            self.assertEqual(float(passValue(float('inf'))), float('inf'))
            self.assertEqual(float(passValue(-float('inf'))), -float('inf'))
        self.assertEqual(passValue((1, '2', (3.4,))),
                         (1, '2', (3.4,)) if self.wantobjects else '1 2 3.4')

    def test_user_command(self):
        result = []
        def testfunc(arg):
            result.append(arg)
            return arg
        self.interp.createcommand('testfunc', testfunc)
        def check(value, expected, conv=lambda x: x):
            del result[:]
            r = self.interp.call('testfunc', value)
            self.assertEqual(len(result), 1)
            self.assertIsInstance(result[0], str)
            self.assertEqual(conv(result[0]), expected)
            self.assertIsInstance(r, str)
            self.assertEqual(conv(r), expected)

        check(True, '1')
        check(False, '0')
        check('string', 'string')
        check('string\xbd', 'string\xbd')
        check('string\u20ac', 'string\u20ac')
        for i in (0, 1, -1, 2**31-1, -2**31):
            check(i, str(i))
        for f in (0.0, 1.0, -1.0, 1/3,
                  sys.float_info.min, sys.float_info.max,
                  -sys.float_info.min, -sys.float_info.max):
            check(f, f, conv=float)
        check(float('inf'), float('inf'), conv=float)
        check(-float('inf'), -float('inf'), conv=float)
        check(float('nan'), 'NaN')
        check((), '')
        check((1, (2,), (3, 4), '5 6', ()), '1 2 {3 4} {5 6} {}')

    def test_splitlist(self):
        splitlist = self.interp.tk.splitlist
        call = self.interp.tk.call
        self.assertRaises(TypeError, splitlist)
        self.assertRaises(TypeError, splitlist, 'a', 'b')
        self.assertRaises(TypeError, splitlist, 2)
        testcases = [
            ('2', ('2',)),
            ('', ()),
            ('{}', ('',)),
            ('""', ('',)),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (u'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \xe2\x82\xac', ('a', '\xe2\x82\xac')),
            (u'a \u20ac', ('a', '\xe2\x82\xac')),
            ('a {b c}', ('a', 'b c')),
            (r'a b\ c', ('a', 'b c')),
            (('a', 'b c'), ('a', 'b c')),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            ((), ()),
            (call('list', 1, '2', (3.4,)),
                (1, '2', (3.4,)) if self.wantobjects else
                ('1', '2', '3.4')),
        ]
        if tcl_version >= (8, 5):
            testcases += [
                (call('dict', 'create', 1, u'\u20ac', '\xe2\x82\xac', (3.4,)),
                    (1, u'\u20ac', u'\u20ac', (3.4,)) if self.wantobjects else
                    ('1', '\xe2\x82\xac', '\xe2\x82\xac', '3.4')),
            ]
        for arg, res in testcases:
            self.assertEqual(splitlist(arg), res)
        self.assertRaises(TclError, splitlist, '{')

    def test_split(self):
        split = self.interp.tk.split
        call = self.interp.tk.call
        self.assertRaises(TypeError, split)
        self.assertRaises(TypeError, split, 'a', 'b')
        self.assertRaises(TypeError, split, 2)
        testcases = [
            ('2', '2'),
            ('', ''),
            ('{}', ''),
            ('""', ''),
            ('{', '{'),
            ('a\n b\t\r c\n ', ('a', 'b', 'c')),
            (u'a\n b\t\r c\n ', ('a', 'b', 'c')),
            ('a \xe2\x82\xac', ('a', '\xe2\x82\xac')),
            (u'a \u20ac', ('a', '\xe2\x82\xac')),
            ('a {b c}', ('a', ('b', 'c'))),
            (r'a b\ c', ('a', ('b', 'c'))),
            (('a', 'b c'), ('a', ('b', 'c'))),
            (('a', u'b c'), ('a', ('b', 'c'))),
            ('a 2', ('a', '2')),
            (('a', 2), ('a', 2)),
            ('a 3.4', ('a', '3.4')),
            (('a', 3.4), ('a', 3.4)),
            (('a', (2, 3.4)), ('a', (2, 3.4))),
            ((), ()),
            (call('list', 1, '2', (3.4,)),
                (1, '2', (3.4,)) if self.wantobjects else
                ('1', '2', '3.4')),
        ]
        if tcl_version >= (8, 5):
            testcases += [
                (call('dict', 'create', 12, u'\u20ac', '\xe2\x82\xac', (3.4,)),
                    (12, u'\u20ac', u'\u20ac', (3.4,)) if self.wantobjects else
                    ('12', '\xe2\x82\xac', '\xe2\x82\xac', '3.4')),
            ]
        for arg, res in testcases:
            self.assertEqual(split(arg), res)

class BigmemTclTest(unittest.TestCase):

    def setUp(self):
        self.interp = Tcl()

    @unittest.skipUnless(_testcapi.INT_MAX < _testcapi.PY_SSIZE_T_MAX,
                         "needs UINT_MAX < SIZE_MAX")
    @test_support.precisionbigmemtest(size=_testcapi.INT_MAX + 1, memuse=5,
                                      dry_run=False)
    def test_huge_string(self, size):
        value = ' ' * size
        self.assertRaises(OverflowError, self.interp.call, 'set', '_', value)

def setUpModule():
    if test_support.verbose:
        tcl = Tcl()
        print 'patchlevel =', tcl.call('info', 'patchlevel')

def test_main():
    test_support.run_unittest(TclTest, TkinterTest, BigmemTclTest)

if __name__ == "__main__":
    test_main()
<|endoftext|>


<commit_before>import logging
import random

from mlabns.db import sliver_tool_fetcher
from mlabns.util import distance
from mlabns.util import message
from mlabns.db import client_signature_fetcher

def _tool_properties_from_query(query):
    """Create ToolProperties from a LookupQuery.

    Creates a ToolProperties object for use with a resolver, based on a
    LookupQuery. Note that it only initializes common properties shared
    by all resolvers (e.g. status, tool_id) whereas resolver-specific properties
    (e.g. country, metro) are not initialized here.

    Args:
        query: LookupQuery from which to create ToolProperties

    Returns:
        A ToolProperties object initialized from the query provided.
    """
    tool_properties = sliver_tool_fetcher.ToolProperties(
        tool_id=query.tool_id,
        status=message.STATUS_ONLINE)
    if query.tool_address_family:
        tool_properties.address_family = query.tool_address_family
    return tool_properties

class ResolverBase(object):
    """Resolver base class."""

    def __init__(self, client_signature=''):
        self.sliver_tool_fetcher = sliver_tool_fetcher.SliverToolFetcher()
        self.client_signature = client_signature

    def _get_matching_candidates(self, query):
        tool_properties = _tool_properties_from_query(query)
        return self._fetch_tools_with_properties(tool_properties)

    def _fetch_tools_with_properties(self, tool_properties):
        candidates = self.sliver_tool_fetcher.fetch(tool_properties)
        if not candidates:
            logging.error('No results found for %s.', tool_properties.tool_id)
            return None
        return candidates

class AllResolver(ResolverBase):

    def answer_query(self, query):
        return self._get_matching_candidates(query)

# site_keep_probability defines explicit probabilities for 1g sites that cannot
# handle the current number of requests. Each value is the probability of
# selecting this site. The default value is 1.0.
site_keep_probability = {
    'bom01': 0.5,
    'hnd01': 0.2,  # 0.2
    'lga1t': 0.5,
    'lis01': 0.5,
    'lju01': 0.5,
    'tnr01': 0.5,
    'tun01': 0.5,
    'vie01': 0.5,
    'yqm01': 0.5,
    'yul02': 0.2,  # 0.2
    'yvr01': 0.2,  # 0.2
    'ywg01': 0.5,
    'yyc02': 0.5,
    'yyz02': 0.2,  # 0.2
}

class GeoResolver(ResolverBase):
    """Chooses the server geographically closest to the client."""

    def _add_candidate(self, query, candidate, site_distances, tool_distances):
        if candidate.site_id not in site_distances:
            site_distances[candidate.site_id] = distance.distance(
                query.latitude, query.longitude, candidate.latitude,
                candidate.longitude)
            tool_distances.append({
                'distance': site_distances[candidate.site_id],
                'tool': candidate
            })

    def _get_closest_n_candidates(self, query, max_results):
        """Selects the top N geographically closest SliverTools to the client.

        Args:
            query: A LookupQuery instance.
            max_results: The maximum number of candidates to return.

        Returns:
            A list of SliverTool entities on success, or None if there is no
            SliverTool available that matches the query.
        """
        candidates = self._get_matching_candidates(query)
        if not candidates:
            return None

        if (query.latitude is None) or (query.longitude is None):
            logging.warning(
                'No latitude/longitude, return random sliver tool(s).')
            return random.sample(candidates, min(len(candidates), max_results))

        # Pre-shuffle the candidates to randomize the order of equidistant
        # results.
        random.shuffle(candidates)

        site_distances = {}
        tool_distances = []

        filtered_candidates = []

        prob = client_signature_fetcher.ClientSignatureFetcher().fetch(
            self.client_signature)
        if random.uniform(0, 1) > prob:
            # NB: the string format makes log monitoring possible.
            logging.info('SIGNATURE_FOUND: %f returned from memcache for %s',
                         prob, self.client_signature)
            # Filter the candidates sites, only keep the '0c' sites
            filtered_candidates = filter(lambda c: c.site_id[-1] == 'c',
                                         candidates)
        else:
            # Filter the candidates sites, only keep the regular sites
            filtered_candidates = filter(lambda c: c.site_id[-1] != 'c',
                                         candidates)

        for candidate in filtered_candidates:
            prob = site_keep_probability.get(candidate.site_id, 1.0)
            if random.uniform(0, 1) < prob:
                # Only add candidate if a random probability is under the "site
                # keep probability" threshold.
                self._add_candidate(query, candidate, site_distances,
                                    tool_distances)

        # Sort the tools by distance
        tool_distances.sort(key=lambda t: t['distance'])

        # Create a new list of just the sorted SliverTool objects.
        sorted_tools = [t['tool'] for t in tool_distances]
        return sorted_tools[:max_results]

    def answer_query(self, query):
        """Selects the geographically closest SliverTool.

        Args:
            query: A LookupQuery instance.

        Returns:
            A single-element list of SliverTools in case of success, or None if
            there is no SliverTool available that matches the query.
        """
        return self._get_closest_n_candidates(query, 1)

class GeoResolverWithOptions(GeoResolver):
    """Chooses the N geographically closest servers to the client."""

    def answer_query(self, query):
        """Selects the top N geographically closest SliverTools to the client.

        Finds the top N closest SliverTools to the client and returns them.
        Note that N is currently hardcoded to 4.

        Args:
            query: A LookupQuery instance.

        Returns:
            A list of SliverTools on success, or None if there is no SliverTool
            available that matches the query.
        """
        # TODO(mtlynch): N is currently hardcoded to 4 here due to concern that
        # changing the value would break compatibility with uTorrent clients. If
        # uTorrent clients can gracefully handle responses where n=1, we should
        # get rid of GeoResolverWithOptions and just use GeoResolver.
        return self._get_closest_n_candidates(query, 4)

class MetroResolver(ResolverBase):
    """Implements the metro policy."""

    def _get_matching_candidates(self, query):
        tool_properties = _tool_properties_from_query(query)
        tool_properties.metro = query.metro
        return self._fetch_tools_with_properties(tool_properties)

    def answer_query(self, query):
        """Returns a SliverTool in a specified metro.

        Args:
            query: A LookupQuery instance.

        Returns:
            A single-element list of SliverTools if a valid match exists, None
            otherwise.
        """
        if not query.metro:
            return None

        candidates = self._get_matching_candidates(query)
        if not candidates:
            return None

        return [random.choice(candidates)]

class RandomResolver(ResolverBase):
    """Returns a server chosen randomly."""

    def answer_query(self, query):
        """Selects a random sliver tool among the available candidates.

        Args:
            query: A LookupQuery instance.

        Returns:
            A single-element list of SliverTools if a valid match exists, None
            otherwise.
        """
        candidates = self._get_matching_candidates(query)
        if not candidates:
            return None

        return [random.choice(candidates)]

class CountryResolver(ResolverBase):
    """Returns a server in a specified country."""

    def _get_matching_candidates(self, query):
        tool_properties = _tool_properties_from_query(query)
        tool_properties.country = query.country
        return self._fetch_tools_with_properties(tool_properties)

    def answer_query(self, query):
        """Returns a SliverTool in a specified country.

        Args:
            query: A LookupQuery instance.

        Returns:
            A single-element list of SliverTools if a valid match exists, None
            otherwise.
        """
        if not query.country:
            return None

        candidates = self._get_matching_candidates(query)
        if not candidates:
            return None

        return [random.choice(candidates)]

def new_resolver(policy, client_signature=''):
    if policy == message.POLICY_GEO:
        return GeoResolver(client_signature)
    elif policy == message.POLICY_METRO:
        return MetroResolver(client_signature)
    elif policy == message.POLICY_RANDOM:
        return RandomResolver(client_signature)
    elif policy == message.POLICY_COUNTRY:
        return CountryResolver(client_signature)
    elif policy == message.POLICY_GEO_OPTIONS:
        return GeoResolverWithOptions(client_signature)
    elif policy == message.POLICY_ALL:
        return AllResolver(client_signature)
    else:
        return RandomResolver(client_signature)
<commit_msg>Lowers probability for HND01 to 0.1 to reduce discards. (#246)<commit_after>import logging
import random

from mlabns.db import sliver_tool_fetcher
from mlabns.util import distance
from mlabns.util import message
from mlabns.db import client_signature_fetcher

def _tool_properties_from_query(query):
    """Create ToolProperties from a LookupQuery.

    Creates a ToolProperties object for use with a resolver, based on a
    LookupQuery. Note that it only initializes common properties shared
    by all resolvers (e.g. status, tool_id) whereas resolver-specific properties
    (e.g. country, metro) are not initialized here.

    Args:
        query: LookupQuery from which to create ToolProperties

    Returns:
        A ToolProperties object initialized from the query provided.
    """
    tool_properties = sliver_tool_fetcher.ToolProperties(
        tool_id=query.tool_id,
        status=message.STATUS_ONLINE)
    if query.tool_address_family:
        tool_properties.address_family = query.tool_address_family
    return tool_properties

class ResolverBase(object):
    """Resolver base class."""

    def __init__(self, client_signature=''):
        self.sliver_tool_fetcher = sliver_tool_fetcher.SliverToolFetcher()
        self.client_signature = client_signature

    def _get_matching_candidates(self, query):
        tool_properties = _tool_properties_from_query(query)
        return self._fetch_tools_with_properties(tool_properties)

    def _fetch_tools_with_properties(self, tool_properties):
        candidates = self.sliver_tool_fetcher.fetch(tool_properties)
        if not candidates:
            logging.error('No results found for %s.', tool_properties.tool_id)
            return None
        return candidates

class AllResolver(ResolverBase):

    def answer_query(self, query):
        return self._get_matching_candidates(query)

# site_keep_probability defines explicit probabilities for 1g sites that cannot
# handle the current number of requests. Each value is the probability of
# selecting this site. The default value is 1.0.
site_keep_probability = {
    'bom01': 0.5,
    'hnd01': 0.1,  # 0.1
    'lga1t': 0.5,
    'lis01': 0.5,
    'lju01': 0.5,
    'tnr01': 0.5,
    'tun01': 0.5,
    'vie01': 0.5,
    'yqm01': 0.5,
    'yul02': 0.2,  # 0.2
    'yvr01': 0.2,  # 0.2
    'ywg01': 0.5,
    'yyc02': 0.5,
    'yyz02': 0.2,  # 0.2
}

class GeoResolver(ResolverBase):
    """Chooses the server geographically closest to the client."""

    def _add_candidate(self, query, candidate, site_distances, tool_distances):
        if candidate.site_id not in site_distances:
            site_distances[candidate.site_id] = distance.distance(
                query.latitude, query.longitude, candidate.latitude,
                candidate.longitude)
            tool_distances.append({
                'distance': site_distances[candidate.site_id],
                'tool': candidate
            })

    def _get_closest_n_candidates(self, query, max_results):
        """Selects the top N geographically closest SliverTools to the client.

        Args:
            query: A LookupQuery instance.
            max_results: The maximum number of candidates to return.

        Returns:
            A list of SliverTool entities on success, or None if there is no
            SliverTool available that matches the query.
        """
        candidates = self._get_matching_candidates(query)
        if not candidates:
            return None

        if (query.latitude is None) or (query.longitude is None):
            logging.warning(
                'No latitude/longitude, return random sliver tool(s).')
            return random.sample(candidates, min(len(candidates), max_results))

        # Pre-shuffle the candidates to randomize the order of equidistant
        # results.
        random.shuffle(candidates)

        site_distances = {}
        tool_distances = []

        filtered_candidates = []

        prob = client_signature_fetcher.ClientSignatureFetcher().fetch(
            self.client_signature)
        if random.uniform(0, 1) > prob:
            # NB: the string format makes log monitoring possible.
            logging.info('SIGNATURE_FOUND: %f returned from memcache for %s',
                         prob, self.client_signature)
            # Filter the candidates sites, only keep the '0c' sites
            filtered_candidates = filter(lambda c: c.site_id[-1] == 'c',
                                         candidates)
        else:
            # Filter the candidates sites, only keep the regular sites
            filtered_candidates = filter(lambda c: c.site_id[-1] != 'c',
                                         candidates)

        for candidate in filtered_candidates:
            prob = site_keep_probability.get(candidate.site_id, 1.0)
            if random.uniform(0, 1) < prob:
                # Only add candidate if a random probability is under the "site
                # keep probability" threshold.
                self._add_candidate(query, candidate, site_distances,
                                    tool_distances)

        # Sort the tools by distance
        tool_distances.sort(key=lambda t: t['distance'])

        # Create a new list of just the sorted SliverTool objects.
        sorted_tools = [t['tool'] for t in tool_distances]
        return sorted_tools[:max_results]

    def answer_query(self, query):
        """Selects the geographically closest SliverTool.

        Args:
            query: A LookupQuery instance.

        Returns:
            A single-element list of SliverTools in case of success, or None if
            there is no SliverTool available that matches the query.
        """
        return self._get_closest_n_candidates(query, 1)

class GeoResolverWithOptions(GeoResolver):
    """Chooses the N geographically closest servers to the client."""

    def answer_query(self, query):
        """Selects the top N geographically closest SliverTools to the client.

        Finds the top N closest SliverTools to the client and returns them.
        Note that N is currently hardcoded to 4.

        Args:
            query: A LookupQuery instance.

        Returns:
            A list of SliverTools on success, or None if there is no SliverTool
            available that matches the query.
        """
        # TODO(mtlynch): N is currently hardcoded to 4 here due to concern that
        # changing the value would break compatibility with uTorrent clients. If
        # uTorrent clients can gracefully handle responses where n=1, we should
        # get rid of GeoResolverWithOptions and just use GeoResolver.
        return self._get_closest_n_candidates(query, 4)

class MetroResolver(ResolverBase):
    """Implements the metro policy."""

    def _get_matching_candidates(self, query):
        tool_properties = _tool_properties_from_query(query)
        tool_properties.metro = query.metro
        return self._fetch_tools_with_properties(tool_properties)

    def answer_query(self, query):
        """Returns a SliverTool in a specified metro.

        Args:
            query: A LookupQuery instance.

        Returns:
            A single-element list of SliverTools if a valid match exists, None
            otherwise.
        """
        if not query.metro:
            return None

        candidates = self._get_matching_candidates(query)
        if not candidates:
            return None

        return [random.choice(candidates)]

class RandomResolver(ResolverBase):
    """Returns a server chosen randomly."""

    def answer_query(self, query):
        """Selects a random sliver tool among the available candidates.

        Args:
            query: A LookupQuery instance.

        Returns:
            A single-element list of SliverTools if a valid match exists, None
            otherwise.
        """
        candidates = self._get_matching_candidates(query)
        if not candidates:
            return None

        return [random.choice(candidates)]

class CountryResolver(ResolverBase):
    """Returns a server in a specified country."""

    def _get_matching_candidates(self, query):
        tool_properties = _tool_properties_from_query(query)
        tool_properties.country = query.country
        return self._fetch_tools_with_properties(tool_properties)

    def answer_query(self, query):
        """Returns a SliverTool in a specified country.

        Args:
            query: A LookupQuery instance.

        Returns:
            A single-element list of SliverTools if a valid match exists, None
            otherwise.
        """
        if not query.country:
            return None

        candidates = self._get_matching_candidates(query)
        if not candidates:
            return None

        return [random.choice(candidates)]

def new_resolver(policy, client_signature=''):
    if policy == message.POLICY_GEO:
        return GeoResolver(client_signature)
    elif policy == message.POLICY_METRO:
        return MetroResolver(client_signature)
    elif policy == message.POLICY_RANDOM:
        return RandomResolver(client_signature)
    elif policy == message.POLICY_COUNTRY:
        return CountryResolver(client_signature)
    elif policy == message.POLICY_GEO_OPTIONS:
        return GeoResolverWithOptions(client_signature)
    elif policy == message.POLICY_ALL:
        return AllResolver(client_signature)
    else:
        return RandomResolver(client_signature)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from . import forms, utils
from datetime import timedelta
from dateutil.relativedelta import relativedelta
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from isodate.isoerror import ISO8601Error
import isodate

class ISO8601DurationField(models.Field):
    """Store and retrieve ISO 8601 formatted durations.

    """

    description = _("A duration of time (ISO 8601 format)")

    default_error_messages = {
        'invalid': _("This value must be in ISO 8601 Duration format."),
        'unknown_type': _("The value's type could not be converted"),
    }

    def __init__(self, *args, **kwargs):
        self.max_length = kwargs['max_length'] = 64
        super(ISO8601DurationField, self).__init__(*args, **kwargs)

    def from_db_value(self, value, *args, **kwargs):
        return self.to_python(value)

    def get_internal_type(self):
        return 'CharField'

    def deconstruct(self, *args, **kwargs):
        name, path, args, kwargs = super(ISO8601DurationField,
                                         self).deconstruct()
        del kwargs['max_length']
        return name, path, args, kwargs

    def to_python(self, value):
        """
        :returns: A duration object parsed from the given value.
        :rtype: :py:class:`~isodate.duration.Duration`

        """
        # DB value is null
        if value is None:
            return None

        # DB value is empty
        if value == '':
            return None

        if isinstance(value, isodate.duration.Duration) or isinstance(
                value, timedelta):
            return value

        try:
            duration = isodate.parse_duration(value)
        except ISO8601Error:
            raise ValidationError(self.default_error_messages['invalid'])
        return duration

    def get_prep_value(self, value):
        # Value in DB should be null.
        if value is None:
            return None

        if not isinstance(value, isodate.duration.Duration):
            raise ValidationError(
                'Cannot convert objects that are not Durations.')

        return isodate.duration_isoformat(value)

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_prep_value(value)

class RelativeDeltaField(ISO8601DurationField):
    """Store and retrieve :py:class:`~datetime.relativedelta.relativedelta`.

    Stores the relativedelta as a string representation of a
    :py:class:`~isodate.duration.Duration`.
    """

    def clean(self, value, model_instance):
        _value = self.get_prep_value(value)  # translate relativedelta to ISO-8601 format
        self.validate(_value, model_instance)
        self.run_validators(value)
        return value

    def formfield(self, **kwargs):
        defaults = {'form_class': forms.RelativeDeltaChoiceField}
        defaults.update(kwargs)
        return super(RelativeDeltaField, self).formfield(**defaults)

    def to_python(self, value):
        if isinstance(value, relativedelta):
            return value

        duration = super(RelativeDeltaField, self).to_python(value)

        if duration:
            return utils.convert_duration_to_relativedelta(duration)

    def get_prep_value(self, value):
        # Value in DB should be null
        if value is None:
            return None

        # Build the Duration object from the given relativedelta.
        duration = utils.convert_relativedelta_to_duration(value)
        duration_string = super(RelativeDeltaField, self).get_prep_value(
            duration)

        return duration_string

    def value_to_string(self, obj):
        val = self._get_val_from_obj(obj)
        s = self.get_prep_value(val)
        return '' if s is None else s
<commit_msg>Override value_from_object in RelativeDeltaField<commit_after># -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from . import forms, utils
from datetime import timedelta
from dateutil.relativedelta import relativedelta
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from isodate.isoerror import ISO8601Error
import isodate

class ISO8601DurationField(models.Field):
    """Store and retrieve ISO 8601 formatted durations.

    """

    description = _("A duration of time (ISO 8601 format)")

    default_error_messages = {
        'invalid': _("This value must be in ISO 8601 Duration format."),
        'unknown_type': _("The value's type could not be converted"),
    }

    def __init__(self, *args, **kwargs):
        self.max_length = kwargs['max_length'] = 64
        super(ISO8601DurationField, self).__init__(*args, **kwargs)

    def from_db_value(self, value, *args, **kwargs):
        return self.to_python(value)

    def get_internal_type(self):
        return 'CharField'

    def deconstruct(self, *args, **kwargs):
        name, path, args, kwargs = super(ISO8601DurationField,
                                         self).deconstruct()
        del kwargs['max_length']
        return name, path, args, kwargs

    def to_python(self, value):
        """
        :returns: A duration object parsed from the given value.
        :rtype: :py:class:`~isodate.duration.Duration`

        """
        # DB value is null
        if value is None:
            return None

        # DB value is empty
        if value == '':
            return None

        if isinstance(value, isodate.duration.Duration) or isinstance(
                value, timedelta):
            return value

        try:
            duration = isodate.parse_duration(value)
        except ISO8601Error:
            raise ValidationError(self.default_error_messages['invalid'])
        return duration

    def get_prep_value(self, value):
        # Value in DB should be null.
        if value is None:
            return None

        if not isinstance(value, isodate.duration.Duration):
            raise ValidationError(
                'Cannot convert objects that are not Durations.')

        return isodate.duration_isoformat(value)

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_prep_value(value)

class RelativeDeltaField(ISO8601DurationField):
    """Store and retrieve :py:class:`~datetime.relativedelta.relativedelta`.

    Stores the relativedelta as a string representation of a
    :py:class:`~isodate.duration.Duration`.
    """

    def clean(self, value, model_instance):
        _value = self.get_prep_value(value)  # translate relativedelta to ISO-8601 format
        self.validate(_value, model_instance)
        self.run_validators(value)
        return value

    def formfield(self, **kwargs):
        defaults = {'form_class': forms.RelativeDeltaChoiceField}
        defaults.update(kwargs)
        return super(RelativeDeltaField, self).formfield(**defaults)

    def to_python(self, value):
        if isinstance(value, relativedelta):
            return value

        duration = super(RelativeDeltaField, self).to_python(value)

        if duration:
            return utils.convert_duration_to_relativedelta(duration)

    def get_prep_value(self, value):
        # Value in DB should be null
        if value is None:
            return None

        # Build the Duration object from the given relativedelta.
        duration = utils.convert_relativedelta_to_duration(value)
        duration_string = super(RelativeDeltaField, self).get_prep_value(
            duration)

        return duration_string

    def value_to_string(self, obj):
        val = self._get_val_from_obj(obj)
        s = self.get_prep_value(val)
        return '' if s is None else s

    def value_from_object(self, obj):
        return self.value_to_string(obj)
<|endoftext|>


<commit_before>from flask import Flask
from flask import request
#pip install MySQL-python
import mysql.connector
from time import gmtime, strftime, localtime
from werkzeug import secure_filename

app = Flask(__name__)

cnx = mysql.connector.connect(user='root', password='',
                              host='127.0.0.1',
                              database='taskmanager')
cnx.autocommit = True

class MySQLCursorDict(mysql.connector.cursor.MySQLCursor):
    def _row_to_python(self, rowdata, desc=None):
        row = super(MySQLCursorDict, self)._row_to_python(rowdata, desc)
        if row:
            return dict(zip(self.column_names, row))
        return None

cur = cnx.cursor(cursor_class=MySQLCursorDict)

@app.route('/')
def hello_world():
    cur.execute("DESC basic_tasks")
    desc = cur.fetchall()

    cur.execute("SELECT * FROM basic_tasks where finish_time=''")
    rows = cur.fetchall()

    # We don't have the direct url to display image(maybe), consider to store image url directly.
    # for r in rows:
    #    r['image_path'] = "" + r['image_path'] + ""

    return 'Scheme:
' + str(desc) + '

' + 'All Tasks:
' + '
'.join([str(row) for row in rows])

@app.route('/file-store', methods=['POST'])
def style_image():
    print('request.headers:' + str(request.headers))
    f = request.files['file']
    file_path = './file-store/' + secure_filename(f.filename.split('/')[-1])
    f.save(file_path)

@app.route('/task/create', methods=['POST'])
def task_create():
    print('request.headers:' + str(request.headers))
    print(str(request.form))

    # We don't save image while create task.
    # Use file-store api to store files.
    #f = request.files['image']
    #image_path = '/Users/wuchenglin/git/neural-style/produce/input/' + secure_filename(f.filename.split('/')[-1])
    #f.save(image_path)

    image_id = request.form['image_id']

    current_time = strftime("%Y-%m-%d %H:%M:%S", localtime())
    sql_insert_template = "INSERT INTO basic_tasks values ('{create_time}', '{finish_time}', '{image_path}', '{image_id}', '{style_image}', {in_process}, '{user_id}', '')" # start_time last

    style_image = 'examples/inputs/starry_night.jpg'
    if request.form.get('style_image_path'):
        style_image = request.form['style_image_path']

    user_id = ''
    if request.form.get('user_id'):
        user_id = request.form['user_id']

    sql_insert = sql_insert_template.format(create_time=current_time, finish_time='', image_path=image_path, image_id=image_id, style_image=style_image, in_process=0, user_id=user_id)
    #sql_insert = sql_insert_template.format(create_time=current_time, finish_time='', image_path=image_path, image_id=image_id, style_image='examples/inputs/shennaichuan.jpg', in_process=0)
    print(sql_insert)
    cur.execute(sql_insert)

    return ''

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
<commit_msg>use pymysql.<commit_after>from flask import Flask
from flask import request
#pip install MySQL-python
import mysql.connector
import pymysql
from time import gmtime, strftime, localtime
from werkzeug import secure_filename

app = Flask(__name__)

cnx = pymysql.connect(user='root', password='',
                              host='127.0.0.1',
                              database='bige',
                              cursorclass=pymysql.cursors.DictCursor)
cnx.autocommit = True

@app.route('/')
def hello_world():
    with cnx.cursor() as cur:
        cur.execute("DESC basic_tasks")
        desc = cur.fetchall()

        cur.execute("SELECT * FROM basic_tasks where finish_time=''")
        rows = cur.fetchall()

        # We don't have the direct url to display image(maybe), consider to store image url directly.
        # for r in rows:
        #    r['image_path'] = "" + r['image_path'] + ""

        return 'Scheme:
' + str(desc) + '

' + 'All Tasks:
' + '
'.join([str(row) for row in rows])

@app.route('/file-store', methods=['POST'])
def style_image():
    print('request.headers:' + str(request.headers))
    f = request.files['file']
    file_path = './file-store/' + secure_filename(f.filename.split('/')[-1])
    f.save(file_path)

@app.route('/task/create', methods=['POST'])
def task_create():
    print('request.headers:' + str(request.headers))
    print(str(request.form))

    # We don't save image while create task.
    # Use file-store api to store files.
    #f = request.files['image']
    #image_path = '/Users/wuchenglin/git/neural-style/produce/input/' + secure_filename(f.filename.split('/')[-1])
    #f.save(image_path)

    image_id = request.form['image_id']

    current_time = strftime("%Y-%m-%d %H:%M:%S", localtime())
    sql_insert_template = "INSERT INTO basic_tasks values ('{create_time}', '{finish_time}', '{image_path}', '{image_id}', '{style_image}', {in_process}, '{user_id}', '')" # start_time last

    style_image = 'examples/inputs/starry_night.jpg'
    if request.form.get('style_image_path'):
        style_image = request.form['style_image_path']

    user_id = ''
    if request.form.get('user_id'):
        user_id = request.form['user_id']

    sql_insert = sql_insert_template.format(create_time=current_time, finish_time='', image_path=image_path, image_id=image_id, style_image=style_image, in_process=0, user_id=user_id)
    #sql_insert = sql_insert_template.format(create_time=current_time, finish_time='', image_path=image_path, image_id=image_id, style_image='examples/inputs/shennaichuan.jpg', in_process=0)
    print(sql_insert)
    with cnx.cursor() as cur:
        cur.execute(sql_insert)

    return ''

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
<|endoftext|>