commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
0
2.94k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
444
message
stringlengths
16
3.45k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43.2k
prompt
stringlengths
17
4.58k
response
stringlengths
1
4.43k
prompt_tagged
stringlengths
58
4.62k
response_tagged
stringlengths
1
4.43k
text
stringlengths
132
7.29k
text_tagged
stringlengths
173
7.33k
52e12dac4a341ddb7bbbf8bcbf5ee8a0d9dc5ec4
treq/test/test_api.py
treq/test/test_api.py
import mock from treq.test.util import TestCase import treq from treq._utils import set_global_pool class TreqAPITests(TestCase): def setUp(self): set_global_pool(None) client_patcher = mock.patch('treq.api.HTTPClient') self.HTTPClient = client_patcher.start() self.addCleanup(client_patcher.stop) pool_patcher = mock.patch('treq._utils.HTTPConnectionPool') self.HTTPConnectionPool = pool_patcher.start() self.addCleanup(pool_patcher.stop) self.client = self.HTTPClient.with_config.return_value def test_default_pool(self): resp = treq.get('http://test.com') self.HTTPClient.with_config.assert_called_once_with( pool=self.HTTPConnectionPool.return_value ) self.assertEqual(self.client.get.return_value, resp) def test_cached_pool(self): pool = self.HTTPConnectionPool.return_value treq.get('http://test.com') self.HTTPConnectionPool.return_value = mock.Mock() treq.get('http://test.com') self.HTTPClient.with_config.assert_called_with(pool=pool)
import mock from treq.test.util import TestCase import treq from treq._utils import set_global_pool class TreqAPITests(TestCase): def setUp(self): set_global_pool(None) agent_patcher = mock.patch('treq.api.Agent') self.Agent = agent_patcher.start() self.addCleanup(agent_patcher.stop) client_patcher = mock.patch('treq.api.HTTPClient') self.HTTPClient = client_patcher.start() self.addCleanup(client_patcher.stop) pool_patcher = mock.patch('treq._utils.HTTPConnectionPool') self.HTTPConnectionPool = pool_patcher.start() self.addCleanup(pool_patcher.stop) self.client = self.HTTPClient.return_value def test_default_pool(self): resp = treq.get('http://test.com') self.Agent.assert_called_once_with( mock.ANY, pool=self.HTTPConnectionPool.return_value ) self.assertEqual(self.client.get.return_value, resp) def test_cached_pool(self): pool = self.HTTPConnectionPool.return_value treq.get('http://test.com') self.HTTPConnectionPool.return_value = mock.Mock() treq.get('http://test.com') self.Agent.assert_called_with(mock.ANY, pool=pool)
Update default_pool tests for new call tree (mocks are fragile).
Update default_pool tests for new call tree (mocks are fragile).
Python
mit
hawkowl/treq,hawkowl/treq,habnabit/treq,glyph/treq,cyli/treq,mithrandi/treq,ldanielburr/treq,FxIII/treq,inspectlabs/treq
import mock from treq.test.util import TestCase import treq from treq._utils import set_global_pool class TreqAPITests(TestCase): def setUp(self): set_global_pool(None) client_patcher = mock.patch('treq.api.HTTPClient') self.HTTPClient = client_patcher.start() self.addCleanup(client_patcher.stop) pool_patcher = mock.patch('treq._utils.HTTPConnectionPool') self.HTTPConnectionPool = pool_patcher.start() self.addCleanup(pool_patcher.stop) self.client = self.HTTPClient.with_config.return_value def test_default_pool(self): resp = treq.get('http://test.com') self.HTTPClient.with_config.assert_called_once_with( pool=self.HTTPConnectionPool.return_value ) self.assertEqual(self.client.get.return_value, resp) def test_cached_pool(self): pool = self.HTTPConnectionPool.return_value treq.get('http://test.com') self.HTTPConnectionPool.return_value = mock.Mock() treq.get('http://test.com') self.HTTPClient.with_config.assert_called_with(pool=pool) Update default_pool tests for new call tree (mocks are fragile).
import mock from treq.test.util import TestCase import treq from treq._utils import set_global_pool class TreqAPITests(TestCase): def setUp(self): set_global_pool(None) agent_patcher = mock.patch('treq.api.Agent') self.Agent = agent_patcher.start() self.addCleanup(agent_patcher.stop) client_patcher = mock.patch('treq.api.HTTPClient') self.HTTPClient = client_patcher.start() self.addCleanup(client_patcher.stop) pool_patcher = mock.patch('treq._utils.HTTPConnectionPool') self.HTTPConnectionPool = pool_patcher.start() self.addCleanup(pool_patcher.stop) self.client = self.HTTPClient.return_value def test_default_pool(self): resp = treq.get('http://test.com') self.Agent.assert_called_once_with( mock.ANY, pool=self.HTTPConnectionPool.return_value ) self.assertEqual(self.client.get.return_value, resp) def test_cached_pool(self): pool = self.HTTPConnectionPool.return_value treq.get('http://test.com') self.HTTPConnectionPool.return_value = mock.Mock() treq.get('http://test.com') self.Agent.assert_called_with(mock.ANY, pool=pool)
<commit_before>import mock from treq.test.util import TestCase import treq from treq._utils import set_global_pool class TreqAPITests(TestCase): def setUp(self): set_global_pool(None) client_patcher = mock.patch('treq.api.HTTPClient') self.HTTPClient = client_patcher.start() self.addCleanup(client_patcher.stop) pool_patcher = mock.patch('treq._utils.HTTPConnectionPool') self.HTTPConnectionPool = pool_patcher.start() self.addCleanup(pool_patcher.stop) self.client = self.HTTPClient.with_config.return_value def test_default_pool(self): resp = treq.get('http://test.com') self.HTTPClient.with_config.assert_called_once_with( pool=self.HTTPConnectionPool.return_value ) self.assertEqual(self.client.get.return_value, resp) def test_cached_pool(self): pool = self.HTTPConnectionPool.return_value treq.get('http://test.com') self.HTTPConnectionPool.return_value = mock.Mock() treq.get('http://test.com') self.HTTPClient.with_config.assert_called_with(pool=pool) <commit_msg>Update default_pool tests for new call tree (mocks are fragile).<commit_after>
import mock from treq.test.util import TestCase import treq from treq._utils import set_global_pool class TreqAPITests(TestCase): def setUp(self): set_global_pool(None) agent_patcher = mock.patch('treq.api.Agent') self.Agent = agent_patcher.start() self.addCleanup(agent_patcher.stop) client_patcher = mock.patch('treq.api.HTTPClient') self.HTTPClient = client_patcher.start() self.addCleanup(client_patcher.stop) pool_patcher = mock.patch('treq._utils.HTTPConnectionPool') self.HTTPConnectionPool = pool_patcher.start() self.addCleanup(pool_patcher.stop) self.client = self.HTTPClient.return_value def test_default_pool(self): resp = treq.get('http://test.com') self.Agent.assert_called_once_with( mock.ANY, pool=self.HTTPConnectionPool.return_value ) self.assertEqual(self.client.get.return_value, resp) def test_cached_pool(self): pool = self.HTTPConnectionPool.return_value treq.get('http://test.com') self.HTTPConnectionPool.return_value = mock.Mock() treq.get('http://test.com') self.Agent.assert_called_with(mock.ANY, pool=pool)
import mock from treq.test.util import TestCase import treq from treq._utils import set_global_pool class TreqAPITests(TestCase): def setUp(self): set_global_pool(None) client_patcher = mock.patch('treq.api.HTTPClient') self.HTTPClient = client_patcher.start() self.addCleanup(client_patcher.stop) pool_patcher = mock.patch('treq._utils.HTTPConnectionPool') self.HTTPConnectionPool = pool_patcher.start() self.addCleanup(pool_patcher.stop) self.client = self.HTTPClient.with_config.return_value def test_default_pool(self): resp = treq.get('http://test.com') self.HTTPClient.with_config.assert_called_once_with( pool=self.HTTPConnectionPool.return_value ) self.assertEqual(self.client.get.return_value, resp) def test_cached_pool(self): pool = self.HTTPConnectionPool.return_value treq.get('http://test.com') self.HTTPConnectionPool.return_value = mock.Mock() treq.get('http://test.com') self.HTTPClient.with_config.assert_called_with(pool=pool) Update default_pool tests for new call tree (mocks are fragile).import mock from treq.test.util import TestCase import treq from treq._utils import set_global_pool class TreqAPITests(TestCase): def setUp(self): set_global_pool(None) agent_patcher = mock.patch('treq.api.Agent') self.Agent = agent_patcher.start() self.addCleanup(agent_patcher.stop) client_patcher = mock.patch('treq.api.HTTPClient') self.HTTPClient = client_patcher.start() self.addCleanup(client_patcher.stop) pool_patcher = mock.patch('treq._utils.HTTPConnectionPool') self.HTTPConnectionPool = pool_patcher.start() self.addCleanup(pool_patcher.stop) self.client = self.HTTPClient.return_value def test_default_pool(self): resp = treq.get('http://test.com') self.Agent.assert_called_once_with( mock.ANY, pool=self.HTTPConnectionPool.return_value ) self.assertEqual(self.client.get.return_value, resp) def test_cached_pool(self): pool = self.HTTPConnectionPool.return_value treq.get('http://test.com') self.HTTPConnectionPool.return_value = mock.Mock() treq.get('http://test.com') self.Agent.assert_called_with(mock.ANY, pool=pool)
<commit_before>import mock from treq.test.util import TestCase import treq from treq._utils import set_global_pool class TreqAPITests(TestCase): def setUp(self): set_global_pool(None) client_patcher = mock.patch('treq.api.HTTPClient') self.HTTPClient = client_patcher.start() self.addCleanup(client_patcher.stop) pool_patcher = mock.patch('treq._utils.HTTPConnectionPool') self.HTTPConnectionPool = pool_patcher.start() self.addCleanup(pool_patcher.stop) self.client = self.HTTPClient.with_config.return_value def test_default_pool(self): resp = treq.get('http://test.com') self.HTTPClient.with_config.assert_called_once_with( pool=self.HTTPConnectionPool.return_value ) self.assertEqual(self.client.get.return_value, resp) def test_cached_pool(self): pool = self.HTTPConnectionPool.return_value treq.get('http://test.com') self.HTTPConnectionPool.return_value = mock.Mock() treq.get('http://test.com') self.HTTPClient.with_config.assert_called_with(pool=pool) <commit_msg>Update default_pool tests for new call tree (mocks are fragile).<commit_after>import mock from treq.test.util import TestCase import treq from treq._utils import set_global_pool class TreqAPITests(TestCase): def setUp(self): set_global_pool(None) agent_patcher = mock.patch('treq.api.Agent') self.Agent = agent_patcher.start() self.addCleanup(agent_patcher.stop) client_patcher = mock.patch('treq.api.HTTPClient') self.HTTPClient = client_patcher.start() self.addCleanup(client_patcher.stop) pool_patcher = mock.patch('treq._utils.HTTPConnectionPool') self.HTTPConnectionPool = pool_patcher.start() self.addCleanup(pool_patcher.stop) self.client = self.HTTPClient.return_value def test_default_pool(self): resp = treq.get('http://test.com') self.Agent.assert_called_once_with( mock.ANY, pool=self.HTTPConnectionPool.return_value ) self.assertEqual(self.client.get.return_value, resp) def test_cached_pool(self): pool = self.HTTPConnectionPool.return_value treq.get('http://test.com') self.HTTPConnectionPool.return_value = mock.Mock() treq.get('http://test.com') self.Agent.assert_called_with(mock.ANY, pool=pool)
69924be13f6b4303304c86fa56a802b6d358e7b2
instance/configuration_example.py
instance/configuration_example.py
# -*- coding: utf-8 -*- """ Instance configuration, possibly overwriting default values. """ class Configuration: """ Instance specific configurations for |projectname| that should not be shared with anyone else (e.g. because of passwords). You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: basestring """ MAIL_PORT = 25 """ The port under which the :attr:`.MAIL_SERVER` is accessible. :type: int """ MAIL_USERNAME = None """ A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: basestring | None """ MAIL_PASSWORD = None """ The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: basestring | None """ SECRET_KEY = 'Absolutely random and very long.' """ A long, random, and secret string used to secure sessions. :type: str """
# -*- coding: utf-8 -*- """ Instance configuration, possibly overwriting default values. """ class Configuration: """ Instance specific configurations for |projectname| that should not be shared with anyone else (e.g. because of passwords). You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ ADMINS = ['admin@example.com'] """ A list of email addresses of all administrators who will be notified on program failures. :type: List[str] """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: str | None """ MAIL_PORT = 25 """ The port under which the :attr:`.MAIL_SERVER` is accessible. :type: int """ MAIL_USERNAME = None """ A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: str | None """ MAIL_PASSWORD = None """ The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: str | None """ SECRET_KEY = '' """ A long, random, and secret string used to secure sessions. :type: str """
Add admin email list to instance configuration.
Add admin email list to instance configuration.
Python
mit
BMeu/Orchard,BMeu/Orchard
# -*- coding: utf-8 -*- """ Instance configuration, possibly overwriting default values. """ class Configuration: """ Instance specific configurations for |projectname| that should not be shared with anyone else (e.g. because of passwords). You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: basestring """ MAIL_PORT = 25 """ The port under which the :attr:`.MAIL_SERVER` is accessible. :type: int """ MAIL_USERNAME = None """ A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: basestring | None """ MAIL_PASSWORD = None """ The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: basestring | None """ SECRET_KEY = 'Absolutely random and very long.' """ A long, random, and secret string used to secure sessions. :type: str """ Add admin email list to instance configuration.
# -*- coding: utf-8 -*- """ Instance configuration, possibly overwriting default values. """ class Configuration: """ Instance specific configurations for |projectname| that should not be shared with anyone else (e.g. because of passwords). You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ ADMINS = ['admin@example.com'] """ A list of email addresses of all administrators who will be notified on program failures. :type: List[str] """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: str | None """ MAIL_PORT = 25 """ The port under which the :attr:`.MAIL_SERVER` is accessible. :type: int """ MAIL_USERNAME = None """ A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: str | None """ MAIL_PASSWORD = None """ The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: str | None """ SECRET_KEY = '' """ A long, random, and secret string used to secure sessions. :type: str """
<commit_before># -*- coding: utf-8 -*- """ Instance configuration, possibly overwriting default values. """ class Configuration: """ Instance specific configurations for |projectname| that should not be shared with anyone else (e.g. because of passwords). You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: basestring """ MAIL_PORT = 25 """ The port under which the :attr:`.MAIL_SERVER` is accessible. :type: int """ MAIL_USERNAME = None """ A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: basestring | None """ MAIL_PASSWORD = None """ The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: basestring | None """ SECRET_KEY = 'Absolutely random and very long.' """ A long, random, and secret string used to secure sessions. :type: str """ <commit_msg>Add admin email list to instance configuration.<commit_after>
# -*- coding: utf-8 -*- """ Instance configuration, possibly overwriting default values. """ class Configuration: """ Instance specific configurations for |projectname| that should not be shared with anyone else (e.g. because of passwords). You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ ADMINS = ['admin@example.com'] """ A list of email addresses of all administrators who will be notified on program failures. :type: List[str] """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: str | None """ MAIL_PORT = 25 """ The port under which the :attr:`.MAIL_SERVER` is accessible. :type: int """ MAIL_USERNAME = None """ A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: str | None """ MAIL_PASSWORD = None """ The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: str | None """ SECRET_KEY = '' """ A long, random, and secret string used to secure sessions. :type: str """
# -*- coding: utf-8 -*- """ Instance configuration, possibly overwriting default values. """ class Configuration: """ Instance specific configurations for |projectname| that should not be shared with anyone else (e.g. because of passwords). You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: basestring """ MAIL_PORT = 25 """ The port under which the :attr:`.MAIL_SERVER` is accessible. :type: int """ MAIL_USERNAME = None """ A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: basestring | None """ MAIL_PASSWORD = None """ The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: basestring | None """ SECRET_KEY = 'Absolutely random and very long.' """ A long, random, and secret string used to secure sessions. :type: str """ Add admin email list to instance configuration.# -*- coding: utf-8 -*- """ Instance configuration, possibly overwriting default values. """ class Configuration: """ Instance specific configurations for |projectname| that should not be shared with anyone else (e.g. because of passwords). You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ ADMINS = ['admin@example.com'] """ A list of email addresses of all administrators who will be notified on program failures. :type: List[str] """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: str | None """ MAIL_PORT = 25 """ The port under which the :attr:`.MAIL_SERVER` is accessible. :type: int """ MAIL_USERNAME = None """ A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: str | None """ MAIL_PASSWORD = None """ The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: str | None """ SECRET_KEY = '' """ A long, random, and secret string used to secure sessions. :type: str """
<commit_before># -*- coding: utf-8 -*- """ Instance configuration, possibly overwriting default values. """ class Configuration: """ Instance specific configurations for |projectname| that should not be shared with anyone else (e.g. because of passwords). You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: basestring """ MAIL_PORT = 25 """ The port under which the :attr:`.MAIL_SERVER` is accessible. :type: int """ MAIL_USERNAME = None """ A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: basestring | None """ MAIL_PASSWORD = None """ The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: basestring | None """ SECRET_KEY = 'Absolutely random and very long.' """ A long, random, and secret string used to secure sessions. :type: str """ <commit_msg>Add admin email list to instance configuration.<commit_after># -*- coding: utf-8 -*- """ Instance configuration, possibly overwriting default values. """ class Configuration: """ Instance specific configurations for |projectname| that should not be shared with anyone else (e.g. because of passwords). You can overwrite any of the values from :mod:`orchard.configuration` in this class. """ ADMINS = ['admin@example.com'] """ A list of email addresses of all administrators who will be notified on program failures. :type: List[str] """ MAIL_SERVER = 'localhost' """ An SMTP mail server used for sending all mails. :type: str | None """ MAIL_PORT = 25 """ The port under which the :attr:`.MAIL_SERVER` is accessible. :type: int """ MAIL_USERNAME = None """ A user on the :attr:`.MAIL_SERVER`. If no user is required to send mails, this can be set to ``None``. :type: str | None """ MAIL_PASSWORD = None """ The password for the :attr:`.MAIL_USERNAME`. If no password is required, this can be set to ``None``. :type: str | None """ SECRET_KEY = '' """ A long, random, and secret string used to secure sessions. :type: str """
b00f9ae056ccab2020a016d2f0f1189f7ac0a788
src/satosa/logging_util.py
src/satosa/logging_util.py
from uuid import uuid4 # The state key for saving the session id in the state LOGGER_STATE_KEY = "SESSION_ID" LOG_FMT = "[{id}] {message}" def get_session_id(state): session_id = ( "UNKNOWN" if state is None else state.get(LOGGER_STATE_KEY, uuid4().urn) ) return session_id def satosa_logging(logger, level, message, state, **kwargs): """ Adds a session ID to the message. :type logger: logging :type level: int :type message: str :type state: satosa.state.State :param logger: Logger to use :param level: Logger level (ex: logging.DEBUG/logging.WARN/...) :param message: Message :param state: The current state :param kwargs: set exc_info=True to get an exception stack trace in the log """ state[LOGGER_STATE_KEY] = session_id = get_session_id(state) logline = LOG_FMT.format(id=session_id, message=message) logger.log(level, logline, **kwargs)
from uuid import uuid4 # The state key for saving the session id in the state LOGGER_STATE_KEY = "SESSION_ID" LOG_FMT = "[{id}] {message}" def get_session_id(state): session_id = ( "UNKNOWN" if state is None else state.get(LOGGER_STATE_KEY, uuid4().urn) ) return session_id def satosa_logging(logger, level, message, state, **kwargs): """ Adds a session ID to the message. :type logger: logging :type level: int :type message: str :type state: satosa.state.State :param logger: Logger to use :param level: Logger level (ex: logging.DEBUG/logging.WARN/...) :param message: Message :param state: The current state :param kwargs: set exc_info=True to get an exception stack trace in the log """ session_id = get_session_id(state) if state is not None: state[LOGGER_STATE_KEY] = session_id logline = LOG_FMT.format(id=session_id, message=message) logger.log(level, logline, **kwargs)
Set state session-id only when state is present
Set state session-id only when state is present Signed-off-by: Ivan Kanakarakis <f60d6943d72436645c4304926eeeac2718a1142c@gmail.com>
Python
apache-2.0
SUNET/SATOSA,SUNET/SATOSA,its-dirg/SATOSA
from uuid import uuid4 # The state key for saving the session id in the state LOGGER_STATE_KEY = "SESSION_ID" LOG_FMT = "[{id}] {message}" def get_session_id(state): session_id = ( "UNKNOWN" if state is None else state.get(LOGGER_STATE_KEY, uuid4().urn) ) return session_id def satosa_logging(logger, level, message, state, **kwargs): """ Adds a session ID to the message. :type logger: logging :type level: int :type message: str :type state: satosa.state.State :param logger: Logger to use :param level: Logger level (ex: logging.DEBUG/logging.WARN/...) :param message: Message :param state: The current state :param kwargs: set exc_info=True to get an exception stack trace in the log """ state[LOGGER_STATE_KEY] = session_id = get_session_id(state) logline = LOG_FMT.format(id=session_id, message=message) logger.log(level, logline, **kwargs) Set state session-id only when state is present Signed-off-by: Ivan Kanakarakis <f60d6943d72436645c4304926eeeac2718a1142c@gmail.com>
from uuid import uuid4 # The state key for saving the session id in the state LOGGER_STATE_KEY = "SESSION_ID" LOG_FMT = "[{id}] {message}" def get_session_id(state): session_id = ( "UNKNOWN" if state is None else state.get(LOGGER_STATE_KEY, uuid4().urn) ) return session_id def satosa_logging(logger, level, message, state, **kwargs): """ Adds a session ID to the message. :type logger: logging :type level: int :type message: str :type state: satosa.state.State :param logger: Logger to use :param level: Logger level (ex: logging.DEBUG/logging.WARN/...) :param message: Message :param state: The current state :param kwargs: set exc_info=True to get an exception stack trace in the log """ session_id = get_session_id(state) if state is not None: state[LOGGER_STATE_KEY] = session_id logline = LOG_FMT.format(id=session_id, message=message) logger.log(level, logline, **kwargs)
<commit_before>from uuid import uuid4 # The state key for saving the session id in the state LOGGER_STATE_KEY = "SESSION_ID" LOG_FMT = "[{id}] {message}" def get_session_id(state): session_id = ( "UNKNOWN" if state is None else state.get(LOGGER_STATE_KEY, uuid4().urn) ) return session_id def satosa_logging(logger, level, message, state, **kwargs): """ Adds a session ID to the message. :type logger: logging :type level: int :type message: str :type state: satosa.state.State :param logger: Logger to use :param level: Logger level (ex: logging.DEBUG/logging.WARN/...) :param message: Message :param state: The current state :param kwargs: set exc_info=True to get an exception stack trace in the log """ state[LOGGER_STATE_KEY] = session_id = get_session_id(state) logline = LOG_FMT.format(id=session_id, message=message) logger.log(level, logline, **kwargs) <commit_msg>Set state session-id only when state is present Signed-off-by: Ivan Kanakarakis <f60d6943d72436645c4304926eeeac2718a1142c@gmail.com><commit_after>
from uuid import uuid4 # The state key for saving the session id in the state LOGGER_STATE_KEY = "SESSION_ID" LOG_FMT = "[{id}] {message}" def get_session_id(state): session_id = ( "UNKNOWN" if state is None else state.get(LOGGER_STATE_KEY, uuid4().urn) ) return session_id def satosa_logging(logger, level, message, state, **kwargs): """ Adds a session ID to the message. :type logger: logging :type level: int :type message: str :type state: satosa.state.State :param logger: Logger to use :param level: Logger level (ex: logging.DEBUG/logging.WARN/...) :param message: Message :param state: The current state :param kwargs: set exc_info=True to get an exception stack trace in the log """ session_id = get_session_id(state) if state is not None: state[LOGGER_STATE_KEY] = session_id logline = LOG_FMT.format(id=session_id, message=message) logger.log(level, logline, **kwargs)
from uuid import uuid4 # The state key for saving the session id in the state LOGGER_STATE_KEY = "SESSION_ID" LOG_FMT = "[{id}] {message}" def get_session_id(state): session_id = ( "UNKNOWN" if state is None else state.get(LOGGER_STATE_KEY, uuid4().urn) ) return session_id def satosa_logging(logger, level, message, state, **kwargs): """ Adds a session ID to the message. :type logger: logging :type level: int :type message: str :type state: satosa.state.State :param logger: Logger to use :param level: Logger level (ex: logging.DEBUG/logging.WARN/...) :param message: Message :param state: The current state :param kwargs: set exc_info=True to get an exception stack trace in the log """ state[LOGGER_STATE_KEY] = session_id = get_session_id(state) logline = LOG_FMT.format(id=session_id, message=message) logger.log(level, logline, **kwargs) Set state session-id only when state is present Signed-off-by: Ivan Kanakarakis <f60d6943d72436645c4304926eeeac2718a1142c@gmail.com>from uuid import uuid4 # The state key for saving the session id in the state LOGGER_STATE_KEY = "SESSION_ID" LOG_FMT = "[{id}] {message}" def get_session_id(state): session_id = ( "UNKNOWN" if state is None else state.get(LOGGER_STATE_KEY, uuid4().urn) ) return session_id def satosa_logging(logger, level, message, state, **kwargs): """ Adds a session ID to the message. :type logger: logging :type level: int :type message: str :type state: satosa.state.State :param logger: Logger to use :param level: Logger level (ex: logging.DEBUG/logging.WARN/...) :param message: Message :param state: The current state :param kwargs: set exc_info=True to get an exception stack trace in the log """ session_id = get_session_id(state) if state is not None: state[LOGGER_STATE_KEY] = session_id logline = LOG_FMT.format(id=session_id, message=message) logger.log(level, logline, **kwargs)
<commit_before>from uuid import uuid4 # The state key for saving the session id in the state LOGGER_STATE_KEY = "SESSION_ID" LOG_FMT = "[{id}] {message}" def get_session_id(state): session_id = ( "UNKNOWN" if state is None else state.get(LOGGER_STATE_KEY, uuid4().urn) ) return session_id def satosa_logging(logger, level, message, state, **kwargs): """ Adds a session ID to the message. :type logger: logging :type level: int :type message: str :type state: satosa.state.State :param logger: Logger to use :param level: Logger level (ex: logging.DEBUG/logging.WARN/...) :param message: Message :param state: The current state :param kwargs: set exc_info=True to get an exception stack trace in the log """ state[LOGGER_STATE_KEY] = session_id = get_session_id(state) logline = LOG_FMT.format(id=session_id, message=message) logger.log(level, logline, **kwargs) <commit_msg>Set state session-id only when state is present Signed-off-by: Ivan Kanakarakis <f60d6943d72436645c4304926eeeac2718a1142c@gmail.com><commit_after>from uuid import uuid4 # The state key for saving the session id in the state LOGGER_STATE_KEY = "SESSION_ID" LOG_FMT = "[{id}] {message}" def get_session_id(state): session_id = ( "UNKNOWN" if state is None else state.get(LOGGER_STATE_KEY, uuid4().urn) ) return session_id def satosa_logging(logger, level, message, state, **kwargs): """ Adds a session ID to the message. :type logger: logging :type level: int :type message: str :type state: satosa.state.State :param logger: Logger to use :param level: Logger level (ex: logging.DEBUG/logging.WARN/...) :param message: Message :param state: The current state :param kwargs: set exc_info=True to get an exception stack trace in the log """ session_id = get_session_id(state) if state is not None: state[LOGGER_STATE_KEY] = session_id logline = LOG_FMT.format(id=session_id, message=message) logger.log(level, logline, **kwargs)
36df0d8f2878a1b51b4d9461f1ee64ef90a826a3
tailor/listeners/mainlistener.py
tailor/listeners/mainlistener.py
from tailor.swift.swiftlistener import SwiftListener from tailor.utils.charformat import isUpperCamelCase class MainListener(SwiftListener): def enterClassName(self, ctx): self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase') def enterEnumName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase') def enterEnumCaseName(self, ctx): pass def enterStructName(self, ctx): pass @staticmethod def __verify_upper_camel_case(ctx, err_msg): construct_name = ctx.getText() if not isUpperCamelCase(construct_name): print('Line', str(ctx.start.line) + ':', err_msg)
from tailor.swift.swiftlistener import SwiftListener from tailor.utils.charformat import isUpperCamelCase class MainListener(SwiftListener): def enterClassName(self, ctx): self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase') def enterEnumName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase') def enterEnumCaseName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum case names should be in UpperCamelCase') def enterStructName(self, ctx): pass @staticmethod def __verify_upper_camel_case(ctx, err_msg): construct_name = ctx.getText() if not isUpperCamelCase(construct_name): print('Line', str(ctx.start.line) + ':', err_msg)
Implement UpperCamelCase name check for enum case
Implement UpperCamelCase name check for enum case
Python
mit
sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor
from tailor.swift.swiftlistener import SwiftListener from tailor.utils.charformat import isUpperCamelCase class MainListener(SwiftListener): def enterClassName(self, ctx): self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase') def enterEnumName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase') def enterEnumCaseName(self, ctx): pass def enterStructName(self, ctx): pass @staticmethod def __verify_upper_camel_case(ctx, err_msg): construct_name = ctx.getText() if not isUpperCamelCase(construct_name): print('Line', str(ctx.start.line) + ':', err_msg) Implement UpperCamelCase name check for enum case
from tailor.swift.swiftlistener import SwiftListener from tailor.utils.charformat import isUpperCamelCase class MainListener(SwiftListener): def enterClassName(self, ctx): self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase') def enterEnumName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase') def enterEnumCaseName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum case names should be in UpperCamelCase') def enterStructName(self, ctx): pass @staticmethod def __verify_upper_camel_case(ctx, err_msg): construct_name = ctx.getText() if not isUpperCamelCase(construct_name): print('Line', str(ctx.start.line) + ':', err_msg)
<commit_before>from tailor.swift.swiftlistener import SwiftListener from tailor.utils.charformat import isUpperCamelCase class MainListener(SwiftListener): def enterClassName(self, ctx): self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase') def enterEnumName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase') def enterEnumCaseName(self, ctx): pass def enterStructName(self, ctx): pass @staticmethod def __verify_upper_camel_case(ctx, err_msg): construct_name = ctx.getText() if not isUpperCamelCase(construct_name): print('Line', str(ctx.start.line) + ':', err_msg) <commit_msg>Implement UpperCamelCase name check for enum case<commit_after>
from tailor.swift.swiftlistener import SwiftListener from tailor.utils.charformat import isUpperCamelCase class MainListener(SwiftListener): def enterClassName(self, ctx): self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase') def enterEnumName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase') def enterEnumCaseName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum case names should be in UpperCamelCase') def enterStructName(self, ctx): pass @staticmethod def __verify_upper_camel_case(ctx, err_msg): construct_name = ctx.getText() if not isUpperCamelCase(construct_name): print('Line', str(ctx.start.line) + ':', err_msg)
from tailor.swift.swiftlistener import SwiftListener from tailor.utils.charformat import isUpperCamelCase class MainListener(SwiftListener): def enterClassName(self, ctx): self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase') def enterEnumName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase') def enterEnumCaseName(self, ctx): pass def enterStructName(self, ctx): pass @staticmethod def __verify_upper_camel_case(ctx, err_msg): construct_name = ctx.getText() if not isUpperCamelCase(construct_name): print('Line', str(ctx.start.line) + ':', err_msg) Implement UpperCamelCase name check for enum casefrom tailor.swift.swiftlistener import SwiftListener from tailor.utils.charformat import isUpperCamelCase class MainListener(SwiftListener): def enterClassName(self, ctx): self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase') def enterEnumName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase') def enterEnumCaseName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum case names should be in UpperCamelCase') def enterStructName(self, ctx): pass @staticmethod def __verify_upper_camel_case(ctx, err_msg): construct_name = ctx.getText() if not isUpperCamelCase(construct_name): print('Line', str(ctx.start.line) + ':', err_msg)
<commit_before>from tailor.swift.swiftlistener import SwiftListener from tailor.utils.charformat import isUpperCamelCase class MainListener(SwiftListener): def enterClassName(self, ctx): self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase') def enterEnumName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase') def enterEnumCaseName(self, ctx): pass def enterStructName(self, ctx): pass @staticmethod def __verify_upper_camel_case(ctx, err_msg): construct_name = ctx.getText() if not isUpperCamelCase(construct_name): print('Line', str(ctx.start.line) + ':', err_msg) <commit_msg>Implement UpperCamelCase name check for enum case<commit_after>from tailor.swift.swiftlistener import SwiftListener from tailor.utils.charformat import isUpperCamelCase class MainListener(SwiftListener): def enterClassName(self, ctx): self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase') def enterEnumName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum names should be in UpperCamelCase') def enterEnumCaseName(self, ctx): self.__verify_upper_camel_case(ctx, 'Enum case names should be in UpperCamelCase') def enterStructName(self, ctx): pass @staticmethod def __verify_upper_camel_case(ctx, err_msg): construct_name = ctx.getText() if not isUpperCamelCase(construct_name): print('Line', str(ctx.start.line) + ':', err_msg)
ab7eb6891ff0f6a574708267f166bc27c7b7e95b
orderedmodel/models.py
orderedmodel/models.py
from django.db import models from django.core.exceptions import ValidationError class OrderedModel(models.Model): order = models.PositiveIntegerField(blank=True, default=1) class Meta: abstract = True ordering = ['order'] def save(self, swapping=False, *args, **kwargs): if not self.id: self.order = self.max_order() + 1 if self.order == 0 and not swapping: raise ValidationError("Can't set 'order' to 0") super(OrderedModel, self).save(*args, **kwargs) @classmethod def swap(cls, obj1, obj2): tmp, obj2.order = obj2.order, 0 obj2.save(swapping=True) obj2.order, obj1.order = obj1.order, tmp obj1.save() obj2.save() @classmethod def max_order(cls): try: return cls.objects.order_by('-order').values_list('order', flat=True)[0] except IndexError: return 0
from django.db import models from django.core.exceptions import ValidationError class OrderedModel(models.Model): order = models.PositiveIntegerField(blank=True, default=1, db_index=True) class Meta: abstract = True ordering = ['order'] def save(self, swapping=False, *args, **kwargs): if not self.id: self.order = self.max_order() + 1 if self.order == 0 and not swapping: raise ValidationError("Can't set 'order' to 0") super(OrderedModel, self).save(*args, **kwargs) @classmethod def swap(cls, obj1, obj2): tmp, obj2.order = obj2.order, 0 obj2.save(swapping=True) obj2.order, obj1.order = obj1.order, tmp obj1.save() obj2.save() @classmethod def max_order(cls): try: return cls.objects.order_by('-order').values_list('order', flat=True)[0] except IndexError: return 0
Enable index for order column
Enable index for order column Ordering will be faster
Python
bsd-3-clause
MagicSolutions/django-orderedmodel,MagicSolutions/django-orderedmodel
from django.db import models from django.core.exceptions import ValidationError class OrderedModel(models.Model): order = models.PositiveIntegerField(blank=True, default=1) class Meta: abstract = True ordering = ['order'] def save(self, swapping=False, *args, **kwargs): if not self.id: self.order = self.max_order() + 1 if self.order == 0 and not swapping: raise ValidationError("Can't set 'order' to 0") super(OrderedModel, self).save(*args, **kwargs) @classmethod def swap(cls, obj1, obj2): tmp, obj2.order = obj2.order, 0 obj2.save(swapping=True) obj2.order, obj1.order = obj1.order, tmp obj1.save() obj2.save() @classmethod def max_order(cls): try: return cls.objects.order_by('-order').values_list('order', flat=True)[0] except IndexError: return 0 Enable index for order column Ordering will be faster
from django.db import models from django.core.exceptions import ValidationError class OrderedModel(models.Model): order = models.PositiveIntegerField(blank=True, default=1, db_index=True) class Meta: abstract = True ordering = ['order'] def save(self, swapping=False, *args, **kwargs): if not self.id: self.order = self.max_order() + 1 if self.order == 0 and not swapping: raise ValidationError("Can't set 'order' to 0") super(OrderedModel, self).save(*args, **kwargs) @classmethod def swap(cls, obj1, obj2): tmp, obj2.order = obj2.order, 0 obj2.save(swapping=True) obj2.order, obj1.order = obj1.order, tmp obj1.save() obj2.save() @classmethod def max_order(cls): try: return cls.objects.order_by('-order').values_list('order', flat=True)[0] except IndexError: return 0
<commit_before>from django.db import models from django.core.exceptions import ValidationError class OrderedModel(models.Model): order = models.PositiveIntegerField(blank=True, default=1) class Meta: abstract = True ordering = ['order'] def save(self, swapping=False, *args, **kwargs): if not self.id: self.order = self.max_order() + 1 if self.order == 0 and not swapping: raise ValidationError("Can't set 'order' to 0") super(OrderedModel, self).save(*args, **kwargs) @classmethod def swap(cls, obj1, obj2): tmp, obj2.order = obj2.order, 0 obj2.save(swapping=True) obj2.order, obj1.order = obj1.order, tmp obj1.save() obj2.save() @classmethod def max_order(cls): try: return cls.objects.order_by('-order').values_list('order', flat=True)[0] except IndexError: return 0 <commit_msg>Enable index for order column Ordering will be faster<commit_after>
from django.db import models from django.core.exceptions import ValidationError class OrderedModel(models.Model): order = models.PositiveIntegerField(blank=True, default=1, db_index=True) class Meta: abstract = True ordering = ['order'] def save(self, swapping=False, *args, **kwargs): if not self.id: self.order = self.max_order() + 1 if self.order == 0 and not swapping: raise ValidationError("Can't set 'order' to 0") super(OrderedModel, self).save(*args, **kwargs) @classmethod def swap(cls, obj1, obj2): tmp, obj2.order = obj2.order, 0 obj2.save(swapping=True) obj2.order, obj1.order = obj1.order, tmp obj1.save() obj2.save() @classmethod def max_order(cls): try: return cls.objects.order_by('-order').values_list('order', flat=True)[0] except IndexError: return 0
from django.db import models from django.core.exceptions import ValidationError class OrderedModel(models.Model): order = models.PositiveIntegerField(blank=True, default=1) class Meta: abstract = True ordering = ['order'] def save(self, swapping=False, *args, **kwargs): if not self.id: self.order = self.max_order() + 1 if self.order == 0 and not swapping: raise ValidationError("Can't set 'order' to 0") super(OrderedModel, self).save(*args, **kwargs) @classmethod def swap(cls, obj1, obj2): tmp, obj2.order = obj2.order, 0 obj2.save(swapping=True) obj2.order, obj1.order = obj1.order, tmp obj1.save() obj2.save() @classmethod def max_order(cls): try: return cls.objects.order_by('-order').values_list('order', flat=True)[0] except IndexError: return 0 Enable index for order column Ordering will be fasterfrom django.db import models from django.core.exceptions import ValidationError class OrderedModel(models.Model): order = models.PositiveIntegerField(blank=True, default=1, db_index=True) class Meta: abstract = True ordering = ['order'] def save(self, swapping=False, *args, **kwargs): if not self.id: self.order = self.max_order() + 1 if self.order == 0 and not swapping: raise ValidationError("Can't set 'order' to 0") super(OrderedModel, self).save(*args, **kwargs) @classmethod def swap(cls, obj1, obj2): tmp, obj2.order = obj2.order, 0 obj2.save(swapping=True) obj2.order, obj1.order = obj1.order, tmp obj1.save() obj2.save() @classmethod def max_order(cls): try: return cls.objects.order_by('-order').values_list('order', flat=True)[0] except IndexError: return 0
<commit_before>from django.db import models from django.core.exceptions import ValidationError class OrderedModel(models.Model): order = models.PositiveIntegerField(blank=True, default=1) class Meta: abstract = True ordering = ['order'] def save(self, swapping=False, *args, **kwargs): if not self.id: self.order = self.max_order() + 1 if self.order == 0 and not swapping: raise ValidationError("Can't set 'order' to 0") super(OrderedModel, self).save(*args, **kwargs) @classmethod def swap(cls, obj1, obj2): tmp, obj2.order = obj2.order, 0 obj2.save(swapping=True) obj2.order, obj1.order = obj1.order, tmp obj1.save() obj2.save() @classmethod def max_order(cls): try: return cls.objects.order_by('-order').values_list('order', flat=True)[0] except IndexError: return 0 <commit_msg>Enable index for order column Ordering will be faster<commit_after>from django.db import models from django.core.exceptions import ValidationError class OrderedModel(models.Model): order = models.PositiveIntegerField(blank=True, default=1, db_index=True) class Meta: abstract = True ordering = ['order'] def save(self, swapping=False, *args, **kwargs): if not self.id: self.order = self.max_order() + 1 if self.order == 0 and not swapping: raise ValidationError("Can't set 'order' to 0") super(OrderedModel, self).save(*args, **kwargs) @classmethod def swap(cls, obj1, obj2): tmp, obj2.order = obj2.order, 0 obj2.save(swapping=True) obj2.order, obj1.order = obj1.order, tmp obj1.save() obj2.save() @classmethod def max_order(cls): try: return cls.objects.order_by('-order').values_list('order', flat=True)[0] except IndexError: return 0
817b597f3a45a8b16de84d480458a66499604f5a
owned_models/models.py
owned_models/models.py
from django.conf import settings from django.db import models class UserOwnedModelManager(models.Manager): def filter_for_user(self, user, *args, **kwargs): return super(UserOwnedModelManager, self).get_queryset().filter(user = user, *args, **kwargs) def get_for_user(self, user, *args, **kwargs): if 'user' in kwargs: kwargs.pop('user') return super(UserOwnedModelManager, self).get_queryset().get(user = user, *args, **kwargs) class UserOwnedModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, editable = False) objects = UserOwnedModelManager() class Meta: abstract = True
from django.conf import settings from django.db import models class UserOwnedModelManager(models.Manager): def filter_for_user(self, user, *args, **kwargs): return super(UserOwnedModelManager, self).get_queryset().filter(user = user, *args, **kwargs) def get_for_user(self, user, *args, **kwargs): if 'user' in kwargs: kwargs.pop('user') return super(UserOwnedModelManager, self).get_queryset().get(user = user, *args, **kwargs) def get_or_create_for_user(self, user, **kwargs): return super(UserOwnedModelManager, self).get_or_create(user = user, **kwargs) class UserOwnedModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, editable = False) objects = UserOwnedModelManager() class Meta: abstract = True
Add `get_or_create_for_user` method to default Manager.
Add `get_or_create_for_user` method to default Manager.
Python
mit
discolabs/django-owned-models
from django.conf import settings from django.db import models class UserOwnedModelManager(models.Manager): def filter_for_user(self, user, *args, **kwargs): return super(UserOwnedModelManager, self).get_queryset().filter(user = user, *args, **kwargs) def get_for_user(self, user, *args, **kwargs): if 'user' in kwargs: kwargs.pop('user') return super(UserOwnedModelManager, self).get_queryset().get(user = user, *args, **kwargs) class UserOwnedModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, editable = False) objects = UserOwnedModelManager() class Meta: abstract = TrueAdd `get_or_create_for_user` method to default Manager.
from django.conf import settings from django.db import models class UserOwnedModelManager(models.Manager): def filter_for_user(self, user, *args, **kwargs): return super(UserOwnedModelManager, self).get_queryset().filter(user = user, *args, **kwargs) def get_for_user(self, user, *args, **kwargs): if 'user' in kwargs: kwargs.pop('user') return super(UserOwnedModelManager, self).get_queryset().get(user = user, *args, **kwargs) def get_or_create_for_user(self, user, **kwargs): return super(UserOwnedModelManager, self).get_or_create(user = user, **kwargs) class UserOwnedModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, editable = False) objects = UserOwnedModelManager() class Meta: abstract = True
<commit_before>from django.conf import settings from django.db import models class UserOwnedModelManager(models.Manager): def filter_for_user(self, user, *args, **kwargs): return super(UserOwnedModelManager, self).get_queryset().filter(user = user, *args, **kwargs) def get_for_user(self, user, *args, **kwargs): if 'user' in kwargs: kwargs.pop('user') return super(UserOwnedModelManager, self).get_queryset().get(user = user, *args, **kwargs) class UserOwnedModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, editable = False) objects = UserOwnedModelManager() class Meta: abstract = True<commit_msg>Add `get_or_create_for_user` method to default Manager.<commit_after>
from django.conf import settings from django.db import models class UserOwnedModelManager(models.Manager): def filter_for_user(self, user, *args, **kwargs): return super(UserOwnedModelManager, self).get_queryset().filter(user = user, *args, **kwargs) def get_for_user(self, user, *args, **kwargs): if 'user' in kwargs: kwargs.pop('user') return super(UserOwnedModelManager, self).get_queryset().get(user = user, *args, **kwargs) def get_or_create_for_user(self, user, **kwargs): return super(UserOwnedModelManager, self).get_or_create(user = user, **kwargs) class UserOwnedModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, editable = False) objects = UserOwnedModelManager() class Meta: abstract = True
from django.conf import settings from django.db import models class UserOwnedModelManager(models.Manager): def filter_for_user(self, user, *args, **kwargs): return super(UserOwnedModelManager, self).get_queryset().filter(user = user, *args, **kwargs) def get_for_user(self, user, *args, **kwargs): if 'user' in kwargs: kwargs.pop('user') return super(UserOwnedModelManager, self).get_queryset().get(user = user, *args, **kwargs) class UserOwnedModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, editable = False) objects = UserOwnedModelManager() class Meta: abstract = TrueAdd `get_or_create_for_user` method to default Manager.from django.conf import settings from django.db import models class UserOwnedModelManager(models.Manager): def filter_for_user(self, user, *args, **kwargs): return super(UserOwnedModelManager, self).get_queryset().filter(user = user, *args, **kwargs) def get_for_user(self, user, *args, **kwargs): if 'user' in kwargs: kwargs.pop('user') return super(UserOwnedModelManager, self).get_queryset().get(user = user, *args, **kwargs) def get_or_create_for_user(self, user, **kwargs): return super(UserOwnedModelManager, self).get_or_create(user = user, **kwargs) class UserOwnedModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, editable = False) objects = UserOwnedModelManager() class Meta: abstract = True
<commit_before>from django.conf import settings from django.db import models class UserOwnedModelManager(models.Manager): def filter_for_user(self, user, *args, **kwargs): return super(UserOwnedModelManager, self).get_queryset().filter(user = user, *args, **kwargs) def get_for_user(self, user, *args, **kwargs): if 'user' in kwargs: kwargs.pop('user') return super(UserOwnedModelManager, self).get_queryset().get(user = user, *args, **kwargs) class UserOwnedModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, editable = False) objects = UserOwnedModelManager() class Meta: abstract = True<commit_msg>Add `get_or_create_for_user` method to default Manager.<commit_after>from django.conf import settings from django.db import models class UserOwnedModelManager(models.Manager): def filter_for_user(self, user, *args, **kwargs): return super(UserOwnedModelManager, self).get_queryset().filter(user = user, *args, **kwargs) def get_for_user(self, user, *args, **kwargs): if 'user' in kwargs: kwargs.pop('user') return super(UserOwnedModelManager, self).get_queryset().get(user = user, *args, **kwargs) def get_or_create_for_user(self, user, **kwargs): return super(UserOwnedModelManager, self).get_or_create(user = user, **kwargs) class UserOwnedModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, editable = False) objects = UserOwnedModelManager() class Meta: abstract = True
10f48f8a8d71a237b97f7952cf8164d0c5138886
budget_proj/budget_app/urls.py
budget_proj/budget_app/urls.py
from django.conf.urls import url from . import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='hackoregon_budget') # Listed in alphabetical order. urlpatterns = [ url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ]
from django.conf.urls import url from . import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='hackoregon_budget') # Listed in alphabetical order. urlpatterns = [ url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^ocrb-prod/$', views.OcrbList.as_view()), url(r'^kpm-prod/$', views.KpmList.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ]
Add endpoints for AWS production feeds
Add endpoints for AWS production feeds Added endpoints for pulling the data from AWS (vs pulling from CSV)
Python
mit
hackoregon/team-budget,jimtyhurst/team-budget,hackoregon/team-budget,hackoregon/team-budget,jimtyhurst/team-budget,jimtyhurst/team-budget
from django.conf.urls import url from . import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='hackoregon_budget') # Listed in alphabetical order. urlpatterns = [ url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ]Add endpoints for AWS production feeds Added endpoints for pulling the data from AWS (vs pulling from CSV)
from django.conf.urls import url from . import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='hackoregon_budget') # Listed in alphabetical order. urlpatterns = [ url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^ocrb-prod/$', views.OcrbList.as_view()), url(r'^kpm-prod/$', views.KpmList.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ]
<commit_before>from django.conf.urls import url from . import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='hackoregon_budget') # Listed in alphabetical order. urlpatterns = [ url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ]<commit_msg>Add endpoints for AWS production feeds Added endpoints for pulling the data from AWS (vs pulling from CSV)<commit_after>
from django.conf.urls import url from . import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='hackoregon_budget') # Listed in alphabetical order. urlpatterns = [ url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^ocrb-prod/$', views.OcrbList.as_view()), url(r'^kpm-prod/$', views.KpmList.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ]
from django.conf.urls import url from . import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='hackoregon_budget') # Listed in alphabetical order. urlpatterns = [ url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ]Add endpoints for AWS production feeds Added endpoints for pulling the data from AWS (vs pulling from CSV)from django.conf.urls import url from . import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='hackoregon_budget') # Listed in alphabetical order. urlpatterns = [ url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^ocrb-prod/$', views.OcrbList.as_view()), url(r'^kpm-prod/$', views.KpmList.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ]
<commit_before>from django.conf.urls import url from . import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='hackoregon_budget') # Listed in alphabetical order. urlpatterns = [ url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ]<commit_msg>Add endpoints for AWS production feeds Added endpoints for pulling the data from AWS (vs pulling from CSV)<commit_after>from django.conf.urls import url from . import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='hackoregon_budget') # Listed in alphabetical order. urlpatterns = [ url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^ocrb-prod/$', views.OcrbList.as_view()), url(r'^kpm-prod/$', views.KpmList.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ]
ea87538d29e4d6e9d3904e6ead86ebe4eb958aff
lib/reinteract/about_dialog.py
lib/reinteract/about_dialog.py
import gtk import os def _find_program_in_path(progname): try: path = os.environ['PATH'] except KeyError: path = os.defpath for dir in path.split(os.pathsep): p = os.path.join(dir, progname) if os.path.exists(p): return p return None def _find_url_open_program(): for progname in ['xdg-open', 'htmlview', 'gnome-open']: path = _find_program_in_path(progname) if path != None: return path return None def _open_url(dialog, url): prog = _find_url_open_program() os.spawnl(os.P_NOWAIT, prog, prog, url) class AboutDialog(gtk.AboutDialog): def __init__(self, parent): gtk.AboutDialog.__init__(self) self.set_transient_for(parent) self.set_name("Reinteract") self.set_logo_icon_name("reinteract") self.set_copyright("Copyright \302\251 2007-2008 Owen Taylor, Red Hat, Inc., and others") self.set_website("http://www.reinteract.org") self.connect("response", lambda d, r: d.destroy()) def run(self): if _find_url_open_program() != None: gtk.about_dialog_set_url_hook(_open_url) gtk.AboutDialog.run(self)
import gtk import os import sys def _find_program_in_path(progname): try: path = os.environ['PATH'] except KeyError: path = os.defpath for dir in path.split(os.pathsep): p = os.path.join(dir, progname) if os.path.exists(p): return p return None def _find_url_open_program(): if sys.platform == 'darwin': return '/usr/bin/open' for progname in ['xdg-open', 'htmlview', 'gnome-open']: path = _find_program_in_path(progname) if path != None: return path return None def _open_url(dialog, url): prog = _find_url_open_program() os.spawnl(os.P_NOWAIT, prog, prog, url) class AboutDialog(gtk.AboutDialog): def __init__(self, parent): gtk.AboutDialog.__init__(self) self.set_transient_for(parent) self.set_name("Reinteract") self.set_logo_icon_name("reinteract") self.set_copyright("Copyright \302\251 2007-2008 Owen Taylor, Red Hat, Inc., and others") self.set_website("http://www.reinteract.org") self.connect("response", lambda d, r: d.destroy()) def run(self): if _find_url_open_program() != None: gtk.about_dialog_set_url_hook(_open_url) gtk.AboutDialog.run(self)
Use 'open' to open about dialog URLs on OS X
Use 'open' to open about dialog URLs on OS X
Python
bsd-2-clause
johnrizzo1/reinteract,alexey4petrov/reinteract,alexey4petrov/reinteract,rschroll/reinteract,johnrizzo1/reinteract,rschroll/reinteract,jbaayen/reinteract,alexey4petrov/reinteract,jbaayen/reinteract,jbaayen/reinteract,johnrizzo1/reinteract,rschroll/reinteract
import gtk import os def _find_program_in_path(progname): try: path = os.environ['PATH'] except KeyError: path = os.defpath for dir in path.split(os.pathsep): p = os.path.join(dir, progname) if os.path.exists(p): return p return None def _find_url_open_program(): for progname in ['xdg-open', 'htmlview', 'gnome-open']: path = _find_program_in_path(progname) if path != None: return path return None def _open_url(dialog, url): prog = _find_url_open_program() os.spawnl(os.P_NOWAIT, prog, prog, url) class AboutDialog(gtk.AboutDialog): def __init__(self, parent): gtk.AboutDialog.__init__(self) self.set_transient_for(parent) self.set_name("Reinteract") self.set_logo_icon_name("reinteract") self.set_copyright("Copyright \302\251 2007-2008 Owen Taylor, Red Hat, Inc., and others") self.set_website("http://www.reinteract.org") self.connect("response", lambda d, r: d.destroy()) def run(self): if _find_url_open_program() != None: gtk.about_dialog_set_url_hook(_open_url) gtk.AboutDialog.run(self) Use 'open' to open about dialog URLs on OS X
import gtk import os import sys def _find_program_in_path(progname): try: path = os.environ['PATH'] except KeyError: path = os.defpath for dir in path.split(os.pathsep): p = os.path.join(dir, progname) if os.path.exists(p): return p return None def _find_url_open_program(): if sys.platform == 'darwin': return '/usr/bin/open' for progname in ['xdg-open', 'htmlview', 'gnome-open']: path = _find_program_in_path(progname) if path != None: return path return None def _open_url(dialog, url): prog = _find_url_open_program() os.spawnl(os.P_NOWAIT, prog, prog, url) class AboutDialog(gtk.AboutDialog): def __init__(self, parent): gtk.AboutDialog.__init__(self) self.set_transient_for(parent) self.set_name("Reinteract") self.set_logo_icon_name("reinteract") self.set_copyright("Copyright \302\251 2007-2008 Owen Taylor, Red Hat, Inc., and others") self.set_website("http://www.reinteract.org") self.connect("response", lambda d, r: d.destroy()) def run(self): if _find_url_open_program() != None: gtk.about_dialog_set_url_hook(_open_url) gtk.AboutDialog.run(self)
<commit_before>import gtk import os def _find_program_in_path(progname): try: path = os.environ['PATH'] except KeyError: path = os.defpath for dir in path.split(os.pathsep): p = os.path.join(dir, progname) if os.path.exists(p): return p return None def _find_url_open_program(): for progname in ['xdg-open', 'htmlview', 'gnome-open']: path = _find_program_in_path(progname) if path != None: return path return None def _open_url(dialog, url): prog = _find_url_open_program() os.spawnl(os.P_NOWAIT, prog, prog, url) class AboutDialog(gtk.AboutDialog): def __init__(self, parent): gtk.AboutDialog.__init__(self) self.set_transient_for(parent) self.set_name("Reinteract") self.set_logo_icon_name("reinteract") self.set_copyright("Copyright \302\251 2007-2008 Owen Taylor, Red Hat, Inc., and others") self.set_website("http://www.reinteract.org") self.connect("response", lambda d, r: d.destroy()) def run(self): if _find_url_open_program() != None: gtk.about_dialog_set_url_hook(_open_url) gtk.AboutDialog.run(self) <commit_msg>Use 'open' to open about dialog URLs on OS X<commit_after>
import gtk import os import sys def _find_program_in_path(progname): try: path = os.environ['PATH'] except KeyError: path = os.defpath for dir in path.split(os.pathsep): p = os.path.join(dir, progname) if os.path.exists(p): return p return None def _find_url_open_program(): if sys.platform == 'darwin': return '/usr/bin/open' for progname in ['xdg-open', 'htmlview', 'gnome-open']: path = _find_program_in_path(progname) if path != None: return path return None def _open_url(dialog, url): prog = _find_url_open_program() os.spawnl(os.P_NOWAIT, prog, prog, url) class AboutDialog(gtk.AboutDialog): def __init__(self, parent): gtk.AboutDialog.__init__(self) self.set_transient_for(parent) self.set_name("Reinteract") self.set_logo_icon_name("reinteract") self.set_copyright("Copyright \302\251 2007-2008 Owen Taylor, Red Hat, Inc., and others") self.set_website("http://www.reinteract.org") self.connect("response", lambda d, r: d.destroy()) def run(self): if _find_url_open_program() != None: gtk.about_dialog_set_url_hook(_open_url) gtk.AboutDialog.run(self)
import gtk import os def _find_program_in_path(progname): try: path = os.environ['PATH'] except KeyError: path = os.defpath for dir in path.split(os.pathsep): p = os.path.join(dir, progname) if os.path.exists(p): return p return None def _find_url_open_program(): for progname in ['xdg-open', 'htmlview', 'gnome-open']: path = _find_program_in_path(progname) if path != None: return path return None def _open_url(dialog, url): prog = _find_url_open_program() os.spawnl(os.P_NOWAIT, prog, prog, url) class AboutDialog(gtk.AboutDialog): def __init__(self, parent): gtk.AboutDialog.__init__(self) self.set_transient_for(parent) self.set_name("Reinteract") self.set_logo_icon_name("reinteract") self.set_copyright("Copyright \302\251 2007-2008 Owen Taylor, Red Hat, Inc., and others") self.set_website("http://www.reinteract.org") self.connect("response", lambda d, r: d.destroy()) def run(self): if _find_url_open_program() != None: gtk.about_dialog_set_url_hook(_open_url) gtk.AboutDialog.run(self) Use 'open' to open about dialog URLs on OS Ximport gtk import os import sys def _find_program_in_path(progname): try: path = os.environ['PATH'] except KeyError: path = os.defpath for dir in path.split(os.pathsep): p = os.path.join(dir, progname) if os.path.exists(p): return p return None def _find_url_open_program(): if sys.platform == 'darwin': return '/usr/bin/open' for progname in ['xdg-open', 'htmlview', 'gnome-open']: path = _find_program_in_path(progname) if path != None: return path return None def _open_url(dialog, url): prog = _find_url_open_program() os.spawnl(os.P_NOWAIT, prog, prog, url) class AboutDialog(gtk.AboutDialog): def __init__(self, parent): gtk.AboutDialog.__init__(self) self.set_transient_for(parent) self.set_name("Reinteract") self.set_logo_icon_name("reinteract") self.set_copyright("Copyright \302\251 2007-2008 Owen Taylor, Red Hat, Inc., and others") self.set_website("http://www.reinteract.org") self.connect("response", lambda d, r: d.destroy()) def run(self): if _find_url_open_program() != None: gtk.about_dialog_set_url_hook(_open_url) gtk.AboutDialog.run(self)
<commit_before>import gtk import os def _find_program_in_path(progname): try: path = os.environ['PATH'] except KeyError: path = os.defpath for dir in path.split(os.pathsep): p = os.path.join(dir, progname) if os.path.exists(p): return p return None def _find_url_open_program(): for progname in ['xdg-open', 'htmlview', 'gnome-open']: path = _find_program_in_path(progname) if path != None: return path return None def _open_url(dialog, url): prog = _find_url_open_program() os.spawnl(os.P_NOWAIT, prog, prog, url) class AboutDialog(gtk.AboutDialog): def __init__(self, parent): gtk.AboutDialog.__init__(self) self.set_transient_for(parent) self.set_name("Reinteract") self.set_logo_icon_name("reinteract") self.set_copyright("Copyright \302\251 2007-2008 Owen Taylor, Red Hat, Inc., and others") self.set_website("http://www.reinteract.org") self.connect("response", lambda d, r: d.destroy()) def run(self): if _find_url_open_program() != None: gtk.about_dialog_set_url_hook(_open_url) gtk.AboutDialog.run(self) <commit_msg>Use 'open' to open about dialog URLs on OS X<commit_after>import gtk import os import sys def _find_program_in_path(progname): try: path = os.environ['PATH'] except KeyError: path = os.defpath for dir in path.split(os.pathsep): p = os.path.join(dir, progname) if os.path.exists(p): return p return None def _find_url_open_program(): if sys.platform == 'darwin': return '/usr/bin/open' for progname in ['xdg-open', 'htmlview', 'gnome-open']: path = _find_program_in_path(progname) if path != None: return path return None def _open_url(dialog, url): prog = _find_url_open_program() os.spawnl(os.P_NOWAIT, prog, prog, url) class AboutDialog(gtk.AboutDialog): def __init__(self, parent): gtk.AboutDialog.__init__(self) self.set_transient_for(parent) self.set_name("Reinteract") self.set_logo_icon_name("reinteract") self.set_copyright("Copyright \302\251 2007-2008 Owen Taylor, Red Hat, Inc., and others") self.set_website("http://www.reinteract.org") self.connect("response", lambda d, r: d.destroy()) def run(self): if _find_url_open_program() != None: gtk.about_dialog_set_url_hook(_open_url) gtk.AboutDialog.run(self)
95508fca6683220b52fb4853c3073b054775a377
activities/models.py
activities/models.py
from __future__ import unicode_literals from django.db import models class Activity(models.Model): datetime = models.DateTimeField(auto_now_add=True) detail = models.TextField(editable=False) to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to', blank=True, null=True) from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') class Meta: ordering = ['-datetime'] verbose_name_plural = 'activities' class Message(models.Model): datetime = models.DateTimeField(auto_now_add=True) message = models.TextField() from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to') class Meta: ordering = ['-datetime'] verbose_name_plural = 'messages'
from __future__ import unicode_literals from django.db import models class Activity(models.Model): datetime = models.DateTimeField(auto_now_add=True) detail = models.TextField(editable=False) to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to', blank=True, null=True) from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') class Meta: ordering = ['-datetime'] verbose_name_plural = 'activities' class Message(models.Model): datetime = models.DateTimeField(auto_now_add=True) message = models.TextField() from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') to_user = models.CharField(max_length=250) class Meta: ordering = ['-datetime'] verbose_name_plural = 'messages'
Change to_user to CharField for message model
Change to_user to CharField for message model
Python
apache-2.0
belatrix/BackendAllStars
from __future__ import unicode_literals from django.db import models class Activity(models.Model): datetime = models.DateTimeField(auto_now_add=True) detail = models.TextField(editable=False) to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to', blank=True, null=True) from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') class Meta: ordering = ['-datetime'] verbose_name_plural = 'activities' class Message(models.Model): datetime = models.DateTimeField(auto_now_add=True) message = models.TextField() from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to') class Meta: ordering = ['-datetime'] verbose_name_plural = 'messages' Change to_user to CharField for message model
from __future__ import unicode_literals from django.db import models class Activity(models.Model): datetime = models.DateTimeField(auto_now_add=True) detail = models.TextField(editable=False) to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to', blank=True, null=True) from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') class Meta: ordering = ['-datetime'] verbose_name_plural = 'activities' class Message(models.Model): datetime = models.DateTimeField(auto_now_add=True) message = models.TextField() from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') to_user = models.CharField(max_length=250) class Meta: ordering = ['-datetime'] verbose_name_plural = 'messages'
<commit_before>from __future__ import unicode_literals from django.db import models class Activity(models.Model): datetime = models.DateTimeField(auto_now_add=True) detail = models.TextField(editable=False) to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to', blank=True, null=True) from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') class Meta: ordering = ['-datetime'] verbose_name_plural = 'activities' class Message(models.Model): datetime = models.DateTimeField(auto_now_add=True) message = models.TextField() from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to') class Meta: ordering = ['-datetime'] verbose_name_plural = 'messages' <commit_msg>Change to_user to CharField for message model<commit_after>
from __future__ import unicode_literals from django.db import models class Activity(models.Model): datetime = models.DateTimeField(auto_now_add=True) detail = models.TextField(editable=False) to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to', blank=True, null=True) from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') class Meta: ordering = ['-datetime'] verbose_name_plural = 'activities' class Message(models.Model): datetime = models.DateTimeField(auto_now_add=True) message = models.TextField() from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') to_user = models.CharField(max_length=250) class Meta: ordering = ['-datetime'] verbose_name_plural = 'messages'
from __future__ import unicode_literals from django.db import models class Activity(models.Model): datetime = models.DateTimeField(auto_now_add=True) detail = models.TextField(editable=False) to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to', blank=True, null=True) from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') class Meta: ordering = ['-datetime'] verbose_name_plural = 'activities' class Message(models.Model): datetime = models.DateTimeField(auto_now_add=True) message = models.TextField() from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to') class Meta: ordering = ['-datetime'] verbose_name_plural = 'messages' Change to_user to CharField for message modelfrom __future__ import unicode_literals from django.db import models class Activity(models.Model): datetime = models.DateTimeField(auto_now_add=True) detail = models.TextField(editable=False) to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to', blank=True, null=True) from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') class Meta: ordering = ['-datetime'] verbose_name_plural = 'activities' class Message(models.Model): datetime = models.DateTimeField(auto_now_add=True) message = models.TextField() from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') to_user = models.CharField(max_length=250) class Meta: ordering = ['-datetime'] verbose_name_plural = 'messages'
<commit_before>from __future__ import unicode_literals from django.db import models class Activity(models.Model): datetime = models.DateTimeField(auto_now_add=True) detail = models.TextField(editable=False) to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to', blank=True, null=True) from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') class Meta: ordering = ['-datetime'] verbose_name_plural = 'activities' class Message(models.Model): datetime = models.DateTimeField(auto_now_add=True) message = models.TextField() from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to') class Meta: ordering = ['-datetime'] verbose_name_plural = 'messages' <commit_msg>Change to_user to CharField for message model<commit_after>from __future__ import unicode_literals from django.db import models class Activity(models.Model): datetime = models.DateTimeField(auto_now_add=True) detail = models.TextField(editable=False) to_user = models.ForeignKey('employees.Employee', related_name='%(class)s_to', blank=True, null=True) from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') class Meta: ordering = ['-datetime'] verbose_name_plural = 'activities' class Message(models.Model): datetime = models.DateTimeField(auto_now_add=True) message = models.TextField() from_user = models.ForeignKey('employees.Employee', related_name='%(class)s_from') to_user = models.CharField(max_length=250) class Meta: ordering = ['-datetime'] verbose_name_plural = 'messages'
e21693f8c08e805421cc9b207dd901ed0fcd85a7
tuskar_ui/infrastructure/history/views.py
tuskar_ui/infrastructure/history/views.py
# -*- coding: utf8 -*- # # 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 horizon import tables as horizon_tables from tuskar_ui import api from tuskar_ui.infrastructure.history import tables class IndexView(horizon_tables.DataTableView): table_class = tables.HistoryTable template_name = "infrastructure/history/index.html" def get_data(self): plan = api.tuskar.OvercloudPlan.get_the_plan(self.request) if plan: stack = api.heat.Stack.get_by_plan(self.request, plan) if stack: return stack.events
# -*- coding: utf8 -*- # # 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 horizon import tables as horizon_tables from tuskar_ui import api from tuskar_ui.infrastructure.history import tables class IndexView(horizon_tables.DataTableView): table_class = tables.HistoryTable template_name = "infrastructure/history/index.html" def get_data(self): plan = api.tuskar.OvercloudPlan.get_the_plan(self.request) if plan: stack = api.heat.Stack.get_by_plan(self.request, plan) if stack: return stack.events return []
Fix error in History table if stack does not exist
Fix error in History table if stack does not exist Change-Id: Ic47761ddff23207a30eae0b7b523a996c545b3ba
Python
apache-2.0
rdo-management/tuskar-ui,rdo-management/tuskar-ui,rdo-management/tuskar-ui,rdo-management/tuskar-ui
# -*- coding: utf8 -*- # # 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 horizon import tables as horizon_tables from tuskar_ui import api from tuskar_ui.infrastructure.history import tables class IndexView(horizon_tables.DataTableView): table_class = tables.HistoryTable template_name = "infrastructure/history/index.html" def get_data(self): plan = api.tuskar.OvercloudPlan.get_the_plan(self.request) if plan: stack = api.heat.Stack.get_by_plan(self.request, plan) if stack: return stack.events Fix error in History table if stack does not exist Change-Id: Ic47761ddff23207a30eae0b7b523a996c545b3ba
# -*- coding: utf8 -*- # # 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 horizon import tables as horizon_tables from tuskar_ui import api from tuskar_ui.infrastructure.history import tables class IndexView(horizon_tables.DataTableView): table_class = tables.HistoryTable template_name = "infrastructure/history/index.html" def get_data(self): plan = api.tuskar.OvercloudPlan.get_the_plan(self.request) if plan: stack = api.heat.Stack.get_by_plan(self.request, plan) if stack: return stack.events return []
<commit_before># -*- coding: utf8 -*- # # 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 horizon import tables as horizon_tables from tuskar_ui import api from tuskar_ui.infrastructure.history import tables class IndexView(horizon_tables.DataTableView): table_class = tables.HistoryTable template_name = "infrastructure/history/index.html" def get_data(self): plan = api.tuskar.OvercloudPlan.get_the_plan(self.request) if plan: stack = api.heat.Stack.get_by_plan(self.request, plan) if stack: return stack.events <commit_msg>Fix error in History table if stack does not exist Change-Id: Ic47761ddff23207a30eae0b7b523a996c545b3ba<commit_after>
# -*- coding: utf8 -*- # # 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 horizon import tables as horizon_tables from tuskar_ui import api from tuskar_ui.infrastructure.history import tables class IndexView(horizon_tables.DataTableView): table_class = tables.HistoryTable template_name = "infrastructure/history/index.html" def get_data(self): plan = api.tuskar.OvercloudPlan.get_the_plan(self.request) if plan: stack = api.heat.Stack.get_by_plan(self.request, plan) if stack: return stack.events return []
# -*- coding: utf8 -*- # # 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 horizon import tables as horizon_tables from tuskar_ui import api from tuskar_ui.infrastructure.history import tables class IndexView(horizon_tables.DataTableView): table_class = tables.HistoryTable template_name = "infrastructure/history/index.html" def get_data(self): plan = api.tuskar.OvercloudPlan.get_the_plan(self.request) if plan: stack = api.heat.Stack.get_by_plan(self.request, plan) if stack: return stack.events Fix error in History table if stack does not exist Change-Id: Ic47761ddff23207a30eae0b7b523a996c545b3ba# -*- coding: utf8 -*- # # 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 horizon import tables as horizon_tables from tuskar_ui import api from tuskar_ui.infrastructure.history import tables class IndexView(horizon_tables.DataTableView): table_class = tables.HistoryTable template_name = "infrastructure/history/index.html" def get_data(self): plan = api.tuskar.OvercloudPlan.get_the_plan(self.request) if plan: stack = api.heat.Stack.get_by_plan(self.request, plan) if stack: return stack.events return []
<commit_before># -*- coding: utf8 -*- # # 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 horizon import tables as horizon_tables from tuskar_ui import api from tuskar_ui.infrastructure.history import tables class IndexView(horizon_tables.DataTableView): table_class = tables.HistoryTable template_name = "infrastructure/history/index.html" def get_data(self): plan = api.tuskar.OvercloudPlan.get_the_plan(self.request) if plan: stack = api.heat.Stack.get_by_plan(self.request, plan) if stack: return stack.events <commit_msg>Fix error in History table if stack does not exist Change-Id: Ic47761ddff23207a30eae0b7b523a996c545b3ba<commit_after># -*- coding: utf8 -*- # # 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 horizon import tables as horizon_tables from tuskar_ui import api from tuskar_ui.infrastructure.history import tables class IndexView(horizon_tables.DataTableView): table_class = tables.HistoryTable template_name = "infrastructure/history/index.html" def get_data(self): plan = api.tuskar.OvercloudPlan.get_the_plan(self.request) if plan: stack = api.heat.Stack.get_by_plan(self.request, plan) if stack: return stack.events return []
09bc3137328fbefe41044b5124f3c6a7abaa8982
wqflask/tests/base/test_general_object.py
wqflask/tests/base/test_general_object.py
import unittest from base.GeneralObject import GeneralObject class TestGeneralObjectTests(unittest.TestCase): """ Test the GeneralObject base class """ def test_object_contents(self): """Test whether base contents are stored properly""" test_obj = GeneralObject("a", "b", "c") self.assertEqual("abc", ''.join(test_obj.contents)) self.assertEqual(len(test_obj), 0) def test_object_dict(self): """Test whether the base class is printed properly""" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(str(test_obj), "value = 1\nname = test\n") self.assertEqual( repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") self.assertEqual(len(test_obj), 2) self.assertEqual(getattr(test_obj, "value"), 1) self.assertEqual(test_obj["value"], 1) test_obj["test"] = 1 self.assertEqual(test_obj["test"], 1)
import unittest from base.GeneralObject import GeneralObject class TestGeneralObjectTests(unittest.TestCase): """ Test the GeneralObject base class """ def test_object_contents(self): """Test whether base contents are stored properly""" test_obj = GeneralObject("a", "b", "c") self.assertEqual("abc", ''.join(test_obj.contents)) self.assertEqual(len(test_obj), 0) def test_object_dict(self): """Test whether the base class is printed properly""" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(str(test_obj), "value = 1\nname = test\n") self.assertEqual( repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") self.assertEqual(len(test_obj), 2) self.assertEqual(test_obj["value"], 1) test_obj["test"] = 1 self.assertEqual(test_obj["test"], 1) def test_get_attribute(self): "Test that getattr works" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(getattr(test_obj, "value", None), 1) self.assertEqual(getattr(test_obj, "non-existent", None), None) def test_object_comparisons(self): "Test that 2 objects of the same length are equal" test_obj1 = GeneralObject("a", name="test", value=1) test_obj2 = GeneralObject("b", name="test2", value=2) test_obj3 = GeneralObject("a", name="test", x=1, y=2) self.assertTrue(test_obj1 == test_obj2 ) self.assertFalse(test_obj1 == test_obj3 )
Add more tests for general_object
Add more tests for general_object * wqflask/tests/base/test_general_object.py: test getattr() and `==`
Python
agpl-3.0
genenetwork/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2
import unittest from base.GeneralObject import GeneralObject class TestGeneralObjectTests(unittest.TestCase): """ Test the GeneralObject base class """ def test_object_contents(self): """Test whether base contents are stored properly""" test_obj = GeneralObject("a", "b", "c") self.assertEqual("abc", ''.join(test_obj.contents)) self.assertEqual(len(test_obj), 0) def test_object_dict(self): """Test whether the base class is printed properly""" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(str(test_obj), "value = 1\nname = test\n") self.assertEqual( repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") self.assertEqual(len(test_obj), 2) self.assertEqual(getattr(test_obj, "value"), 1) self.assertEqual(test_obj["value"], 1) test_obj["test"] = 1 self.assertEqual(test_obj["test"], 1) Add more tests for general_object * wqflask/tests/base/test_general_object.py: test getattr() and `==`
import unittest from base.GeneralObject import GeneralObject class TestGeneralObjectTests(unittest.TestCase): """ Test the GeneralObject base class """ def test_object_contents(self): """Test whether base contents are stored properly""" test_obj = GeneralObject("a", "b", "c") self.assertEqual("abc", ''.join(test_obj.contents)) self.assertEqual(len(test_obj), 0) def test_object_dict(self): """Test whether the base class is printed properly""" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(str(test_obj), "value = 1\nname = test\n") self.assertEqual( repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") self.assertEqual(len(test_obj), 2) self.assertEqual(test_obj["value"], 1) test_obj["test"] = 1 self.assertEqual(test_obj["test"], 1) def test_get_attribute(self): "Test that getattr works" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(getattr(test_obj, "value", None), 1) self.assertEqual(getattr(test_obj, "non-existent", None), None) def test_object_comparisons(self): "Test that 2 objects of the same length are equal" test_obj1 = GeneralObject("a", name="test", value=1) test_obj2 = GeneralObject("b", name="test2", value=2) test_obj3 = GeneralObject("a", name="test", x=1, y=2) self.assertTrue(test_obj1 == test_obj2 ) self.assertFalse(test_obj1 == test_obj3 )
<commit_before>import unittest from base.GeneralObject import GeneralObject class TestGeneralObjectTests(unittest.TestCase): """ Test the GeneralObject base class """ def test_object_contents(self): """Test whether base contents are stored properly""" test_obj = GeneralObject("a", "b", "c") self.assertEqual("abc", ''.join(test_obj.contents)) self.assertEqual(len(test_obj), 0) def test_object_dict(self): """Test whether the base class is printed properly""" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(str(test_obj), "value = 1\nname = test\n") self.assertEqual( repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") self.assertEqual(len(test_obj), 2) self.assertEqual(getattr(test_obj, "value"), 1) self.assertEqual(test_obj["value"], 1) test_obj["test"] = 1 self.assertEqual(test_obj["test"], 1) <commit_msg>Add more tests for general_object * wqflask/tests/base/test_general_object.py: test getattr() and `==`<commit_after>
import unittest from base.GeneralObject import GeneralObject class TestGeneralObjectTests(unittest.TestCase): """ Test the GeneralObject base class """ def test_object_contents(self): """Test whether base contents are stored properly""" test_obj = GeneralObject("a", "b", "c") self.assertEqual("abc", ''.join(test_obj.contents)) self.assertEqual(len(test_obj), 0) def test_object_dict(self): """Test whether the base class is printed properly""" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(str(test_obj), "value = 1\nname = test\n") self.assertEqual( repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") self.assertEqual(len(test_obj), 2) self.assertEqual(test_obj["value"], 1) test_obj["test"] = 1 self.assertEqual(test_obj["test"], 1) def test_get_attribute(self): "Test that getattr works" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(getattr(test_obj, "value", None), 1) self.assertEqual(getattr(test_obj, "non-existent", None), None) def test_object_comparisons(self): "Test that 2 objects of the same length are equal" test_obj1 = GeneralObject("a", name="test", value=1) test_obj2 = GeneralObject("b", name="test2", value=2) test_obj3 = GeneralObject("a", name="test", x=1, y=2) self.assertTrue(test_obj1 == test_obj2 ) self.assertFalse(test_obj1 == test_obj3 )
import unittest from base.GeneralObject import GeneralObject class TestGeneralObjectTests(unittest.TestCase): """ Test the GeneralObject base class """ def test_object_contents(self): """Test whether base contents are stored properly""" test_obj = GeneralObject("a", "b", "c") self.assertEqual("abc", ''.join(test_obj.contents)) self.assertEqual(len(test_obj), 0) def test_object_dict(self): """Test whether the base class is printed properly""" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(str(test_obj), "value = 1\nname = test\n") self.assertEqual( repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") self.assertEqual(len(test_obj), 2) self.assertEqual(getattr(test_obj, "value"), 1) self.assertEqual(test_obj["value"], 1) test_obj["test"] = 1 self.assertEqual(test_obj["test"], 1) Add more tests for general_object * wqflask/tests/base/test_general_object.py: test getattr() and `==`import unittest from base.GeneralObject import GeneralObject class TestGeneralObjectTests(unittest.TestCase): """ Test the GeneralObject base class """ def test_object_contents(self): """Test whether base contents are stored properly""" test_obj = GeneralObject("a", "b", "c") self.assertEqual("abc", ''.join(test_obj.contents)) self.assertEqual(len(test_obj), 0) def test_object_dict(self): """Test whether the base class is printed properly""" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(str(test_obj), "value = 1\nname = test\n") self.assertEqual( repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") self.assertEqual(len(test_obj), 2) self.assertEqual(test_obj["value"], 1) test_obj["test"] = 1 self.assertEqual(test_obj["test"], 1) def test_get_attribute(self): "Test that getattr works" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(getattr(test_obj, "value", None), 1) self.assertEqual(getattr(test_obj, "non-existent", None), None) def test_object_comparisons(self): "Test that 2 objects of the same length are equal" test_obj1 = GeneralObject("a", name="test", value=1) test_obj2 = GeneralObject("b", name="test2", value=2) test_obj3 = GeneralObject("a", name="test", x=1, y=2) self.assertTrue(test_obj1 == test_obj2 ) self.assertFalse(test_obj1 == test_obj3 )
<commit_before>import unittest from base.GeneralObject import GeneralObject class TestGeneralObjectTests(unittest.TestCase): """ Test the GeneralObject base class """ def test_object_contents(self): """Test whether base contents are stored properly""" test_obj = GeneralObject("a", "b", "c") self.assertEqual("abc", ''.join(test_obj.contents)) self.assertEqual(len(test_obj), 0) def test_object_dict(self): """Test whether the base class is printed properly""" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(str(test_obj), "value = 1\nname = test\n") self.assertEqual( repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") self.assertEqual(len(test_obj), 2) self.assertEqual(getattr(test_obj, "value"), 1) self.assertEqual(test_obj["value"], 1) test_obj["test"] = 1 self.assertEqual(test_obj["test"], 1) <commit_msg>Add more tests for general_object * wqflask/tests/base/test_general_object.py: test getattr() and `==`<commit_after>import unittest from base.GeneralObject import GeneralObject class TestGeneralObjectTests(unittest.TestCase): """ Test the GeneralObject base class """ def test_object_contents(self): """Test whether base contents are stored properly""" test_obj = GeneralObject("a", "b", "c") self.assertEqual("abc", ''.join(test_obj.contents)) self.assertEqual(len(test_obj), 0) def test_object_dict(self): """Test whether the base class is printed properly""" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(str(test_obj), "value = 1\nname = test\n") self.assertEqual( repr(test_obj), "value = 1\nname = test\ncontents = ['a']\n") self.assertEqual(len(test_obj), 2) self.assertEqual(test_obj["value"], 1) test_obj["test"] = 1 self.assertEqual(test_obj["test"], 1) def test_get_attribute(self): "Test that getattr works" test_obj = GeneralObject("a", name="test", value=1) self.assertEqual(getattr(test_obj, "value", None), 1) self.assertEqual(getattr(test_obj, "non-existent", None), None) def test_object_comparisons(self): "Test that 2 objects of the same length are equal" test_obj1 = GeneralObject("a", name="test", value=1) test_obj2 = GeneralObject("b", name="test2", value=2) test_obj3 = GeneralObject("a", name="test", x=1, y=2) self.assertTrue(test_obj1 == test_obj2 ) self.assertFalse(test_obj1 == test_obj3 )
36916009198abca34c4457d93bc65abea6193d75
yunity/tests/unit/test__utils__session.py
yunity/tests/unit/test__utils__session.py
from django.test import TestCase from yunity.utils.session import RealtimeClientData class TestSharedSession(TestCase): def test_session_key(self): self.assertEqual(RealtimeClientData.session_key('123'), 'session-store-123') def test_set_get_django_redis(self): RealtimeClientData.set_user_session('123', 3) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '3') RealtimeClientData.set_user_session('123', 4) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '4') def test_integration_data_to_users(self): """ This is a RealtimeClient integration test. For current implementation, subscribe to the notifications topic to see it working: redis-cli subscribe notifications """ RealtimeClientData.set_user_session('123', 3) RealtimeClientData.send_to_users([3], {'msg': 'hello'})
from django.test import TestCase from yunity.utils.session import RealtimeClientData class TestSharedSession(TestCase): def test_session_key(self): self.assertEqual(RealtimeClientData.session_key('123'), 'session-store-123') def test_set_get_django_redis(self): RealtimeClientData.set_user_session('123', 3) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '3') RealtimeClientData.set_user_session('123', 4) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '4') def test_integration_data_to_users(self): """ This is a RealtimeClient integration test. For current implementation, subscribe to the notifications topic to see it working: redis-cli subscribe notifications """ RealtimeClientData.set_user_session('123', 3) RealtimeClientData.send_to_users([3], RealtimeClientData.Types.CHAT_MESSAGE, {'msg': 'hello'})
Fix missing refactorization in unit test
Fix missing refactorization in unit test send_to_users unit test was not modified after parameter change.
Python
agpl-3.0
yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core
from django.test import TestCase from yunity.utils.session import RealtimeClientData class TestSharedSession(TestCase): def test_session_key(self): self.assertEqual(RealtimeClientData.session_key('123'), 'session-store-123') def test_set_get_django_redis(self): RealtimeClientData.set_user_session('123', 3) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '3') RealtimeClientData.set_user_session('123', 4) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '4') def test_integration_data_to_users(self): """ This is a RealtimeClient integration test. For current implementation, subscribe to the notifications topic to see it working: redis-cli subscribe notifications """ RealtimeClientData.set_user_session('123', 3) RealtimeClientData.send_to_users([3], {'msg': 'hello'}) Fix missing refactorization in unit test send_to_users unit test was not modified after parameter change.
from django.test import TestCase from yunity.utils.session import RealtimeClientData class TestSharedSession(TestCase): def test_session_key(self): self.assertEqual(RealtimeClientData.session_key('123'), 'session-store-123') def test_set_get_django_redis(self): RealtimeClientData.set_user_session('123', 3) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '3') RealtimeClientData.set_user_session('123', 4) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '4') def test_integration_data_to_users(self): """ This is a RealtimeClient integration test. For current implementation, subscribe to the notifications topic to see it working: redis-cli subscribe notifications """ RealtimeClientData.set_user_session('123', 3) RealtimeClientData.send_to_users([3], RealtimeClientData.Types.CHAT_MESSAGE, {'msg': 'hello'})
<commit_before>from django.test import TestCase from yunity.utils.session import RealtimeClientData class TestSharedSession(TestCase): def test_session_key(self): self.assertEqual(RealtimeClientData.session_key('123'), 'session-store-123') def test_set_get_django_redis(self): RealtimeClientData.set_user_session('123', 3) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '3') RealtimeClientData.set_user_session('123', 4) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '4') def test_integration_data_to_users(self): """ This is a RealtimeClient integration test. For current implementation, subscribe to the notifications topic to see it working: redis-cli subscribe notifications """ RealtimeClientData.set_user_session('123', 3) RealtimeClientData.send_to_users([3], {'msg': 'hello'}) <commit_msg>Fix missing refactorization in unit test send_to_users unit test was not modified after parameter change.<commit_after>
from django.test import TestCase from yunity.utils.session import RealtimeClientData class TestSharedSession(TestCase): def test_session_key(self): self.assertEqual(RealtimeClientData.session_key('123'), 'session-store-123') def test_set_get_django_redis(self): RealtimeClientData.set_user_session('123', 3) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '3') RealtimeClientData.set_user_session('123', 4) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '4') def test_integration_data_to_users(self): """ This is a RealtimeClient integration test. For current implementation, subscribe to the notifications topic to see it working: redis-cli subscribe notifications """ RealtimeClientData.set_user_session('123', 3) RealtimeClientData.send_to_users([3], RealtimeClientData.Types.CHAT_MESSAGE, {'msg': 'hello'})
from django.test import TestCase from yunity.utils.session import RealtimeClientData class TestSharedSession(TestCase): def test_session_key(self): self.assertEqual(RealtimeClientData.session_key('123'), 'session-store-123') def test_set_get_django_redis(self): RealtimeClientData.set_user_session('123', 3) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '3') RealtimeClientData.set_user_session('123', 4) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '4') def test_integration_data_to_users(self): """ This is a RealtimeClient integration test. For current implementation, subscribe to the notifications topic to see it working: redis-cli subscribe notifications """ RealtimeClientData.set_user_session('123', 3) RealtimeClientData.send_to_users([3], {'msg': 'hello'}) Fix missing refactorization in unit test send_to_users unit test was not modified after parameter change.from django.test import TestCase from yunity.utils.session import RealtimeClientData class TestSharedSession(TestCase): def test_session_key(self): self.assertEqual(RealtimeClientData.session_key('123'), 'session-store-123') def test_set_get_django_redis(self): RealtimeClientData.set_user_session('123', 3) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '3') RealtimeClientData.set_user_session('123', 4) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '4') def test_integration_data_to_users(self): """ This is a RealtimeClient integration test. For current implementation, subscribe to the notifications topic to see it working: redis-cli subscribe notifications """ RealtimeClientData.set_user_session('123', 3) RealtimeClientData.send_to_users([3], RealtimeClientData.Types.CHAT_MESSAGE, {'msg': 'hello'})
<commit_before>from django.test import TestCase from yunity.utils.session import RealtimeClientData class TestSharedSession(TestCase): def test_session_key(self): self.assertEqual(RealtimeClientData.session_key('123'), 'session-store-123') def test_set_get_django_redis(self): RealtimeClientData.set_user_session('123', 3) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '3') RealtimeClientData.set_user_session('123', 4) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '4') def test_integration_data_to_users(self): """ This is a RealtimeClient integration test. For current implementation, subscribe to the notifications topic to see it working: redis-cli subscribe notifications """ RealtimeClientData.set_user_session('123', 3) RealtimeClientData.send_to_users([3], {'msg': 'hello'}) <commit_msg>Fix missing refactorization in unit test send_to_users unit test was not modified after parameter change.<commit_after>from django.test import TestCase from yunity.utils.session import RealtimeClientData class TestSharedSession(TestCase): def test_session_key(self): self.assertEqual(RealtimeClientData.session_key('123'), 'session-store-123') def test_set_get_django_redis(self): RealtimeClientData.set_user_session('123', 3) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '3') RealtimeClientData.set_user_session('123', 4) self.assertEqual(RealtimeClientData.get_user_by_session('123'), '4') def test_integration_data_to_users(self): """ This is a RealtimeClient integration test. For current implementation, subscribe to the notifications topic to see it working: redis-cli subscribe notifications """ RealtimeClientData.set_user_session('123', 3) RealtimeClientData.send_to_users([3], RealtimeClientData.Types.CHAT_MESSAGE, {'msg': 'hello'})
a52bd5acd50d37314247e4ffaed501ba08e0eca3
tests/test_simple_model.py
tests/test_simple_model.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) @pytest.mark.parametrize('t1', T_VALUES) def test_invalid_dim(t1, get_model): """ Check that an error is raised when the dimension does not match the hopping matrix keys. """ with pytest.raises(ValueError): get_model(*t1, dim=2)
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) def test_invalid_dim(get_model): """ Check that an error is raised when the reciprocal lattice vector does not match the dimension. """ model = get_model(0.1, 0.2) model.add_hop(1j, 0, 1, (0, 1, 2)) with pytest.raises(ValueError): model.add_hop(1j, 0, 1, (0, 1))
Fix test broken by previous commit.
Fix test broken by previous commit.
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) @pytest.mark.parametrize('t1', T_VALUES) def test_invalid_dim(t1, get_model): """ Check that an error is raised when the dimension does not match the hopping matrix keys. """ with pytest.raises(ValueError): get_model(*t1, dim=2) Fix test broken by previous commit.
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) def test_invalid_dim(get_model): """ Check that an error is raised when the reciprocal lattice vector does not match the dimension. """ model = get_model(0.1, 0.2) model.add_hop(1j, 0, 1, (0, 1, 2)) with pytest.raises(ValueError): model.add_hop(1j, 0, 1, (0, 1))
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) @pytest.mark.parametrize('t1', T_VALUES) def test_invalid_dim(t1, get_model): """ Check that an error is raised when the dimension does not match the hopping matrix keys. """ with pytest.raises(ValueError): get_model(*t1, dim=2) <commit_msg>Fix test broken by previous commit.<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) def test_invalid_dim(get_model): """ Check that an error is raised when the reciprocal lattice vector does not match the dimension. """ model = get_model(0.1, 0.2) model.add_hop(1j, 0, 1, (0, 1, 2)) with pytest.raises(ValueError): model.add_hop(1j, 0, 1, (0, 1))
#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) @pytest.mark.parametrize('t1', T_VALUES) def test_invalid_dim(t1, get_model): """ Check that an error is raised when the dimension does not match the hopping matrix keys. """ with pytest.raises(ValueError): get_model(*t1, dim=2) Fix test broken by previous commit.#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) def test_invalid_dim(get_model): """ Check that an error is raised when the reciprocal lattice vector does not match the dimension. """ model = get_model(0.1, 0.2) model.add_hop(1j, 0, 1, (0, 1, 2)) with pytest.raises(ValueError): model.add_hop(1j, 0, 1, (0, 1))
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) @pytest.mark.parametrize('t1', T_VALUES) def test_invalid_dim(t1, get_model): """ Check that an error is raised when the dimension does not match the hopping matrix keys. """ with pytest.raises(ValueError): get_model(*t1, dim=2) <commit_msg>Fix test broken by previous commit.<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- # (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik # Author: Dominik Gresch <greschd@gmx.ch> """Tests for creating a simple tight-binding model.""" import pytest from parameters import T_VALUES, KPT @pytest.mark.parametrize('t1', T_VALUES) @pytest.mark.parametrize('k', KPT) def test_simple(t1, get_model, k, compare_data, models_equal, compare_isclose): """Regression test for a simple manually created tight-binding model.""" model = get_model(*t1) compare_isclose(model.hamilton(k), tag='hamilton') compare_isclose(model.eigenval(k), tag='eigenval') compare_data(models_equal, model) def test_invalid_dim(get_model): """ Check that an error is raised when the reciprocal lattice vector does not match the dimension. """ model = get_model(0.1, 0.2) model.add_hop(1j, 0, 1, (0, 1, 2)) with pytest.raises(ValueError): model.add_hop(1j, 0, 1, (0, 1))
941ccc65bd14e65f7e877d107f67ee3bfe8e68a3
thecure/sprites/enemies.py
thecure/sprites/enemies.py
from pygame.locals import * from thecure import get_engine from thecure.sprites.base import WalkingSprite class Enemy(WalkingSprite): DEFAULT_HEALTH = 10 class InfectedHuman(Enemy): MOVE_SPEED = 2 def tick(self): super(InfectedHuman, self).tick() if self.started: # Figure out how close we are to the player. player = get_engine().player if player.rect.x > self.rect.x: x = 1 elif player.rect.x < self.rect.x: x = -1 else: x = 0 if player.rect.y > self.rect.y: y = 1 elif player.rect.y < self.rect.y: y = -1 else: y = 0 self.velocity = (x * self.MOVE_SPEED, y * self.MOVE_SPEED) if self.velocity != (0, 0): self.frame_state = 'walking' self.anim_timer.start() self.recompute_direction() else: self.frame_state = 'default' self.anim_timer.stop()
from pygame.locals import * from thecure import get_engine from thecure.sprites.base import Direction, WalkingSprite class Enemy(WalkingSprite): DEFAULT_HEALTH = 10 class InfectedHuman(Enemy): MOVE_SPEED = 2 APPROACH_DISTANCE = 400 def tick(self): super(InfectedHuman, self).tick() if self.started: # Figure out how close we are to the player. player = get_engine().player distance_x = abs(player.rect.x - self.rect.x) distance_y = abs(player.rect.y - self.rect.y) if (self.frame_state == 'walking' or (distance_x <= self.APPROACH_DISTANCE and distance_y <= self.APPROACH_DISTANCE)): x_dir = None y_dir = None if player.rect.x > self.rect.x: x = 1 x_dir = Direction.RIGHT elif player.rect.x < self.rect.x: x = -1 x_dir = Direction.LEFT else: x = 0 if player.rect.y > self.rect.y: y = 1 y_dir = Direction.DOWN elif player.rect.y < self.rect.y: y = -1 y_dir = Direction.UP else: y = 0 self.velocity = (x * self.MOVE_SPEED, y * self.MOVE_SPEED) if self.velocity != (0, 0): self.frame_state = 'walking' self.anim_timer.start() if distance_x > distance_y: self.set_direction(x_dir) elif distance_y > distance_x: self.set_direction(y_dir) else: self.frame_state = 'default' self.anim_timer.stop()
Improve infected human approach AI.
Improve infected human approach AI. The approach AI now only kicks in when the player is within 400 pixels of the enemy. The direction it chooses to look in is a bit more sane now. It will figure out whether the distance is greater in the X or Y location, and pick a direction based on that. Now they actually appear to walk toward the player correctly.
Python
mit
chipx86/the-cure
from pygame.locals import * from thecure import get_engine from thecure.sprites.base import WalkingSprite class Enemy(WalkingSprite): DEFAULT_HEALTH = 10 class InfectedHuman(Enemy): MOVE_SPEED = 2 def tick(self): super(InfectedHuman, self).tick() if self.started: # Figure out how close we are to the player. player = get_engine().player if player.rect.x > self.rect.x: x = 1 elif player.rect.x < self.rect.x: x = -1 else: x = 0 if player.rect.y > self.rect.y: y = 1 elif player.rect.y < self.rect.y: y = -1 else: y = 0 self.velocity = (x * self.MOVE_SPEED, y * self.MOVE_SPEED) if self.velocity != (0, 0): self.frame_state = 'walking' self.anim_timer.start() self.recompute_direction() else: self.frame_state = 'default' self.anim_timer.stop() Improve infected human approach AI. The approach AI now only kicks in when the player is within 400 pixels of the enemy. The direction it chooses to look in is a bit more sane now. It will figure out whether the distance is greater in the X or Y location, and pick a direction based on that. Now they actually appear to walk toward the player correctly.
from pygame.locals import * from thecure import get_engine from thecure.sprites.base import Direction, WalkingSprite class Enemy(WalkingSprite): DEFAULT_HEALTH = 10 class InfectedHuman(Enemy): MOVE_SPEED = 2 APPROACH_DISTANCE = 400 def tick(self): super(InfectedHuman, self).tick() if self.started: # Figure out how close we are to the player. player = get_engine().player distance_x = abs(player.rect.x - self.rect.x) distance_y = abs(player.rect.y - self.rect.y) if (self.frame_state == 'walking' or (distance_x <= self.APPROACH_DISTANCE and distance_y <= self.APPROACH_DISTANCE)): x_dir = None y_dir = None if player.rect.x > self.rect.x: x = 1 x_dir = Direction.RIGHT elif player.rect.x < self.rect.x: x = -1 x_dir = Direction.LEFT else: x = 0 if player.rect.y > self.rect.y: y = 1 y_dir = Direction.DOWN elif player.rect.y < self.rect.y: y = -1 y_dir = Direction.UP else: y = 0 self.velocity = (x * self.MOVE_SPEED, y * self.MOVE_SPEED) if self.velocity != (0, 0): self.frame_state = 'walking' self.anim_timer.start() if distance_x > distance_y: self.set_direction(x_dir) elif distance_y > distance_x: self.set_direction(y_dir) else: self.frame_state = 'default' self.anim_timer.stop()
<commit_before>from pygame.locals import * from thecure import get_engine from thecure.sprites.base import WalkingSprite class Enemy(WalkingSprite): DEFAULT_HEALTH = 10 class InfectedHuman(Enemy): MOVE_SPEED = 2 def tick(self): super(InfectedHuman, self).tick() if self.started: # Figure out how close we are to the player. player = get_engine().player if player.rect.x > self.rect.x: x = 1 elif player.rect.x < self.rect.x: x = -1 else: x = 0 if player.rect.y > self.rect.y: y = 1 elif player.rect.y < self.rect.y: y = -1 else: y = 0 self.velocity = (x * self.MOVE_SPEED, y * self.MOVE_SPEED) if self.velocity != (0, 0): self.frame_state = 'walking' self.anim_timer.start() self.recompute_direction() else: self.frame_state = 'default' self.anim_timer.stop() <commit_msg>Improve infected human approach AI. The approach AI now only kicks in when the player is within 400 pixels of the enemy. The direction it chooses to look in is a bit more sane now. It will figure out whether the distance is greater in the X or Y location, and pick a direction based on that. Now they actually appear to walk toward the player correctly.<commit_after>
from pygame.locals import * from thecure import get_engine from thecure.sprites.base import Direction, WalkingSprite class Enemy(WalkingSprite): DEFAULT_HEALTH = 10 class InfectedHuman(Enemy): MOVE_SPEED = 2 APPROACH_DISTANCE = 400 def tick(self): super(InfectedHuman, self).tick() if self.started: # Figure out how close we are to the player. player = get_engine().player distance_x = abs(player.rect.x - self.rect.x) distance_y = abs(player.rect.y - self.rect.y) if (self.frame_state == 'walking' or (distance_x <= self.APPROACH_DISTANCE and distance_y <= self.APPROACH_DISTANCE)): x_dir = None y_dir = None if player.rect.x > self.rect.x: x = 1 x_dir = Direction.RIGHT elif player.rect.x < self.rect.x: x = -1 x_dir = Direction.LEFT else: x = 0 if player.rect.y > self.rect.y: y = 1 y_dir = Direction.DOWN elif player.rect.y < self.rect.y: y = -1 y_dir = Direction.UP else: y = 0 self.velocity = (x * self.MOVE_SPEED, y * self.MOVE_SPEED) if self.velocity != (0, 0): self.frame_state = 'walking' self.anim_timer.start() if distance_x > distance_y: self.set_direction(x_dir) elif distance_y > distance_x: self.set_direction(y_dir) else: self.frame_state = 'default' self.anim_timer.stop()
from pygame.locals import * from thecure import get_engine from thecure.sprites.base import WalkingSprite class Enemy(WalkingSprite): DEFAULT_HEALTH = 10 class InfectedHuman(Enemy): MOVE_SPEED = 2 def tick(self): super(InfectedHuman, self).tick() if self.started: # Figure out how close we are to the player. player = get_engine().player if player.rect.x > self.rect.x: x = 1 elif player.rect.x < self.rect.x: x = -1 else: x = 0 if player.rect.y > self.rect.y: y = 1 elif player.rect.y < self.rect.y: y = -1 else: y = 0 self.velocity = (x * self.MOVE_SPEED, y * self.MOVE_SPEED) if self.velocity != (0, 0): self.frame_state = 'walking' self.anim_timer.start() self.recompute_direction() else: self.frame_state = 'default' self.anim_timer.stop() Improve infected human approach AI. The approach AI now only kicks in when the player is within 400 pixels of the enemy. The direction it chooses to look in is a bit more sane now. It will figure out whether the distance is greater in the X or Y location, and pick a direction based on that. Now they actually appear to walk toward the player correctly.from pygame.locals import * from thecure import get_engine from thecure.sprites.base import Direction, WalkingSprite class Enemy(WalkingSprite): DEFAULT_HEALTH = 10 class InfectedHuman(Enemy): MOVE_SPEED = 2 APPROACH_DISTANCE = 400 def tick(self): super(InfectedHuman, self).tick() if self.started: # Figure out how close we are to the player. player = get_engine().player distance_x = abs(player.rect.x - self.rect.x) distance_y = abs(player.rect.y - self.rect.y) if (self.frame_state == 'walking' or (distance_x <= self.APPROACH_DISTANCE and distance_y <= self.APPROACH_DISTANCE)): x_dir = None y_dir = None if player.rect.x > self.rect.x: x = 1 x_dir = Direction.RIGHT elif player.rect.x < self.rect.x: x = -1 x_dir = Direction.LEFT else: x = 0 if player.rect.y > self.rect.y: y = 1 y_dir = Direction.DOWN elif player.rect.y < self.rect.y: y = -1 y_dir = Direction.UP else: y = 0 self.velocity = (x * self.MOVE_SPEED, y * self.MOVE_SPEED) if self.velocity != (0, 0): self.frame_state = 'walking' self.anim_timer.start() if distance_x > distance_y: self.set_direction(x_dir) elif distance_y > distance_x: self.set_direction(y_dir) else: self.frame_state = 'default' self.anim_timer.stop()
<commit_before>from pygame.locals import * from thecure import get_engine from thecure.sprites.base import WalkingSprite class Enemy(WalkingSprite): DEFAULT_HEALTH = 10 class InfectedHuman(Enemy): MOVE_SPEED = 2 def tick(self): super(InfectedHuman, self).tick() if self.started: # Figure out how close we are to the player. player = get_engine().player if player.rect.x > self.rect.x: x = 1 elif player.rect.x < self.rect.x: x = -1 else: x = 0 if player.rect.y > self.rect.y: y = 1 elif player.rect.y < self.rect.y: y = -1 else: y = 0 self.velocity = (x * self.MOVE_SPEED, y * self.MOVE_SPEED) if self.velocity != (0, 0): self.frame_state = 'walking' self.anim_timer.start() self.recompute_direction() else: self.frame_state = 'default' self.anim_timer.stop() <commit_msg>Improve infected human approach AI. The approach AI now only kicks in when the player is within 400 pixels of the enemy. The direction it chooses to look in is a bit more sane now. It will figure out whether the distance is greater in the X or Y location, and pick a direction based on that. Now they actually appear to walk toward the player correctly.<commit_after>from pygame.locals import * from thecure import get_engine from thecure.sprites.base import Direction, WalkingSprite class Enemy(WalkingSprite): DEFAULT_HEALTH = 10 class InfectedHuman(Enemy): MOVE_SPEED = 2 APPROACH_DISTANCE = 400 def tick(self): super(InfectedHuman, self).tick() if self.started: # Figure out how close we are to the player. player = get_engine().player distance_x = abs(player.rect.x - self.rect.x) distance_y = abs(player.rect.y - self.rect.y) if (self.frame_state == 'walking' or (distance_x <= self.APPROACH_DISTANCE and distance_y <= self.APPROACH_DISTANCE)): x_dir = None y_dir = None if player.rect.x > self.rect.x: x = 1 x_dir = Direction.RIGHT elif player.rect.x < self.rect.x: x = -1 x_dir = Direction.LEFT else: x = 0 if player.rect.y > self.rect.y: y = 1 y_dir = Direction.DOWN elif player.rect.y < self.rect.y: y = -1 y_dir = Direction.UP else: y = 0 self.velocity = (x * self.MOVE_SPEED, y * self.MOVE_SPEED) if self.velocity != (0, 0): self.frame_state = 'walking' self.anim_timer.start() if distance_x > distance_y: self.set_direction(x_dir) elif distance_y > distance_x: self.set_direction(y_dir) else: self.frame_state = 'default' self.anim_timer.stop()
6af918668cddf30c12a10fe46bc174e110bf04c3
red_api.py
red_api.py
import os from pymongo import MongoClient MONGO_USER = os.getenv('MONGO_USER') MONGO_PASSWORD = os.getenv('MONGO_PASSWORD') MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD) # Open a connection to Mongo once # mongo_client = MongoClient(MONGO_URI) red_john_tweets = mongo_client.redjohn.tweets suspects = [ 'partridge', 'kirkland', 'bertram', 'stiles', 'haffner', 'mcallister', 'smith' ] def get_suspect_mentions(): suspect_mentions = {} for suspect in suspects: mentions = red_john_tweets.find({ 'suspect': suspect }).count() suspect_mentions[suspect] = mentions return suspect_mentions def get_tweet_count(): return red_john_tweets.count() def get_suspect_tweets(suspect, limit=5): tweets = red_john_tweets.find({ 'suspect': suspect })[:limit] return list(tweets)
import os from pymongo import DESCENDING from pymongo import MongoClient from bson.json_util import dumps MONGO_USER = os.getenv('MONGO_USER') MONGO_PASSWORD = os.getenv('MONGO_PASSWORD') MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD) # Open a connection to Mongo once # mongo_client = MongoClient(MONGO_URI) red_john_tweets = mongo_client.redjohn.tweets suspects = [ 'partridge', 'kirkland', 'bertram', 'stiles', 'haffner', 'mcallister', 'smith' ] def get_suspect_mentions(): suspect_mentions = {} for suspect in suspects: mentions = red_john_tweets.find({ 'suspect': suspect }).count() suspect_mentions[suspect] = mentions return suspect_mentions def get_tweet_count(): return red_john_tweets.count() def get_suspect_tweets(suspect, limit=5): tweets = red_john_tweets.find({ 'suspect': suspect }).sort('entry_time', DESCENDING)[:limit] return dumps(tweets)
Use bson's JSON util to handle ObjectIds in a JSON context
Use bson's JSON util to handle ObjectIds in a JSON context
Python
mit
AnSavvides/redjohn,AnSavvides/redjohn
import os from pymongo import MongoClient MONGO_USER = os.getenv('MONGO_USER') MONGO_PASSWORD = os.getenv('MONGO_PASSWORD') MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD) # Open a connection to Mongo once # mongo_client = MongoClient(MONGO_URI) red_john_tweets = mongo_client.redjohn.tweets suspects = [ 'partridge', 'kirkland', 'bertram', 'stiles', 'haffner', 'mcallister', 'smith' ] def get_suspect_mentions(): suspect_mentions = {} for suspect in suspects: mentions = red_john_tweets.find({ 'suspect': suspect }).count() suspect_mentions[suspect] = mentions return suspect_mentions def get_tweet_count(): return red_john_tweets.count() def get_suspect_tweets(suspect, limit=5): tweets = red_john_tweets.find({ 'suspect': suspect })[:limit] return list(tweets)Use bson's JSON util to handle ObjectIds in a JSON context
import os from pymongo import DESCENDING from pymongo import MongoClient from bson.json_util import dumps MONGO_USER = os.getenv('MONGO_USER') MONGO_PASSWORD = os.getenv('MONGO_PASSWORD') MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD) # Open a connection to Mongo once # mongo_client = MongoClient(MONGO_URI) red_john_tweets = mongo_client.redjohn.tweets suspects = [ 'partridge', 'kirkland', 'bertram', 'stiles', 'haffner', 'mcallister', 'smith' ] def get_suspect_mentions(): suspect_mentions = {} for suspect in suspects: mentions = red_john_tweets.find({ 'suspect': suspect }).count() suspect_mentions[suspect] = mentions return suspect_mentions def get_tweet_count(): return red_john_tweets.count() def get_suspect_tweets(suspect, limit=5): tweets = red_john_tweets.find({ 'suspect': suspect }).sort('entry_time', DESCENDING)[:limit] return dumps(tweets)
<commit_before>import os from pymongo import MongoClient MONGO_USER = os.getenv('MONGO_USER') MONGO_PASSWORD = os.getenv('MONGO_PASSWORD') MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD) # Open a connection to Mongo once # mongo_client = MongoClient(MONGO_URI) red_john_tweets = mongo_client.redjohn.tweets suspects = [ 'partridge', 'kirkland', 'bertram', 'stiles', 'haffner', 'mcallister', 'smith' ] def get_suspect_mentions(): suspect_mentions = {} for suspect in suspects: mentions = red_john_tweets.find({ 'suspect': suspect }).count() suspect_mentions[suspect] = mentions return suspect_mentions def get_tweet_count(): return red_john_tweets.count() def get_suspect_tweets(suspect, limit=5): tweets = red_john_tweets.find({ 'suspect': suspect })[:limit] return list(tweets)<commit_msg>Use bson's JSON util to handle ObjectIds in a JSON context<commit_after>
import os from pymongo import DESCENDING from pymongo import MongoClient from bson.json_util import dumps MONGO_USER = os.getenv('MONGO_USER') MONGO_PASSWORD = os.getenv('MONGO_PASSWORD') MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD) # Open a connection to Mongo once # mongo_client = MongoClient(MONGO_URI) red_john_tweets = mongo_client.redjohn.tweets suspects = [ 'partridge', 'kirkland', 'bertram', 'stiles', 'haffner', 'mcallister', 'smith' ] def get_suspect_mentions(): suspect_mentions = {} for suspect in suspects: mentions = red_john_tweets.find({ 'suspect': suspect }).count() suspect_mentions[suspect] = mentions return suspect_mentions def get_tweet_count(): return red_john_tweets.count() def get_suspect_tweets(suspect, limit=5): tweets = red_john_tweets.find({ 'suspect': suspect }).sort('entry_time', DESCENDING)[:limit] return dumps(tweets)
import os from pymongo import MongoClient MONGO_USER = os.getenv('MONGO_USER') MONGO_PASSWORD = os.getenv('MONGO_PASSWORD') MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD) # Open a connection to Mongo once # mongo_client = MongoClient(MONGO_URI) red_john_tweets = mongo_client.redjohn.tweets suspects = [ 'partridge', 'kirkland', 'bertram', 'stiles', 'haffner', 'mcallister', 'smith' ] def get_suspect_mentions(): suspect_mentions = {} for suspect in suspects: mentions = red_john_tweets.find({ 'suspect': suspect }).count() suspect_mentions[suspect] = mentions return suspect_mentions def get_tweet_count(): return red_john_tweets.count() def get_suspect_tweets(suspect, limit=5): tweets = red_john_tweets.find({ 'suspect': suspect })[:limit] return list(tweets)Use bson's JSON util to handle ObjectIds in a JSON contextimport os from pymongo import DESCENDING from pymongo import MongoClient from bson.json_util import dumps MONGO_USER = os.getenv('MONGO_USER') MONGO_PASSWORD = os.getenv('MONGO_PASSWORD') MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD) # Open a connection to Mongo once # mongo_client = MongoClient(MONGO_URI) red_john_tweets = mongo_client.redjohn.tweets suspects = [ 'partridge', 'kirkland', 'bertram', 'stiles', 'haffner', 'mcallister', 'smith' ] def get_suspect_mentions(): suspect_mentions = {} for suspect in suspects: mentions = red_john_tweets.find({ 'suspect': suspect }).count() suspect_mentions[suspect] = mentions return suspect_mentions def get_tweet_count(): return red_john_tweets.count() def get_suspect_tweets(suspect, limit=5): tweets = red_john_tweets.find({ 'suspect': suspect }).sort('entry_time', DESCENDING)[:limit] return dumps(tweets)
<commit_before>import os from pymongo import MongoClient MONGO_USER = os.getenv('MONGO_USER') MONGO_PASSWORD = os.getenv('MONGO_PASSWORD') MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD) # Open a connection to Mongo once # mongo_client = MongoClient(MONGO_URI) red_john_tweets = mongo_client.redjohn.tweets suspects = [ 'partridge', 'kirkland', 'bertram', 'stiles', 'haffner', 'mcallister', 'smith' ] def get_suspect_mentions(): suspect_mentions = {} for suspect in suspects: mentions = red_john_tweets.find({ 'suspect': suspect }).count() suspect_mentions[suspect] = mentions return suspect_mentions def get_tweet_count(): return red_john_tweets.count() def get_suspect_tweets(suspect, limit=5): tweets = red_john_tweets.find({ 'suspect': suspect })[:limit] return list(tweets)<commit_msg>Use bson's JSON util to handle ObjectIds in a JSON context<commit_after>import os from pymongo import DESCENDING from pymongo import MongoClient from bson.json_util import dumps MONGO_USER = os.getenv('MONGO_USER') MONGO_PASSWORD = os.getenv('MONGO_PASSWORD') MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD) # Open a connection to Mongo once # mongo_client = MongoClient(MONGO_URI) red_john_tweets = mongo_client.redjohn.tweets suspects = [ 'partridge', 'kirkland', 'bertram', 'stiles', 'haffner', 'mcallister', 'smith' ] def get_suspect_mentions(): suspect_mentions = {} for suspect in suspects: mentions = red_john_tweets.find({ 'suspect': suspect }).count() suspect_mentions[suspect] = mentions return suspect_mentions def get_tweet_count(): return red_john_tweets.count() def get_suspect_tweets(suspect, limit=5): tweets = red_john_tweets.find({ 'suspect': suspect }).sort('entry_time', DESCENDING)[:limit] return dumps(tweets)
48c63eb527b92d22fcdc3eba6e9b52bd2ee54f8e
Build/POSIXEnvironment.py
Build/POSIXEnvironment.py
import BaseEnvironment import os class Environment(BaseEnvironment.Environment): def __init__(self, **kw): apply(BaseEnvironment.Environment.__init__, (self,), kw) self.ConfigureCompiler() def ConfigureCompiler(self): cxx = os.path.basename(self['CXX']) if cxx.startswith("clang") or cxx.startswith("g++"): self.AppendUnique(CXXFLAGS=['-Wall', '-Wpedantic', '-g'])
import BaseEnvironment import os class Environment(BaseEnvironment.Environment): def __init__(self, **kw): apply(BaseEnvironment.Environment.__init__, (self,), kw) self.ConfigureCompiler() def ConfigureCompiler(self): cxx = os.path.basename(self['CXX']) if cxx.startswith("clang") or cxx.startswith("g++"): self.AppendUnique(CXXFLAGS=['-Wall', '-pedantic', '-g'])
Use '-pedantic' to fix build with old GCC versions.
Use '-pedantic' to fix build with old GCC versions.
Python
mit
matthargett/mockitopp,matthargett/mockitopp,tpounds/mockitopp,tpounds/mockitopp
import BaseEnvironment import os class Environment(BaseEnvironment.Environment): def __init__(self, **kw): apply(BaseEnvironment.Environment.__init__, (self,), kw) self.ConfigureCompiler() def ConfigureCompiler(self): cxx = os.path.basename(self['CXX']) if cxx.startswith("clang") or cxx.startswith("g++"): self.AppendUnique(CXXFLAGS=['-Wall', '-Wpedantic', '-g']) Use '-pedantic' to fix build with old GCC versions.
import BaseEnvironment import os class Environment(BaseEnvironment.Environment): def __init__(self, **kw): apply(BaseEnvironment.Environment.__init__, (self,), kw) self.ConfigureCompiler() def ConfigureCompiler(self): cxx = os.path.basename(self['CXX']) if cxx.startswith("clang") or cxx.startswith("g++"): self.AppendUnique(CXXFLAGS=['-Wall', '-pedantic', '-g'])
<commit_before>import BaseEnvironment import os class Environment(BaseEnvironment.Environment): def __init__(self, **kw): apply(BaseEnvironment.Environment.__init__, (self,), kw) self.ConfigureCompiler() def ConfigureCompiler(self): cxx = os.path.basename(self['CXX']) if cxx.startswith("clang") or cxx.startswith("g++"): self.AppendUnique(CXXFLAGS=['-Wall', '-Wpedantic', '-g']) <commit_msg>Use '-pedantic' to fix build with old GCC versions.<commit_after>
import BaseEnvironment import os class Environment(BaseEnvironment.Environment): def __init__(self, **kw): apply(BaseEnvironment.Environment.__init__, (self,), kw) self.ConfigureCompiler() def ConfigureCompiler(self): cxx = os.path.basename(self['CXX']) if cxx.startswith("clang") or cxx.startswith("g++"): self.AppendUnique(CXXFLAGS=['-Wall', '-pedantic', '-g'])
import BaseEnvironment import os class Environment(BaseEnvironment.Environment): def __init__(self, **kw): apply(BaseEnvironment.Environment.__init__, (self,), kw) self.ConfigureCompiler() def ConfigureCompiler(self): cxx = os.path.basename(self['CXX']) if cxx.startswith("clang") or cxx.startswith("g++"): self.AppendUnique(CXXFLAGS=['-Wall', '-Wpedantic', '-g']) Use '-pedantic' to fix build with old GCC versions.import BaseEnvironment import os class Environment(BaseEnvironment.Environment): def __init__(self, **kw): apply(BaseEnvironment.Environment.__init__, (self,), kw) self.ConfigureCompiler() def ConfigureCompiler(self): cxx = os.path.basename(self['CXX']) if cxx.startswith("clang") or cxx.startswith("g++"): self.AppendUnique(CXXFLAGS=['-Wall', '-pedantic', '-g'])
<commit_before>import BaseEnvironment import os class Environment(BaseEnvironment.Environment): def __init__(self, **kw): apply(BaseEnvironment.Environment.__init__, (self,), kw) self.ConfigureCompiler() def ConfigureCompiler(self): cxx = os.path.basename(self['CXX']) if cxx.startswith("clang") or cxx.startswith("g++"): self.AppendUnique(CXXFLAGS=['-Wall', '-Wpedantic', '-g']) <commit_msg>Use '-pedantic' to fix build with old GCC versions.<commit_after>import BaseEnvironment import os class Environment(BaseEnvironment.Environment): def __init__(self, **kw): apply(BaseEnvironment.Environment.__init__, (self,), kw) self.ConfigureCompiler() def ConfigureCompiler(self): cxx = os.path.basename(self['CXX']) if cxx.startswith("clang") or cxx.startswith("g++"): self.AppendUnique(CXXFLAGS=['-Wall', '-pedantic', '-g'])
8f70981f93da9648a618fb529629e5bdd88a1f7d
tests/test_command_line_tool.py
tests/test_command_line_tool.py
import unittest import os from performance_testing.command_line import Tool from performance_testing.result import Result from performance_testing.config import Config class CommandLineToolTest(unittest.TestCase): def setUp(self): self.current_directory = os.path.dirname(os.path.abspath(__file__)) self.config = os.path.join(self.current_directory, 'assets/test_config.yml') self.result_directory = os.path.join(self.current_directory, 'assets/test_result') def test_init(self): tool = Tool(config=self.config, result_directory=self.result_directory) self.assertIsInstance(tool.config, Config) self.assertIsInstance(tool.result, Result)
import unittest import os from performance_testing.command_line import Tool from performance_testing.result import Result from performance_testing.config import Config import config class CommandLineToolTest(unittest.TestCase): def setUp(self): self.current_directory = os.path.dirname(os.path.abspath(__file__)) self.result_directory = os.path.join(self.current_directory, 'assets/test_result') def test_init(self): tool = Tool(config=config.CONFIG, result_directory=self.result_directory) self.assertIsInstance(tool.config, Config) self.assertIsInstance(tool.result, Result)
Remove yaml config and use config object
Remove yaml config and use config object
Python
mit
BakeCode/performance-testing,BakeCode/performance-testing
import unittest import os from performance_testing.command_line import Tool from performance_testing.result import Result from performance_testing.config import Config class CommandLineToolTest(unittest.TestCase): def setUp(self): self.current_directory = os.path.dirname(os.path.abspath(__file__)) self.config = os.path.join(self.current_directory, 'assets/test_config.yml') self.result_directory = os.path.join(self.current_directory, 'assets/test_result') def test_init(self): tool = Tool(config=self.config, result_directory=self.result_directory) self.assertIsInstance(tool.config, Config) self.assertIsInstance(tool.result, Result) Remove yaml config and use config object
import unittest import os from performance_testing.command_line import Tool from performance_testing.result import Result from performance_testing.config import Config import config class CommandLineToolTest(unittest.TestCase): def setUp(self): self.current_directory = os.path.dirname(os.path.abspath(__file__)) self.result_directory = os.path.join(self.current_directory, 'assets/test_result') def test_init(self): tool = Tool(config=config.CONFIG, result_directory=self.result_directory) self.assertIsInstance(tool.config, Config) self.assertIsInstance(tool.result, Result)
<commit_before>import unittest import os from performance_testing.command_line import Tool from performance_testing.result import Result from performance_testing.config import Config class CommandLineToolTest(unittest.TestCase): def setUp(self): self.current_directory = os.path.dirname(os.path.abspath(__file__)) self.config = os.path.join(self.current_directory, 'assets/test_config.yml') self.result_directory = os.path.join(self.current_directory, 'assets/test_result') def test_init(self): tool = Tool(config=self.config, result_directory=self.result_directory) self.assertIsInstance(tool.config, Config) self.assertIsInstance(tool.result, Result) <commit_msg>Remove yaml config and use config object<commit_after>
import unittest import os from performance_testing.command_line import Tool from performance_testing.result import Result from performance_testing.config import Config import config class CommandLineToolTest(unittest.TestCase): def setUp(self): self.current_directory = os.path.dirname(os.path.abspath(__file__)) self.result_directory = os.path.join(self.current_directory, 'assets/test_result') def test_init(self): tool = Tool(config=config.CONFIG, result_directory=self.result_directory) self.assertIsInstance(tool.config, Config) self.assertIsInstance(tool.result, Result)
import unittest import os from performance_testing.command_line import Tool from performance_testing.result import Result from performance_testing.config import Config class CommandLineToolTest(unittest.TestCase): def setUp(self): self.current_directory = os.path.dirname(os.path.abspath(__file__)) self.config = os.path.join(self.current_directory, 'assets/test_config.yml') self.result_directory = os.path.join(self.current_directory, 'assets/test_result') def test_init(self): tool = Tool(config=self.config, result_directory=self.result_directory) self.assertIsInstance(tool.config, Config) self.assertIsInstance(tool.result, Result) Remove yaml config and use config objectimport unittest import os from performance_testing.command_line import Tool from performance_testing.result import Result from performance_testing.config import Config import config class CommandLineToolTest(unittest.TestCase): def setUp(self): self.current_directory = os.path.dirname(os.path.abspath(__file__)) self.result_directory = os.path.join(self.current_directory, 'assets/test_result') def test_init(self): tool = Tool(config=config.CONFIG, result_directory=self.result_directory) self.assertIsInstance(tool.config, Config) self.assertIsInstance(tool.result, Result)
<commit_before>import unittest import os from performance_testing.command_line import Tool from performance_testing.result import Result from performance_testing.config import Config class CommandLineToolTest(unittest.TestCase): def setUp(self): self.current_directory = os.path.dirname(os.path.abspath(__file__)) self.config = os.path.join(self.current_directory, 'assets/test_config.yml') self.result_directory = os.path.join(self.current_directory, 'assets/test_result') def test_init(self): tool = Tool(config=self.config, result_directory=self.result_directory) self.assertIsInstance(tool.config, Config) self.assertIsInstance(tool.result, Result) <commit_msg>Remove yaml config and use config object<commit_after>import unittest import os from performance_testing.command_line import Tool from performance_testing.result import Result from performance_testing.config import Config import config class CommandLineToolTest(unittest.TestCase): def setUp(self): self.current_directory = os.path.dirname(os.path.abspath(__file__)) self.result_directory = os.path.join(self.current_directory, 'assets/test_result') def test_init(self): tool = Tool(config=config.CONFIG, result_directory=self.result_directory) self.assertIsInstance(tool.config, Config) self.assertIsInstance(tool.result, Result)
25f69d929af9ef600f067343524272bcaef54a6b
KerbalStuff/celery.py
KerbalStuff/celery.py
import smtplib from celery import Celery from email.mime.text import MIMEText from KerbalStuff.config import _cfg, _cfgi, _cfgb app = Celery("tasks", broker="redis://localhost:6379/0") def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in range(0, len(l), n): yield l[i:i+n] @app.task def send_mail(sender, recipients, subject, message, important=False): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(host=_cfg("smtp-host"), port=_cfgi("smtp-port")) message = MIMEText(message) if important: message['X-MC-Important'] = "true" message['X-MC-PreserveRecipients'] = "false" message['Subject'] = subject message['From'] = sender for group in chunks(recipients, 100): message['To'] = ";".join(group) print("Sending email from {} to {} recipients".format(sender, len(group))) smtp.sendmail(sender, group, message.as_string()) smtp.quit()
import smtplib from celery import Celery from email.mime.text import MIMEText from KerbalStuff.config import _cfg, _cfgi, _cfgb app = Celery("tasks", broker="redis://localhost:6379/0") def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in range(0, len(l), n): yield l[i:i+n] @app.task def send_mail(sender, recipients, subject, message, important=False): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(host=_cfg("smtp-host"), port=_cfgi("smtp-port")) message = MIMEText(message) if important: message['X-MC-Important'] = "true" message['X-MC-PreserveRecipients'] = "false" message['Subject'] = subject message['From'] = sender for group in chunks(recipients, 100): message['To'] = "undisclosed-recipients:;" print("Sending email from {} to {} recipients".format(sender, len(group))) smtp.sendmail(sender, group, message.as_string()) smtp.quit()
Remove addresses from "To" field, BCC instead.
[proposal] Remove addresses from "To" field, BCC instead. Closing privacy issue by hiding the "To" field altogether. Just commented out the "To" line. For issue #68
Python
mit
EIREXE/SpaceDock,EIREXE/SpaceDock,EIREXE/SpaceDock,EIREXE/SpaceDock
import smtplib from celery import Celery from email.mime.text import MIMEText from KerbalStuff.config import _cfg, _cfgi, _cfgb app = Celery("tasks", broker="redis://localhost:6379/0") def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in range(0, len(l), n): yield l[i:i+n] @app.task def send_mail(sender, recipients, subject, message, important=False): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(host=_cfg("smtp-host"), port=_cfgi("smtp-port")) message = MIMEText(message) if important: message['X-MC-Important'] = "true" message['X-MC-PreserveRecipients'] = "false" message['Subject'] = subject message['From'] = sender for group in chunks(recipients, 100): message['To'] = ";".join(group) print("Sending email from {} to {} recipients".format(sender, len(group))) smtp.sendmail(sender, group, message.as_string()) smtp.quit() [proposal] Remove addresses from "To" field, BCC instead. Closing privacy issue by hiding the "To" field altogether. Just commented out the "To" line. For issue #68
import smtplib from celery import Celery from email.mime.text import MIMEText from KerbalStuff.config import _cfg, _cfgi, _cfgb app = Celery("tasks", broker="redis://localhost:6379/0") def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in range(0, len(l), n): yield l[i:i+n] @app.task def send_mail(sender, recipients, subject, message, important=False): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(host=_cfg("smtp-host"), port=_cfgi("smtp-port")) message = MIMEText(message) if important: message['X-MC-Important'] = "true" message['X-MC-PreserveRecipients'] = "false" message['Subject'] = subject message['From'] = sender for group in chunks(recipients, 100): message['To'] = "undisclosed-recipients:;" print("Sending email from {} to {} recipients".format(sender, len(group))) smtp.sendmail(sender, group, message.as_string()) smtp.quit()
<commit_before>import smtplib from celery import Celery from email.mime.text import MIMEText from KerbalStuff.config import _cfg, _cfgi, _cfgb app = Celery("tasks", broker="redis://localhost:6379/0") def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in range(0, len(l), n): yield l[i:i+n] @app.task def send_mail(sender, recipients, subject, message, important=False): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(host=_cfg("smtp-host"), port=_cfgi("smtp-port")) message = MIMEText(message) if important: message['X-MC-Important'] = "true" message['X-MC-PreserveRecipients'] = "false" message['Subject'] = subject message['From'] = sender for group in chunks(recipients, 100): message['To'] = ";".join(group) print("Sending email from {} to {} recipients".format(sender, len(group))) smtp.sendmail(sender, group, message.as_string()) smtp.quit() <commit_msg>[proposal] Remove addresses from "To" field, BCC instead. Closing privacy issue by hiding the "To" field altogether. Just commented out the "To" line. For issue #68<commit_after>
import smtplib from celery import Celery from email.mime.text import MIMEText from KerbalStuff.config import _cfg, _cfgi, _cfgb app = Celery("tasks", broker="redis://localhost:6379/0") def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in range(0, len(l), n): yield l[i:i+n] @app.task def send_mail(sender, recipients, subject, message, important=False): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(host=_cfg("smtp-host"), port=_cfgi("smtp-port")) message = MIMEText(message) if important: message['X-MC-Important'] = "true" message['X-MC-PreserveRecipients'] = "false" message['Subject'] = subject message['From'] = sender for group in chunks(recipients, 100): message['To'] = "undisclosed-recipients:;" print("Sending email from {} to {} recipients".format(sender, len(group))) smtp.sendmail(sender, group, message.as_string()) smtp.quit()
import smtplib from celery import Celery from email.mime.text import MIMEText from KerbalStuff.config import _cfg, _cfgi, _cfgb app = Celery("tasks", broker="redis://localhost:6379/0") def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in range(0, len(l), n): yield l[i:i+n] @app.task def send_mail(sender, recipients, subject, message, important=False): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(host=_cfg("smtp-host"), port=_cfgi("smtp-port")) message = MIMEText(message) if important: message['X-MC-Important'] = "true" message['X-MC-PreserveRecipients'] = "false" message['Subject'] = subject message['From'] = sender for group in chunks(recipients, 100): message['To'] = ";".join(group) print("Sending email from {} to {} recipients".format(sender, len(group))) smtp.sendmail(sender, group, message.as_string()) smtp.quit() [proposal] Remove addresses from "To" field, BCC instead. Closing privacy issue by hiding the "To" field altogether. Just commented out the "To" line. For issue #68import smtplib from celery import Celery from email.mime.text import MIMEText from KerbalStuff.config import _cfg, _cfgi, _cfgb app = Celery("tasks", broker="redis://localhost:6379/0") def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in range(0, len(l), n): yield l[i:i+n] @app.task def send_mail(sender, recipients, subject, message, important=False): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(host=_cfg("smtp-host"), port=_cfgi("smtp-port")) message = MIMEText(message) if important: message['X-MC-Important'] = "true" message['X-MC-PreserveRecipients'] = "false" message['Subject'] = subject message['From'] = sender for group in chunks(recipients, 100): message['To'] = "undisclosed-recipients:;" print("Sending email from {} to {} recipients".format(sender, len(group))) smtp.sendmail(sender, group, message.as_string()) smtp.quit()
<commit_before>import smtplib from celery import Celery from email.mime.text import MIMEText from KerbalStuff.config import _cfg, _cfgi, _cfgb app = Celery("tasks", broker="redis://localhost:6379/0") def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in range(0, len(l), n): yield l[i:i+n] @app.task def send_mail(sender, recipients, subject, message, important=False): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(host=_cfg("smtp-host"), port=_cfgi("smtp-port")) message = MIMEText(message) if important: message['X-MC-Important'] = "true" message['X-MC-PreserveRecipients'] = "false" message['Subject'] = subject message['From'] = sender for group in chunks(recipients, 100): message['To'] = ";".join(group) print("Sending email from {} to {} recipients".format(sender, len(group))) smtp.sendmail(sender, group, message.as_string()) smtp.quit() <commit_msg>[proposal] Remove addresses from "To" field, BCC instead. Closing privacy issue by hiding the "To" field altogether. Just commented out the "To" line. For issue #68<commit_after>import smtplib from celery import Celery from email.mime.text import MIMEText from KerbalStuff.config import _cfg, _cfgi, _cfgb app = Celery("tasks", broker="redis://localhost:6379/0") def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in range(0, len(l), n): yield l[i:i+n] @app.task def send_mail(sender, recipients, subject, message, important=False): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(host=_cfg("smtp-host"), port=_cfgi("smtp-port")) message = MIMEText(message) if important: message['X-MC-Important'] = "true" message['X-MC-PreserveRecipients'] = "false" message['Subject'] = subject message['From'] = sender for group in chunks(recipients, 100): message['To'] = "undisclosed-recipients:;" print("Sending email from {} to {} recipients".format(sender, len(group))) smtp.sendmail(sender, group, message.as_string()) smtp.quit()
2d8a3b8c9ca6196317758e58cefc76163b88607f
falcom/table.py
falcom/table.py
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class Table: class InputStrContainsCarriageReturn (RuntimeError): pass def __init__ (self, tab_separated_text = None): if tab_separated_text and "\r" in tab_separated_text: raise self.InputStrContainsCarriageReturn self.text = tab_separated_text if self.text: self.text = self.text.rstrip("\n") @property def rows (self): return len(self) @property def cols (self): return len(self.text.split("\n")[0].split("\t")) if self.text else 0 def __len__ (self): return len(self.text.split("\n")) if self.text else 0 def __iter__ (self): if self.text: for row in self.text.split("\n"): yield(tuple(row.split("\t"))) else: return iter(()) def __getitem__ (self, key): if self.text: return tuple(self.text.split("\n")[key].split("\t")) else: raise IndexError def __repr__ (self): return "<{} {}>".format(self.__class__.__name__, repr(self.text))
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class Table: class InputStrContainsCarriageReturn (RuntimeError): pass def __init__ (self, tab_separated_text = None): if tab_separated_text: if "\r" in tab_separated_text: raise self.InputStrContainsCarriageReturn self.text = tab_separated_text.rstrip("\n") else: self.text = tab_separated_text @property def rows (self): return len(self) @property def cols (self): return len(self.text.split("\n")[0].split("\t")) if self.text else 0 def __len__ (self): return len(self.text.split("\n")) if self.text else 0 def __iter__ (self): if self.text: for row in self.text.split("\n"): yield(tuple(row.split("\t"))) else: return iter(()) def __getitem__ (self, key): if self.text: return tuple(self.text.split("\n")[key].split("\t")) else: raise IndexError def __repr__ (self): return "<{} {}>".format(self.__class__.__name__, repr(self.text))
Move assignments in Table.__init__ around
Move assignments in Table.__init__ around
Python
bsd-3-clause
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class Table: class InputStrContainsCarriageReturn (RuntimeError): pass def __init__ (self, tab_separated_text = None): if tab_separated_text and "\r" in tab_separated_text: raise self.InputStrContainsCarriageReturn self.text = tab_separated_text if self.text: self.text = self.text.rstrip("\n") @property def rows (self): return len(self) @property def cols (self): return len(self.text.split("\n")[0].split("\t")) if self.text else 0 def __len__ (self): return len(self.text.split("\n")) if self.text else 0 def __iter__ (self): if self.text: for row in self.text.split("\n"): yield(tuple(row.split("\t"))) else: return iter(()) def __getitem__ (self, key): if self.text: return tuple(self.text.split("\n")[key].split("\t")) else: raise IndexError def __repr__ (self): return "<{} {}>".format(self.__class__.__name__, repr(self.text)) Move assignments in Table.__init__ around
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class Table: class InputStrContainsCarriageReturn (RuntimeError): pass def __init__ (self, tab_separated_text = None): if tab_separated_text: if "\r" in tab_separated_text: raise self.InputStrContainsCarriageReturn self.text = tab_separated_text.rstrip("\n") else: self.text = tab_separated_text @property def rows (self): return len(self) @property def cols (self): return len(self.text.split("\n")[0].split("\t")) if self.text else 0 def __len__ (self): return len(self.text.split("\n")) if self.text else 0 def __iter__ (self): if self.text: for row in self.text.split("\n"): yield(tuple(row.split("\t"))) else: return iter(()) def __getitem__ (self, key): if self.text: return tuple(self.text.split("\n")[key].split("\t")) else: raise IndexError def __repr__ (self): return "<{} {}>".format(self.__class__.__name__, repr(self.text))
<commit_before># Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class Table: class InputStrContainsCarriageReturn (RuntimeError): pass def __init__ (self, tab_separated_text = None): if tab_separated_text and "\r" in tab_separated_text: raise self.InputStrContainsCarriageReturn self.text = tab_separated_text if self.text: self.text = self.text.rstrip("\n") @property def rows (self): return len(self) @property def cols (self): return len(self.text.split("\n")[0].split("\t")) if self.text else 0 def __len__ (self): return len(self.text.split("\n")) if self.text else 0 def __iter__ (self): if self.text: for row in self.text.split("\n"): yield(tuple(row.split("\t"))) else: return iter(()) def __getitem__ (self, key): if self.text: return tuple(self.text.split("\n")[key].split("\t")) else: raise IndexError def __repr__ (self): return "<{} {}>".format(self.__class__.__name__, repr(self.text)) <commit_msg>Move assignments in Table.__init__ around<commit_after>
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class Table: class InputStrContainsCarriageReturn (RuntimeError): pass def __init__ (self, tab_separated_text = None): if tab_separated_text: if "\r" in tab_separated_text: raise self.InputStrContainsCarriageReturn self.text = tab_separated_text.rstrip("\n") else: self.text = tab_separated_text @property def rows (self): return len(self) @property def cols (self): return len(self.text.split("\n")[0].split("\t")) if self.text else 0 def __len__ (self): return len(self.text.split("\n")) if self.text else 0 def __iter__ (self): if self.text: for row in self.text.split("\n"): yield(tuple(row.split("\t"))) else: return iter(()) def __getitem__ (self, key): if self.text: return tuple(self.text.split("\n")[key].split("\t")) else: raise IndexError def __repr__ (self): return "<{} {}>".format(self.__class__.__name__, repr(self.text))
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class Table: class InputStrContainsCarriageReturn (RuntimeError): pass def __init__ (self, tab_separated_text = None): if tab_separated_text and "\r" in tab_separated_text: raise self.InputStrContainsCarriageReturn self.text = tab_separated_text if self.text: self.text = self.text.rstrip("\n") @property def rows (self): return len(self) @property def cols (self): return len(self.text.split("\n")[0].split("\t")) if self.text else 0 def __len__ (self): return len(self.text.split("\n")) if self.text else 0 def __iter__ (self): if self.text: for row in self.text.split("\n"): yield(tuple(row.split("\t"))) else: return iter(()) def __getitem__ (self, key): if self.text: return tuple(self.text.split("\n")[key].split("\t")) else: raise IndexError def __repr__ (self): return "<{} {}>".format(self.__class__.__name__, repr(self.text)) Move assignments in Table.__init__ around# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class Table: class InputStrContainsCarriageReturn (RuntimeError): pass def __init__ (self, tab_separated_text = None): if tab_separated_text: if "\r" in tab_separated_text: raise self.InputStrContainsCarriageReturn self.text = tab_separated_text.rstrip("\n") else: self.text = tab_separated_text @property def rows (self): return len(self) @property def cols (self): return len(self.text.split("\n")[0].split("\t")) if self.text else 0 def __len__ (self): return len(self.text.split("\n")) if self.text else 0 def __iter__ (self): if self.text: for row in self.text.split("\n"): yield(tuple(row.split("\t"))) else: return iter(()) def __getitem__ (self, key): if self.text: return tuple(self.text.split("\n")[key].split("\t")) else: raise IndexError def __repr__ (self): return "<{} {}>".format(self.__class__.__name__, repr(self.text))
<commit_before># Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class Table: class InputStrContainsCarriageReturn (RuntimeError): pass def __init__ (self, tab_separated_text = None): if tab_separated_text and "\r" in tab_separated_text: raise self.InputStrContainsCarriageReturn self.text = tab_separated_text if self.text: self.text = self.text.rstrip("\n") @property def rows (self): return len(self) @property def cols (self): return len(self.text.split("\n")[0].split("\t")) if self.text else 0 def __len__ (self): return len(self.text.split("\n")) if self.text else 0 def __iter__ (self): if self.text: for row in self.text.split("\n"): yield(tuple(row.split("\t"))) else: return iter(()) def __getitem__ (self, key): if self.text: return tuple(self.text.split("\n")[key].split("\t")) else: raise IndexError def __repr__ (self): return "<{} {}>".format(self.__class__.__name__, repr(self.text)) <commit_msg>Move assignments in Table.__init__ around<commit_after># Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class Table: class InputStrContainsCarriageReturn (RuntimeError): pass def __init__ (self, tab_separated_text = None): if tab_separated_text: if "\r" in tab_separated_text: raise self.InputStrContainsCarriageReturn self.text = tab_separated_text.rstrip("\n") else: self.text = tab_separated_text @property def rows (self): return len(self) @property def cols (self): return len(self.text.split("\n")[0].split("\t")) if self.text else 0 def __len__ (self): return len(self.text.split("\n")) if self.text else 0 def __iter__ (self): if self.text: for row in self.text.split("\n"): yield(tuple(row.split("\t"))) else: return iter(()) def __getitem__ (self, key): if self.text: return tuple(self.text.split("\n")[key].split("\t")) else: raise IndexError def __repr__ (self): return "<{} {}>".format(self.__class__.__name__, repr(self.text))
6b36fcd7bdc64c914a800a4c4d8381e59adff6f7
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup from distutils.core import Command from sys import stdout, version_info import logging VERSION = '0.9' DESCRIPTION = "A wrapper for comicvine.com" with open('README.md', 'r') as f: LONG_DESCRIPTION = f.read() extra = {} if version_info >= (3,): extra['use_2to3'] = True extra['convert_2to3_doctests'] = ['README.md'] logging.basicConfig(stream=stdout) logging.getLogger("tests").setLevel(logging.DEBUG) setup( name='PyComicVine', version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author='Martin Lenders', author_email='authmillenon@gmail.com', url='http://www.github.com/authmillenon/pycomicvine/', packages=['pycomicvine', 'pycomicvine.tests'], install_requires=['simplejson','python-dateutil >= 2.0'], license="MIT License", test_suite='pycomicvine.tests', **extra )
#!/usr/bin/env python from setuptools import setup from distutils.core import Command from sys import stdout, version_info import logging VERSION = '0.9' DESCRIPTION = "A wrapper for comicvine.com" with open('README.md', 'r') as f: LONG_DESCRIPTION = f.read() extra = {} if version_info >= (3,): extra['use_2to3'] = True extra['convert_2to3_doctests'] = ['README.md'] if version_info >= (3,2,) and version_info < (3,3,): extra['install_requires'] = ['python-dateutil >= 2.0'] else: extra['install_requires'] = ['simplejson', 'python-dateutil >= 2.0'] logging.basicConfig(stream=stdout) logging.getLogger("tests").setLevel(logging.DEBUG) setup( name='PyComicVine', version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author='Martin Lenders', author_email='authmillenon@gmail.com', url='http://www.github.com/authmillenon/pycomicvine/', packages=['pycomicvine', 'pycomicvine.tests'], license="MIT License", test_suite='pycomicvine.tests', **extra )
Remove simplejson for Python 3.2.x since there is no support
Remove simplejson for Python 3.2.x since there is no support
Python
mit
authmillenon/pycomicvine
#!/usr/bin/env python from setuptools import setup from distutils.core import Command from sys import stdout, version_info import logging VERSION = '0.9' DESCRIPTION = "A wrapper for comicvine.com" with open('README.md', 'r') as f: LONG_DESCRIPTION = f.read() extra = {} if version_info >= (3,): extra['use_2to3'] = True extra['convert_2to3_doctests'] = ['README.md'] logging.basicConfig(stream=stdout) logging.getLogger("tests").setLevel(logging.DEBUG) setup( name='PyComicVine', version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author='Martin Lenders', author_email='authmillenon@gmail.com', url='http://www.github.com/authmillenon/pycomicvine/', packages=['pycomicvine', 'pycomicvine.tests'], install_requires=['simplejson','python-dateutil >= 2.0'], license="MIT License", test_suite='pycomicvine.tests', **extra ) Remove simplejson for Python 3.2.x since there is no support
#!/usr/bin/env python from setuptools import setup from distutils.core import Command from sys import stdout, version_info import logging VERSION = '0.9' DESCRIPTION = "A wrapper for comicvine.com" with open('README.md', 'r') as f: LONG_DESCRIPTION = f.read() extra = {} if version_info >= (3,): extra['use_2to3'] = True extra['convert_2to3_doctests'] = ['README.md'] if version_info >= (3,2,) and version_info < (3,3,): extra['install_requires'] = ['python-dateutil >= 2.0'] else: extra['install_requires'] = ['simplejson', 'python-dateutil >= 2.0'] logging.basicConfig(stream=stdout) logging.getLogger("tests").setLevel(logging.DEBUG) setup( name='PyComicVine', version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author='Martin Lenders', author_email='authmillenon@gmail.com', url='http://www.github.com/authmillenon/pycomicvine/', packages=['pycomicvine', 'pycomicvine.tests'], license="MIT License", test_suite='pycomicvine.tests', **extra )
<commit_before>#!/usr/bin/env python from setuptools import setup from distutils.core import Command from sys import stdout, version_info import logging VERSION = '0.9' DESCRIPTION = "A wrapper for comicvine.com" with open('README.md', 'r') as f: LONG_DESCRIPTION = f.read() extra = {} if version_info >= (3,): extra['use_2to3'] = True extra['convert_2to3_doctests'] = ['README.md'] logging.basicConfig(stream=stdout) logging.getLogger("tests").setLevel(logging.DEBUG) setup( name='PyComicVine', version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author='Martin Lenders', author_email='authmillenon@gmail.com', url='http://www.github.com/authmillenon/pycomicvine/', packages=['pycomicvine', 'pycomicvine.tests'], install_requires=['simplejson','python-dateutil >= 2.0'], license="MIT License", test_suite='pycomicvine.tests', **extra ) <commit_msg>Remove simplejson for Python 3.2.x since there is no support<commit_after>
#!/usr/bin/env python from setuptools import setup from distutils.core import Command from sys import stdout, version_info import logging VERSION = '0.9' DESCRIPTION = "A wrapper for comicvine.com" with open('README.md', 'r') as f: LONG_DESCRIPTION = f.read() extra = {} if version_info >= (3,): extra['use_2to3'] = True extra['convert_2to3_doctests'] = ['README.md'] if version_info >= (3,2,) and version_info < (3,3,): extra['install_requires'] = ['python-dateutil >= 2.0'] else: extra['install_requires'] = ['simplejson', 'python-dateutil >= 2.0'] logging.basicConfig(stream=stdout) logging.getLogger("tests").setLevel(logging.DEBUG) setup( name='PyComicVine', version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author='Martin Lenders', author_email='authmillenon@gmail.com', url='http://www.github.com/authmillenon/pycomicvine/', packages=['pycomicvine', 'pycomicvine.tests'], license="MIT License", test_suite='pycomicvine.tests', **extra )
#!/usr/bin/env python from setuptools import setup from distutils.core import Command from sys import stdout, version_info import logging VERSION = '0.9' DESCRIPTION = "A wrapper for comicvine.com" with open('README.md', 'r') as f: LONG_DESCRIPTION = f.read() extra = {} if version_info >= (3,): extra['use_2to3'] = True extra['convert_2to3_doctests'] = ['README.md'] logging.basicConfig(stream=stdout) logging.getLogger("tests").setLevel(logging.DEBUG) setup( name='PyComicVine', version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author='Martin Lenders', author_email='authmillenon@gmail.com', url='http://www.github.com/authmillenon/pycomicvine/', packages=['pycomicvine', 'pycomicvine.tests'], install_requires=['simplejson','python-dateutil >= 2.0'], license="MIT License", test_suite='pycomicvine.tests', **extra ) Remove simplejson for Python 3.2.x since there is no support#!/usr/bin/env python from setuptools import setup from distutils.core import Command from sys import stdout, version_info import logging VERSION = '0.9' DESCRIPTION = "A wrapper for comicvine.com" with open('README.md', 'r') as f: LONG_DESCRIPTION = f.read() extra = {} if version_info >= (3,): extra['use_2to3'] = True extra['convert_2to3_doctests'] = ['README.md'] if version_info >= (3,2,) and version_info < (3,3,): extra['install_requires'] = ['python-dateutil >= 2.0'] else: extra['install_requires'] = ['simplejson', 'python-dateutil >= 2.0'] logging.basicConfig(stream=stdout) logging.getLogger("tests").setLevel(logging.DEBUG) setup( name='PyComicVine', version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author='Martin Lenders', author_email='authmillenon@gmail.com', url='http://www.github.com/authmillenon/pycomicvine/', packages=['pycomicvine', 'pycomicvine.tests'], license="MIT License", test_suite='pycomicvine.tests', **extra )
<commit_before>#!/usr/bin/env python from setuptools import setup from distutils.core import Command from sys import stdout, version_info import logging VERSION = '0.9' DESCRIPTION = "A wrapper for comicvine.com" with open('README.md', 'r') as f: LONG_DESCRIPTION = f.read() extra = {} if version_info >= (3,): extra['use_2to3'] = True extra['convert_2to3_doctests'] = ['README.md'] logging.basicConfig(stream=stdout) logging.getLogger("tests").setLevel(logging.DEBUG) setup( name='PyComicVine', version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author='Martin Lenders', author_email='authmillenon@gmail.com', url='http://www.github.com/authmillenon/pycomicvine/', packages=['pycomicvine', 'pycomicvine.tests'], install_requires=['simplejson','python-dateutil >= 2.0'], license="MIT License", test_suite='pycomicvine.tests', **extra ) <commit_msg>Remove simplejson for Python 3.2.x since there is no support<commit_after>#!/usr/bin/env python from setuptools import setup from distutils.core import Command from sys import stdout, version_info import logging VERSION = '0.9' DESCRIPTION = "A wrapper for comicvine.com" with open('README.md', 'r') as f: LONG_DESCRIPTION = f.read() extra = {} if version_info >= (3,): extra['use_2to3'] = True extra['convert_2to3_doctests'] = ['README.md'] if version_info >= (3,2,) and version_info < (3,3,): extra['install_requires'] = ['python-dateutil >= 2.0'] else: extra['install_requires'] = ['simplejson', 'python-dateutil >= 2.0'] logging.basicConfig(stream=stdout) logging.getLogger("tests").setLevel(logging.DEBUG) setup( name='PyComicVine', version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author='Martin Lenders', author_email='authmillenon@gmail.com', url='http://www.github.com/authmillenon/pycomicvine/', packages=['pycomicvine', 'pycomicvine.tests'], license="MIT License", test_suite='pycomicvine.tests', **extra )
016cb79166bfaeb28f5d1a0c540f7e0632d485a1
setup.py
setup.py
from distutils.core import setup VERSION = '0.0.2.8' setup( name='jpp', version=VERSION, packages=['jpp', 'jpp.parser', 'jpp.cli_test', 'jpp.cli_test.sub_path'], url='https://github.com/asherbar/json-plus-plus/archive/{}.tar.gz'.format(VERSION), license='MIT', author='asherbar', author_email='asherbare@gmail.com', description='An extension of JSON with an emphasis on reusability', install_requires=['ply'], entry_points={ 'console_scripts': [ 'jpp=jpp.cli:main', ], }, )
from distutils.core import setup VERSION = '0.0.2.8' setup( name='jpp', version=VERSION, packages=['jpp', 'jpp.parser', 'jpp.cli_test'], url='https://github.com/asherbar/json-plus-plus/archive/{}.tar.gz'.format(VERSION), license='MIT', author='asherbar', author_email='asherbare@gmail.com', description='An extension of JSON with an emphasis on reusability', install_requires=['ply'], entry_points={ 'console_scripts': [ 'jpp=jpp.cli:main', ], }, )
Fix error due to missing package in packages list
Fix error due to missing package in packages list
Python
mit
asherbar/json-plus-plus
from distutils.core import setup VERSION = '0.0.2.8' setup( name='jpp', version=VERSION, packages=['jpp', 'jpp.parser', 'jpp.cli_test', 'jpp.cli_test.sub_path'], url='https://github.com/asherbar/json-plus-plus/archive/{}.tar.gz'.format(VERSION), license='MIT', author='asherbar', author_email='asherbare@gmail.com', description='An extension of JSON with an emphasis on reusability', install_requires=['ply'], entry_points={ 'console_scripts': [ 'jpp=jpp.cli:main', ], }, ) Fix error due to missing package in packages list
from distutils.core import setup VERSION = '0.0.2.8' setup( name='jpp', version=VERSION, packages=['jpp', 'jpp.parser', 'jpp.cli_test'], url='https://github.com/asherbar/json-plus-plus/archive/{}.tar.gz'.format(VERSION), license='MIT', author='asherbar', author_email='asherbare@gmail.com', description='An extension of JSON with an emphasis on reusability', install_requires=['ply'], entry_points={ 'console_scripts': [ 'jpp=jpp.cli:main', ], }, )
<commit_before>from distutils.core import setup VERSION = '0.0.2.8' setup( name='jpp', version=VERSION, packages=['jpp', 'jpp.parser', 'jpp.cli_test', 'jpp.cli_test.sub_path'], url='https://github.com/asherbar/json-plus-plus/archive/{}.tar.gz'.format(VERSION), license='MIT', author='asherbar', author_email='asherbare@gmail.com', description='An extension of JSON with an emphasis on reusability', install_requires=['ply'], entry_points={ 'console_scripts': [ 'jpp=jpp.cli:main', ], }, ) <commit_msg>Fix error due to missing package in packages list<commit_after>
from distutils.core import setup VERSION = '0.0.2.8' setup( name='jpp', version=VERSION, packages=['jpp', 'jpp.parser', 'jpp.cli_test'], url='https://github.com/asherbar/json-plus-plus/archive/{}.tar.gz'.format(VERSION), license='MIT', author='asherbar', author_email='asherbare@gmail.com', description='An extension of JSON with an emphasis on reusability', install_requires=['ply'], entry_points={ 'console_scripts': [ 'jpp=jpp.cli:main', ], }, )
from distutils.core import setup VERSION = '0.0.2.8' setup( name='jpp', version=VERSION, packages=['jpp', 'jpp.parser', 'jpp.cli_test', 'jpp.cli_test.sub_path'], url='https://github.com/asherbar/json-plus-plus/archive/{}.tar.gz'.format(VERSION), license='MIT', author='asherbar', author_email='asherbare@gmail.com', description='An extension of JSON with an emphasis on reusability', install_requires=['ply'], entry_points={ 'console_scripts': [ 'jpp=jpp.cli:main', ], }, ) Fix error due to missing package in packages listfrom distutils.core import setup VERSION = '0.0.2.8' setup( name='jpp', version=VERSION, packages=['jpp', 'jpp.parser', 'jpp.cli_test'], url='https://github.com/asherbar/json-plus-plus/archive/{}.tar.gz'.format(VERSION), license='MIT', author='asherbar', author_email='asherbare@gmail.com', description='An extension of JSON with an emphasis on reusability', install_requires=['ply'], entry_points={ 'console_scripts': [ 'jpp=jpp.cli:main', ], }, )
<commit_before>from distutils.core import setup VERSION = '0.0.2.8' setup( name='jpp', version=VERSION, packages=['jpp', 'jpp.parser', 'jpp.cli_test', 'jpp.cli_test.sub_path'], url='https://github.com/asherbar/json-plus-plus/archive/{}.tar.gz'.format(VERSION), license='MIT', author='asherbar', author_email='asherbare@gmail.com', description='An extension of JSON with an emphasis on reusability', install_requires=['ply'], entry_points={ 'console_scripts': [ 'jpp=jpp.cli:main', ], }, ) <commit_msg>Fix error due to missing package in packages list<commit_after>from distutils.core import setup VERSION = '0.0.2.8' setup( name='jpp', version=VERSION, packages=['jpp', 'jpp.parser', 'jpp.cli_test'], url='https://github.com/asherbar/json-plus-plus/archive/{}.tar.gz'.format(VERSION), license='MIT', author='asherbar', author_email='asherbare@gmail.com', description='An extension of JSON with an emphasis on reusability', install_requires=['ply'], entry_points={ 'console_scripts': [ 'jpp=jpp.cli:main', ], }, )
b7ab1cb1cf4f19c0537be9a59bbf4af8ced9f0ec
setup.py
setup.py
from setuptools import setup import species_separator setup( name="species_separator", version=species_separator.__version__, url='https://github.com/statbio/Sargasso', license='MIT License', author='Owen Dando', author_email='owen.dando@ed.ac.uk', packages=['species_separator'], install_requires=[ 'Babel==2.2.0', 'Jinja2==2.8', 'MarkupSafe==0.23', 'Pygments==2.1.3', 'Sphinx==1.4', 'alabaster==0.7.7', 'docopt==0.6.2', 'docutils==0.12', 'imagesize==0.7.0', 'pysam==0.8.2.1', 'pytz==2016.3', 'schema==0.3.1', 'six==1.10.0', 'snowballstemmer==1.2.1', ], scripts=[ 'bin/build_star_index', 'bin/collate_raw_reads', 'bin/filter_control', 'bin/filter_reads', 'bin/filter_sample_reads', 'bin/map_reads', 'bin/sort_reads', 'bin/species_separator', ] )
from setuptools import setup import species_separator setup( name="species_separator", version=species_separator.__version__, url='https://github.com/statbio/Sargasso', license='MIT License', author='Owen Dando', author_email='owen.dando@ed.ac.uk', packages=['species_separator'], install_requires=[ 'docopt==0.6.2', 'pysam==0.8.2.1', 'schema==0.3.1', ], scripts=[ 'bin/build_star_index', 'bin/collate_raw_reads', 'bin/filter_control', 'bin/filter_reads', 'bin/filter_sample_reads', 'bin/map_reads', 'bin/sort_reads', 'bin/species_separator', ] )
Remove old packages only needed by Sphinx.
Remove old packages only needed by Sphinx.
Python
mit
statbio/Sargasso,statbio/Sargasso
from setuptools import setup import species_separator setup( name="species_separator", version=species_separator.__version__, url='https://github.com/statbio/Sargasso', license='MIT License', author='Owen Dando', author_email='owen.dando@ed.ac.uk', packages=['species_separator'], install_requires=[ 'Babel==2.2.0', 'Jinja2==2.8', 'MarkupSafe==0.23', 'Pygments==2.1.3', 'Sphinx==1.4', 'alabaster==0.7.7', 'docopt==0.6.2', 'docutils==0.12', 'imagesize==0.7.0', 'pysam==0.8.2.1', 'pytz==2016.3', 'schema==0.3.1', 'six==1.10.0', 'snowballstemmer==1.2.1', ], scripts=[ 'bin/build_star_index', 'bin/collate_raw_reads', 'bin/filter_control', 'bin/filter_reads', 'bin/filter_sample_reads', 'bin/map_reads', 'bin/sort_reads', 'bin/species_separator', ] ) Remove old packages only needed by Sphinx.
from setuptools import setup import species_separator setup( name="species_separator", version=species_separator.__version__, url='https://github.com/statbio/Sargasso', license='MIT License', author='Owen Dando', author_email='owen.dando@ed.ac.uk', packages=['species_separator'], install_requires=[ 'docopt==0.6.2', 'pysam==0.8.2.1', 'schema==0.3.1', ], scripts=[ 'bin/build_star_index', 'bin/collate_raw_reads', 'bin/filter_control', 'bin/filter_reads', 'bin/filter_sample_reads', 'bin/map_reads', 'bin/sort_reads', 'bin/species_separator', ] )
<commit_before>from setuptools import setup import species_separator setup( name="species_separator", version=species_separator.__version__, url='https://github.com/statbio/Sargasso', license='MIT License', author='Owen Dando', author_email='owen.dando@ed.ac.uk', packages=['species_separator'], install_requires=[ 'Babel==2.2.0', 'Jinja2==2.8', 'MarkupSafe==0.23', 'Pygments==2.1.3', 'Sphinx==1.4', 'alabaster==0.7.7', 'docopt==0.6.2', 'docutils==0.12', 'imagesize==0.7.0', 'pysam==0.8.2.1', 'pytz==2016.3', 'schema==0.3.1', 'six==1.10.0', 'snowballstemmer==1.2.1', ], scripts=[ 'bin/build_star_index', 'bin/collate_raw_reads', 'bin/filter_control', 'bin/filter_reads', 'bin/filter_sample_reads', 'bin/map_reads', 'bin/sort_reads', 'bin/species_separator', ] ) <commit_msg>Remove old packages only needed by Sphinx.<commit_after>
from setuptools import setup import species_separator setup( name="species_separator", version=species_separator.__version__, url='https://github.com/statbio/Sargasso', license='MIT License', author='Owen Dando', author_email='owen.dando@ed.ac.uk', packages=['species_separator'], install_requires=[ 'docopt==0.6.2', 'pysam==0.8.2.1', 'schema==0.3.1', ], scripts=[ 'bin/build_star_index', 'bin/collate_raw_reads', 'bin/filter_control', 'bin/filter_reads', 'bin/filter_sample_reads', 'bin/map_reads', 'bin/sort_reads', 'bin/species_separator', ] )
from setuptools import setup import species_separator setup( name="species_separator", version=species_separator.__version__, url='https://github.com/statbio/Sargasso', license='MIT License', author='Owen Dando', author_email='owen.dando@ed.ac.uk', packages=['species_separator'], install_requires=[ 'Babel==2.2.0', 'Jinja2==2.8', 'MarkupSafe==0.23', 'Pygments==2.1.3', 'Sphinx==1.4', 'alabaster==0.7.7', 'docopt==0.6.2', 'docutils==0.12', 'imagesize==0.7.0', 'pysam==0.8.2.1', 'pytz==2016.3', 'schema==0.3.1', 'six==1.10.0', 'snowballstemmer==1.2.1', ], scripts=[ 'bin/build_star_index', 'bin/collate_raw_reads', 'bin/filter_control', 'bin/filter_reads', 'bin/filter_sample_reads', 'bin/map_reads', 'bin/sort_reads', 'bin/species_separator', ] ) Remove old packages only needed by Sphinx.from setuptools import setup import species_separator setup( name="species_separator", version=species_separator.__version__, url='https://github.com/statbio/Sargasso', license='MIT License', author='Owen Dando', author_email='owen.dando@ed.ac.uk', packages=['species_separator'], install_requires=[ 'docopt==0.6.2', 'pysam==0.8.2.1', 'schema==0.3.1', ], scripts=[ 'bin/build_star_index', 'bin/collate_raw_reads', 'bin/filter_control', 'bin/filter_reads', 'bin/filter_sample_reads', 'bin/map_reads', 'bin/sort_reads', 'bin/species_separator', ] )
<commit_before>from setuptools import setup import species_separator setup( name="species_separator", version=species_separator.__version__, url='https://github.com/statbio/Sargasso', license='MIT License', author='Owen Dando', author_email='owen.dando@ed.ac.uk', packages=['species_separator'], install_requires=[ 'Babel==2.2.0', 'Jinja2==2.8', 'MarkupSafe==0.23', 'Pygments==2.1.3', 'Sphinx==1.4', 'alabaster==0.7.7', 'docopt==0.6.2', 'docutils==0.12', 'imagesize==0.7.0', 'pysam==0.8.2.1', 'pytz==2016.3', 'schema==0.3.1', 'six==1.10.0', 'snowballstemmer==1.2.1', ], scripts=[ 'bin/build_star_index', 'bin/collate_raw_reads', 'bin/filter_control', 'bin/filter_reads', 'bin/filter_sample_reads', 'bin/map_reads', 'bin/sort_reads', 'bin/species_separator', ] ) <commit_msg>Remove old packages only needed by Sphinx.<commit_after>from setuptools import setup import species_separator setup( name="species_separator", version=species_separator.__version__, url='https://github.com/statbio/Sargasso', license='MIT License', author='Owen Dando', author_email='owen.dando@ed.ac.uk', packages=['species_separator'], install_requires=[ 'docopt==0.6.2', 'pysam==0.8.2.1', 'schema==0.3.1', ], scripts=[ 'bin/build_star_index', 'bin/collate_raw_reads', 'bin/filter_control', 'bin/filter_reads', 'bin/filter_sample_reads', 'bin/map_reads', 'bin/sort_reads', 'bin/species_separator', ] )
0d300b0f7f1efd208d7e7bcb341ece39a3d7daab
setup.py
setup.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='rotunicode', version='0.1.3', description='Python codec for converting between a string of ASCII ' 'and Unicode chars maintaining readability', long_description=open(join(base_dir, 'README.rst')).read(), author='Kunal Parmar', author_email='kunalparmar@gmail.com', url='https://pypi.python.org/pypi/rotunicode', license=open(join(base_dir, 'LICENSE')).read(), packages=find_packages(exclude=['test']), namespace_packages=[b'box'], test_suite='test', zip_safe=False, ) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='rotunicode', version='0.1.3', description='Python codec for converting between a string of ASCII ' 'and Unicode chars maintaining readability', long_description=open(join(base_dir, 'README.rst')).read(), author='Kunal Parmar', author_email='kunalparmar@gmail.com', url='https://github.com/box/rotunicode', license=open(join(base_dir, 'LICENSE')).read(), packages=find_packages(exclude=['test']), namespace_packages=[b'box'], test_suite='test', zip_safe=False, ) if __name__ == '__main__': main()
Update URL to point to GitHub.
Update URL to point to GitHub.
Python
apache-2.0
box/rotunicode,box/rotunicode
# -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='rotunicode', version='0.1.3', description='Python codec for converting between a string of ASCII ' 'and Unicode chars maintaining readability', long_description=open(join(base_dir, 'README.rst')).read(), author='Kunal Parmar', author_email='kunalparmar@gmail.com', url='https://pypi.python.org/pypi/rotunicode', license=open(join(base_dir, 'LICENSE')).read(), packages=find_packages(exclude=['test']), namespace_packages=[b'box'], test_suite='test', zip_safe=False, ) if __name__ == '__main__': main() Update URL to point to GitHub.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='rotunicode', version='0.1.3', description='Python codec for converting between a string of ASCII ' 'and Unicode chars maintaining readability', long_description=open(join(base_dir, 'README.rst')).read(), author='Kunal Parmar', author_email='kunalparmar@gmail.com', url='https://github.com/box/rotunicode', license=open(join(base_dir, 'LICENSE')).read(), packages=find_packages(exclude=['test']), namespace_packages=[b'box'], test_suite='test', zip_safe=False, ) if __name__ == '__main__': main()
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='rotunicode', version='0.1.3', description='Python codec for converting between a string of ASCII ' 'and Unicode chars maintaining readability', long_description=open(join(base_dir, 'README.rst')).read(), author='Kunal Parmar', author_email='kunalparmar@gmail.com', url='https://pypi.python.org/pypi/rotunicode', license=open(join(base_dir, 'LICENSE')).read(), packages=find_packages(exclude=['test']), namespace_packages=[b'box'], test_suite='test', zip_safe=False, ) if __name__ == '__main__': main() <commit_msg>Update URL to point to GitHub.<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='rotunicode', version='0.1.3', description='Python codec for converting between a string of ASCII ' 'and Unicode chars maintaining readability', long_description=open(join(base_dir, 'README.rst')).read(), author='Kunal Parmar', author_email='kunalparmar@gmail.com', url='https://github.com/box/rotunicode', license=open(join(base_dir, 'LICENSE')).read(), packages=find_packages(exclude=['test']), namespace_packages=[b'box'], test_suite='test', zip_safe=False, ) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='rotunicode', version='0.1.3', description='Python codec for converting between a string of ASCII ' 'and Unicode chars maintaining readability', long_description=open(join(base_dir, 'README.rst')).read(), author='Kunal Parmar', author_email='kunalparmar@gmail.com', url='https://pypi.python.org/pypi/rotunicode', license=open(join(base_dir, 'LICENSE')).read(), packages=find_packages(exclude=['test']), namespace_packages=[b'box'], test_suite='test', zip_safe=False, ) if __name__ == '__main__': main() Update URL to point to GitHub.# -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='rotunicode', version='0.1.3', description='Python codec for converting between a string of ASCII ' 'and Unicode chars maintaining readability', long_description=open(join(base_dir, 'README.rst')).read(), author='Kunal Parmar', author_email='kunalparmar@gmail.com', url='https://github.com/box/rotunicode', license=open(join(base_dir, 'LICENSE')).read(), packages=find_packages(exclude=['test']), namespace_packages=[b'box'], test_suite='test', zip_safe=False, ) if __name__ == '__main__': main()
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='rotunicode', version='0.1.3', description='Python codec for converting between a string of ASCII ' 'and Unicode chars maintaining readability', long_description=open(join(base_dir, 'README.rst')).read(), author='Kunal Parmar', author_email='kunalparmar@gmail.com', url='https://pypi.python.org/pypi/rotunicode', license=open(join(base_dir, 'LICENSE')).read(), packages=find_packages(exclude=['test']), namespace_packages=[b'box'], test_suite='test', zip_safe=False, ) if __name__ == '__main__': main() <commit_msg>Update URL to point to GitHub.<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from setuptools import setup, find_packages from os.path import dirname, join def main(): base_dir = dirname(__file__) setup( name='rotunicode', version='0.1.3', description='Python codec for converting between a string of ASCII ' 'and Unicode chars maintaining readability', long_description=open(join(base_dir, 'README.rst')).read(), author='Kunal Parmar', author_email='kunalparmar@gmail.com', url='https://github.com/box/rotunicode', license=open(join(base_dir, 'LICENSE')).read(), packages=find_packages(exclude=['test']), namespace_packages=[b'box'], test_suite='test', zip_safe=False, ) if __name__ == '__main__': main()
cb6d0ea6c05eb62fafe97ac13d5665cb00b2db3c
setup.py
setup.py
#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE> from distutils.core import setup setup(name='spherical_functions', version='1.0', description='Python/numba implementation of Wigner D Matrices, spin-weighted spherical harmonics, and associated functions', author='Michael Boyle', # author_email='', url='https://github.com/moble/spherical_functions', package_dir={'spherical_functions': ''}, packages=['spherical_functions',], )
#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE> from distutils.core import setup setup(name='spherical_functions', version='1.0', description='Python/numba implementation of Wigner D Matrices, spin-weighted spherical harmonics, and associated functions', author='Michael Boyle', # author_email='', url='https://github.com/moble/spherical_functions', packages=['spherical_functions',], package_dir={'spherical_functions': ''}, package_data={'spherical_functions': ['Wigner_coefficients.npy', 'binomial_coefficients.npy', 'ladder_operator_coefficients.npy']}, )
Copy data files for numpy
Copy data files for numpy
Python
mit
moble/spherical_functions
#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE> from distutils.core import setup setup(name='spherical_functions', version='1.0', description='Python/numba implementation of Wigner D Matrices, spin-weighted spherical harmonics, and associated functions', author='Michael Boyle', # author_email='', url='https://github.com/moble/spherical_functions', package_dir={'spherical_functions': ''}, packages=['spherical_functions',], ) Copy data files for numpy
#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE> from distutils.core import setup setup(name='spherical_functions', version='1.0', description='Python/numba implementation of Wigner D Matrices, spin-weighted spherical harmonics, and associated functions', author='Michael Boyle', # author_email='', url='https://github.com/moble/spherical_functions', packages=['spherical_functions',], package_dir={'spherical_functions': ''}, package_data={'spherical_functions': ['Wigner_coefficients.npy', 'binomial_coefficients.npy', 'ladder_operator_coefficients.npy']}, )
<commit_before>#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE> from distutils.core import setup setup(name='spherical_functions', version='1.0', description='Python/numba implementation of Wigner D Matrices, spin-weighted spherical harmonics, and associated functions', author='Michael Boyle', # author_email='', url='https://github.com/moble/spherical_functions', package_dir={'spherical_functions': ''}, packages=['spherical_functions',], ) <commit_msg>Copy data files for numpy<commit_after>
#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE> from distutils.core import setup setup(name='spherical_functions', version='1.0', description='Python/numba implementation of Wigner D Matrices, spin-weighted spherical harmonics, and associated functions', author='Michael Boyle', # author_email='', url='https://github.com/moble/spherical_functions', packages=['spherical_functions',], package_dir={'spherical_functions': ''}, package_data={'spherical_functions': ['Wigner_coefficients.npy', 'binomial_coefficients.npy', 'ladder_operator_coefficients.npy']}, )
#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE> from distutils.core import setup setup(name='spherical_functions', version='1.0', description='Python/numba implementation of Wigner D Matrices, spin-weighted spherical harmonics, and associated functions', author='Michael Boyle', # author_email='', url='https://github.com/moble/spherical_functions', package_dir={'spherical_functions': ''}, packages=['spherical_functions',], ) Copy data files for numpy#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE> from distutils.core import setup setup(name='spherical_functions', version='1.0', description='Python/numba implementation of Wigner D Matrices, spin-weighted spherical harmonics, and associated functions', author='Michael Boyle', # author_email='', url='https://github.com/moble/spherical_functions', packages=['spherical_functions',], package_dir={'spherical_functions': ''}, package_data={'spherical_functions': ['Wigner_coefficients.npy', 'binomial_coefficients.npy', 'ladder_operator_coefficients.npy']}, )
<commit_before>#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE> from distutils.core import setup setup(name='spherical_functions', version='1.0', description='Python/numba implementation of Wigner D Matrices, spin-weighted spherical harmonics, and associated functions', author='Michael Boyle', # author_email='', url='https://github.com/moble/spherical_functions', package_dir={'spherical_functions': ''}, packages=['spherical_functions',], ) <commit_msg>Copy data files for numpy<commit_after>#!/usr/bin/env python # Copyright (c) 2014, Michael Boyle # See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE> from distutils.core import setup setup(name='spherical_functions', version='1.0', description='Python/numba implementation of Wigner D Matrices, spin-weighted spherical harmonics, and associated functions', author='Michael Boyle', # author_email='', url='https://github.com/moble/spherical_functions', packages=['spherical_functions',], package_dir={'spherical_functions': ''}, package_data={'spherical_functions': ['Wigner_coefficients.npy', 'binomial_coefficients.npy', 'ladder_operator_coefficients.npy']}, )
d2a6bbb824c6a0be5402ddb304f2fa629513a910
setup.py
setup.py
from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='portstat', version='0.0.1', keywords=('port', 'monitor', 'traffic'), url='https://github.com/imlonghao/portstat', license='Apache License 2.0', author='imlonghao', author_email='shield@fastmail.com', description='A simple port traffic monitor', long_description=long_description, packages=find_packages(), platforms='any', entry_points={ 'console_scripts': [ 'portstat=portstat.portstat:main' ] } )
from setuptools import setup, find_packages from os import path from codecs import open here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='portstat', version='0.0.1', keywords=('port', 'monitor', 'traffic'), url='https://github.com/imlonghao/portstat', license='Apache License 2.0', author='imlonghao', author_email='shield@fastmail.com', description='A simple port traffic monitor', long_description=long_description, packages=find_packages(), platforms='any', entry_points={ 'console_scripts': [ 'portstat=portstat.portstat:main' ] } )
Fix the problem in Python 2.x
Fix the problem in Python 2.x
Python
apache-2.0
imlonghao/portstat
from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='portstat', version='0.0.1', keywords=('port', 'monitor', 'traffic'), url='https://github.com/imlonghao/portstat', license='Apache License 2.0', author='imlonghao', author_email='shield@fastmail.com', description='A simple port traffic monitor', long_description=long_description, packages=find_packages(), platforms='any', entry_points={ 'console_scripts': [ 'portstat=portstat.portstat:main' ] } ) Fix the problem in Python 2.x
from setuptools import setup, find_packages from os import path from codecs import open here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='portstat', version='0.0.1', keywords=('port', 'monitor', 'traffic'), url='https://github.com/imlonghao/portstat', license='Apache License 2.0', author='imlonghao', author_email='shield@fastmail.com', description='A simple port traffic monitor', long_description=long_description, packages=find_packages(), platforms='any', entry_points={ 'console_scripts': [ 'portstat=portstat.portstat:main' ] } )
<commit_before>from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='portstat', version='0.0.1', keywords=('port', 'monitor', 'traffic'), url='https://github.com/imlonghao/portstat', license='Apache License 2.0', author='imlonghao', author_email='shield@fastmail.com', description='A simple port traffic monitor', long_description=long_description, packages=find_packages(), platforms='any', entry_points={ 'console_scripts': [ 'portstat=portstat.portstat:main' ] } ) <commit_msg>Fix the problem in Python 2.x<commit_after>
from setuptools import setup, find_packages from os import path from codecs import open here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='portstat', version='0.0.1', keywords=('port', 'monitor', 'traffic'), url='https://github.com/imlonghao/portstat', license='Apache License 2.0', author='imlonghao', author_email='shield@fastmail.com', description='A simple port traffic monitor', long_description=long_description, packages=find_packages(), platforms='any', entry_points={ 'console_scripts': [ 'portstat=portstat.portstat:main' ] } )
from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='portstat', version='0.0.1', keywords=('port', 'monitor', 'traffic'), url='https://github.com/imlonghao/portstat', license='Apache License 2.0', author='imlonghao', author_email='shield@fastmail.com', description='A simple port traffic monitor', long_description=long_description, packages=find_packages(), platforms='any', entry_points={ 'console_scripts': [ 'portstat=portstat.portstat:main' ] } ) Fix the problem in Python 2.xfrom setuptools import setup, find_packages from os import path from codecs import open here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='portstat', version='0.0.1', keywords=('port', 'monitor', 'traffic'), url='https://github.com/imlonghao/portstat', license='Apache License 2.0', author='imlonghao', author_email='shield@fastmail.com', description='A simple port traffic monitor', long_description=long_description, packages=find_packages(), platforms='any', entry_points={ 'console_scripts': [ 'portstat=portstat.portstat:main' ] } )
<commit_before>from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='portstat', version='0.0.1', keywords=('port', 'monitor', 'traffic'), url='https://github.com/imlonghao/portstat', license='Apache License 2.0', author='imlonghao', author_email='shield@fastmail.com', description='A simple port traffic monitor', long_description=long_description, packages=find_packages(), platforms='any', entry_points={ 'console_scripts': [ 'portstat=portstat.portstat:main' ] } ) <commit_msg>Fix the problem in Python 2.x<commit_after>from setuptools import setup, find_packages from os import path from codecs import open here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='portstat', version='0.0.1', keywords=('port', 'monitor', 'traffic'), url='https://github.com/imlonghao/portstat', license='Apache License 2.0', author='imlonghao', author_email='shield@fastmail.com', description='A simple port traffic monitor', long_description=long_description, packages=find_packages(), platforms='any', entry_points={ 'console_scripts': [ 'portstat=portstat.portstat:main' ] } )
1449dbb7dd769b0d806bdfd8c7e3bfda632af5b9
setup.py
setup.py
from setuptools import setup, find_packages setup( name='pyop', version='2.0.8', packages=find_packages('src'), package_dir={'': 'src'}, url='https://github.com/IdentityPython/pyop', license='Apache 2.0', author='Rebecka Gulliksson', author_email='satosa-dev@lists.sunet.se', description='OpenID Connect Provider (OP) library in Python.', install_requires=[ 'oic<0.12', 'pymongo' ] )
from setuptools import setup, find_packages setup( name='pyop', version='2.0.8', packages=find_packages('src'), package_dir={'': 'src'}, url='https://github.com/IdentityPython/pyop', license='Apache 2.0', author='Rebecka Gulliksson', author_email='satosa-dev@lists.sunet.se', description='OpenID Connect Provider (OP) library in Python.', install_requires=[ 'oic>0.13.1', 'pymongo' ] )
Use the latest version of pyoidc/oic dependency
Use the latest version of pyoidc/oic dependency Signed-off-by: Ivan Kanakarakis <f60d6943d72436645c4304926eeeac2718a1142c@gmail.com>
Python
apache-2.0
its-dirg/pyop
from setuptools import setup, find_packages setup( name='pyop', version='2.0.8', packages=find_packages('src'), package_dir={'': 'src'}, url='https://github.com/IdentityPython/pyop', license='Apache 2.0', author='Rebecka Gulliksson', author_email='satosa-dev@lists.sunet.se', description='OpenID Connect Provider (OP) library in Python.', install_requires=[ 'oic<0.12', 'pymongo' ] ) Use the latest version of pyoidc/oic dependency Signed-off-by: Ivan Kanakarakis <f60d6943d72436645c4304926eeeac2718a1142c@gmail.com>
from setuptools import setup, find_packages setup( name='pyop', version='2.0.8', packages=find_packages('src'), package_dir={'': 'src'}, url='https://github.com/IdentityPython/pyop', license='Apache 2.0', author='Rebecka Gulliksson', author_email='satosa-dev@lists.sunet.se', description='OpenID Connect Provider (OP) library in Python.', install_requires=[ 'oic>0.13.1', 'pymongo' ] )
<commit_before>from setuptools import setup, find_packages setup( name='pyop', version='2.0.8', packages=find_packages('src'), package_dir={'': 'src'}, url='https://github.com/IdentityPython/pyop', license='Apache 2.0', author='Rebecka Gulliksson', author_email='satosa-dev@lists.sunet.se', description='OpenID Connect Provider (OP) library in Python.', install_requires=[ 'oic<0.12', 'pymongo' ] ) <commit_msg>Use the latest version of pyoidc/oic dependency Signed-off-by: Ivan Kanakarakis <f60d6943d72436645c4304926eeeac2718a1142c@gmail.com><commit_after>
from setuptools import setup, find_packages setup( name='pyop', version='2.0.8', packages=find_packages('src'), package_dir={'': 'src'}, url='https://github.com/IdentityPython/pyop', license='Apache 2.0', author='Rebecka Gulliksson', author_email='satosa-dev@lists.sunet.se', description='OpenID Connect Provider (OP) library in Python.', install_requires=[ 'oic>0.13.1', 'pymongo' ] )
from setuptools import setup, find_packages setup( name='pyop', version='2.0.8', packages=find_packages('src'), package_dir={'': 'src'}, url='https://github.com/IdentityPython/pyop', license='Apache 2.0', author='Rebecka Gulliksson', author_email='satosa-dev@lists.sunet.se', description='OpenID Connect Provider (OP) library in Python.', install_requires=[ 'oic<0.12', 'pymongo' ] ) Use the latest version of pyoidc/oic dependency Signed-off-by: Ivan Kanakarakis <f60d6943d72436645c4304926eeeac2718a1142c@gmail.com>from setuptools import setup, find_packages setup( name='pyop', version='2.0.8', packages=find_packages('src'), package_dir={'': 'src'}, url='https://github.com/IdentityPython/pyop', license='Apache 2.0', author='Rebecka Gulliksson', author_email='satosa-dev@lists.sunet.se', description='OpenID Connect Provider (OP) library in Python.', install_requires=[ 'oic>0.13.1', 'pymongo' ] )
<commit_before>from setuptools import setup, find_packages setup( name='pyop', version='2.0.8', packages=find_packages('src'), package_dir={'': 'src'}, url='https://github.com/IdentityPython/pyop', license='Apache 2.0', author='Rebecka Gulliksson', author_email='satosa-dev@lists.sunet.se', description='OpenID Connect Provider (OP) library in Python.', install_requires=[ 'oic<0.12', 'pymongo' ] ) <commit_msg>Use the latest version of pyoidc/oic dependency Signed-off-by: Ivan Kanakarakis <f60d6943d72436645c4304926eeeac2718a1142c@gmail.com><commit_after>from setuptools import setup, find_packages setup( name='pyop', version='2.0.8', packages=find_packages('src'), package_dir={'': 'src'}, url='https://github.com/IdentityPython/pyop', license='Apache 2.0', author='Rebecka Gulliksson', author_email='satosa-dev@lists.sunet.se', description='OpenID Connect Provider (OP) library in Python.', install_requires=[ 'oic>0.13.1', 'pymongo' ] )
3552fc831813477fa8ceebafe7358fddf59d881a
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import sys, os import django_throttling setup( name='django-throttling', version=django_throttling.get_version(), description="Basic throttling app for Django", long_description=open('README.rst', 'r').read(), keywords='django, throttling', author='Igor', author_email='lilo.panic@gmail.com', url='http://github.com.org/night-crawler/django-throttling', license='MIT', package_dir={'django_throttling': 'django_throttling'}, include_package_data=True, packages=find_packages(), classifiers=[ "Development Status :: 2 - Pre-Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Page Counters", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", "Topic :: Security", "Topic :: Utilities", ] )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import sys, os import django_throttling setup( name='django-throttling', version=django_throttling.get_version(), description="Basic throttling app for Django", long_description=open('README.rst', 'r').read(), keywords='django, throttling', author='Igor', author_email='lilo.panic@gmail.com', url='http://github.com/night-crawler/django-throttling', license='MIT', package_dir={'django_throttling': 'django_throttling'}, include_package_data=True, packages=find_packages(), classifiers=[ "Development Status :: 2 - Pre-Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Page Counters", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", "Topic :: Security", "Topic :: Utilities", ] )
Fix a mistake in a git url
Fix a mistake in a git url
Python
mit
night-crawler/django-throttling
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import sys, os import django_throttling setup( name='django-throttling', version=django_throttling.get_version(), description="Basic throttling app for Django", long_description=open('README.rst', 'r').read(), keywords='django, throttling', author='Igor', author_email='lilo.panic@gmail.com', url='http://github.com.org/night-crawler/django-throttling', license='MIT', package_dir={'django_throttling': 'django_throttling'}, include_package_data=True, packages=find_packages(), classifiers=[ "Development Status :: 2 - Pre-Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Page Counters", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", "Topic :: Security", "Topic :: Utilities", ] )Fix a mistake in a git url
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import sys, os import django_throttling setup( name='django-throttling', version=django_throttling.get_version(), description="Basic throttling app for Django", long_description=open('README.rst', 'r').read(), keywords='django, throttling', author='Igor', author_email='lilo.panic@gmail.com', url='http://github.com/night-crawler/django-throttling', license='MIT', package_dir={'django_throttling': 'django_throttling'}, include_package_data=True, packages=find_packages(), classifiers=[ "Development Status :: 2 - Pre-Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Page Counters", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", "Topic :: Security", "Topic :: Utilities", ] )
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import sys, os import django_throttling setup( name='django-throttling', version=django_throttling.get_version(), description="Basic throttling app for Django", long_description=open('README.rst', 'r').read(), keywords='django, throttling', author='Igor', author_email='lilo.panic@gmail.com', url='http://github.com.org/night-crawler/django-throttling', license='MIT', package_dir={'django_throttling': 'django_throttling'}, include_package_data=True, packages=find_packages(), classifiers=[ "Development Status :: 2 - Pre-Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Page Counters", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", "Topic :: Security", "Topic :: Utilities", ] )<commit_msg>Fix a mistake in a git url<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import sys, os import django_throttling setup( name='django-throttling', version=django_throttling.get_version(), description="Basic throttling app for Django", long_description=open('README.rst', 'r').read(), keywords='django, throttling', author='Igor', author_email='lilo.panic@gmail.com', url='http://github.com/night-crawler/django-throttling', license='MIT', package_dir={'django_throttling': 'django_throttling'}, include_package_data=True, packages=find_packages(), classifiers=[ "Development Status :: 2 - Pre-Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Page Counters", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", "Topic :: Security", "Topic :: Utilities", ] )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import sys, os import django_throttling setup( name='django-throttling', version=django_throttling.get_version(), description="Basic throttling app for Django", long_description=open('README.rst', 'r').read(), keywords='django, throttling', author='Igor', author_email='lilo.panic@gmail.com', url='http://github.com.org/night-crawler/django-throttling', license='MIT', package_dir={'django_throttling': 'django_throttling'}, include_package_data=True, packages=find_packages(), classifiers=[ "Development Status :: 2 - Pre-Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Page Counters", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", "Topic :: Security", "Topic :: Utilities", ] )Fix a mistake in a git url#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import sys, os import django_throttling setup( name='django-throttling', version=django_throttling.get_version(), description="Basic throttling app for Django", long_description=open('README.rst', 'r').read(), keywords='django, throttling', author='Igor', author_email='lilo.panic@gmail.com', url='http://github.com/night-crawler/django-throttling', license='MIT', package_dir={'django_throttling': 'django_throttling'}, include_package_data=True, packages=find_packages(), classifiers=[ "Development Status :: 2 - Pre-Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Page Counters", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", "Topic :: Security", "Topic :: Utilities", ] )
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import sys, os import django_throttling setup( name='django-throttling', version=django_throttling.get_version(), description="Basic throttling app for Django", long_description=open('README.rst', 'r').read(), keywords='django, throttling', author='Igor', author_email='lilo.panic@gmail.com', url='http://github.com.org/night-crawler/django-throttling', license='MIT', package_dir={'django_throttling': 'django_throttling'}, include_package_data=True, packages=find_packages(), classifiers=[ "Development Status :: 2 - Pre-Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Page Counters", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", "Topic :: Security", "Topic :: Utilities", ] )<commit_msg>Fix a mistake in a git url<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages import sys, os import django_throttling setup( name='django-throttling', version=django_throttling.get_version(), description="Basic throttling app for Django", long_description=open('README.rst', 'r').read(), keywords='django, throttling', author='Igor', author_email='lilo.panic@gmail.com', url='http://github.com/night-crawler/django-throttling', license='MIT', package_dir={'django_throttling': 'django_throttling'}, include_package_data=True, packages=find_packages(), classifiers=[ "Development Status :: 2 - Pre-Alpha", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Page Counters", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", "Topic :: Security", "Topic :: Utilities", ] )
339ea0bdb831d7f5f91d503a09c73e3b63e3a972
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='django-remote-forms', version='0.0.1', description='A platform independent form serializer for Django.', author='WiserTogether Tech Team', author_email='tech@wisertogether.com', url='http://github.com/wisertoghether/django-remote-forms/', long_description=open('README.md', 'r').read(), packages=[ 'django_remote_forms', ], package_data={ }, zip_safe=False, requires=[ ], install_requires=[ ], classifiers=[ 'Development Status :: Pre Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: MIT', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='django-remote-forms', version='0.0.2', description='A platform independent form serializer for Django.', author='WiserTogether Tech Team', author_email='tech@wisertogether.com', url='http://github.com/wisertoghether/django-remote-forms/', long_description=open('README.md', 'r').read(), packages=[ 'django_remote_forms', ], package_data={ }, zip_safe=False, requires=[ ], install_requires=[ ], classifiers=[ 'Development Status :: Pre Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: MIT', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
Upgrade the version to force reinstall by wheels
Upgrade the version to force reinstall by wheels
Python
mit
360youlun/django-remote-forms
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='django-remote-forms', version='0.0.1', description='A platform independent form serializer for Django.', author='WiserTogether Tech Team', author_email='tech@wisertogether.com', url='http://github.com/wisertoghether/django-remote-forms/', long_description=open('README.md', 'r').read(), packages=[ 'django_remote_forms', ], package_data={ }, zip_safe=False, requires=[ ], install_requires=[ ], classifiers=[ 'Development Status :: Pre Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: MIT', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], ) Upgrade the version to force reinstall by wheels
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='django-remote-forms', version='0.0.2', description='A platform independent form serializer for Django.', author='WiserTogether Tech Team', author_email='tech@wisertogether.com', url='http://github.com/wisertoghether/django-remote-forms/', long_description=open('README.md', 'r').read(), packages=[ 'django_remote_forms', ], package_data={ }, zip_safe=False, requires=[ ], install_requires=[ ], classifiers=[ 'Development Status :: Pre Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: MIT', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='django-remote-forms', version='0.0.1', description='A platform independent form serializer for Django.', author='WiserTogether Tech Team', author_email='tech@wisertogether.com', url='http://github.com/wisertoghether/django-remote-forms/', long_description=open('README.md', 'r').read(), packages=[ 'django_remote_forms', ], package_data={ }, zip_safe=False, requires=[ ], install_requires=[ ], classifiers=[ 'Development Status :: Pre Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: MIT', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], ) <commit_msg>Upgrade the version to force reinstall by wheels<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='django-remote-forms', version='0.0.2', description='A platform independent form serializer for Django.', author='WiserTogether Tech Team', author_email='tech@wisertogether.com', url='http://github.com/wisertoghether/django-remote-forms/', long_description=open('README.md', 'r').read(), packages=[ 'django_remote_forms', ], package_data={ }, zip_safe=False, requires=[ ], install_requires=[ ], classifiers=[ 'Development Status :: Pre Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: MIT', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='django-remote-forms', version='0.0.1', description='A platform independent form serializer for Django.', author='WiserTogether Tech Team', author_email='tech@wisertogether.com', url='http://github.com/wisertoghether/django-remote-forms/', long_description=open('README.md', 'r').read(), packages=[ 'django_remote_forms', ], package_data={ }, zip_safe=False, requires=[ ], install_requires=[ ], classifiers=[ 'Development Status :: Pre Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: MIT', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], ) Upgrade the version to force reinstall by wheels#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='django-remote-forms', version='0.0.2', description='A platform independent form serializer for Django.', author='WiserTogether Tech Team', author_email='tech@wisertogether.com', url='http://github.com/wisertoghether/django-remote-forms/', long_description=open('README.md', 'r').read(), packages=[ 'django_remote_forms', ], package_data={ }, zip_safe=False, requires=[ ], install_requires=[ ], classifiers=[ 'Development Status :: Pre Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: MIT', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='django-remote-forms', version='0.0.1', description='A platform independent form serializer for Django.', author='WiserTogether Tech Team', author_email='tech@wisertogether.com', url='http://github.com/wisertoghether/django-remote-forms/', long_description=open('README.md', 'r').read(), packages=[ 'django_remote_forms', ], package_data={ }, zip_safe=False, requires=[ ], install_requires=[ ], classifiers=[ 'Development Status :: Pre Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: MIT', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], ) <commit_msg>Upgrade the version to force reinstall by wheels<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='django-remote-forms', version='0.0.2', description='A platform independent form serializer for Django.', author='WiserTogether Tech Team', author_email='tech@wisertogether.com', url='http://github.com/wisertoghether/django-remote-forms/', long_description=open('README.md', 'r').read(), packages=[ 'django_remote_forms', ], package_data={ }, zip_safe=False, requires=[ ], install_requires=[ ], classifiers=[ 'Development Status :: Pre Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: MIT', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
391d03c332633f26da92769d442913f76a9e2f50
setup.py
setup.py
from setuptools import find_packages, setup version = '2.3' setup(name='op_robot_tests', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'robotframework', 'robotframework-selenium2library', 'robotframework-debuglibrary', 'robotframework-selenium2screenshots', 'Pillow', 'iso8601', 'PyYAML', 'munch', 'fake-factory', 'dpath', 'jsonpath-rw', 'dateutils', 'pytz', 'parse', 'chromedriver', 'barbecue', 'haversine' ], entry_points={ 'console_scripts': [ 'openprocurement_tests = op_robot_tests.runner:runner', ], } )
from setuptools import find_packages, setup version = '2.3' setup(name='op_robot_tests', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'robotframework', 'robotframework-selenium2library', 'robotframework-debuglibrary', 'robotframework-selenium2screenshots', 'Pillow', 'iso8601', 'PyYAML', 'munch', 'fake-factory', 'dpath', 'jsonpath-rw', 'dateutils', 'pytz', 'parse', 'chromedriver', 'barbecue', 'haversine' ], entry_points={ 'console_scripts': [ 'openprocurement_tests = op_robot_tests.runner:runner', 'op_tests = op_robot_tests.runner:runner', ], } )
Add a short alias for bin/openprocurement_tests
Add a short alias for bin/openprocurement_tests Alias is: bin/op_tests
Python
apache-2.0
kosaniak/robot_tests,openprocurement/robot_tests,mykhaly/robot_tests,selurvedu/robot_tests,cleardevice/robot_tests,VadimShurhal/robot_tests.broker.aps,SlaOne/robot_tests,bubanoid/robot_tests,Rzaporozhets/robot_tests,Leits/robot_tests
from setuptools import find_packages, setup version = '2.3' setup(name='op_robot_tests', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'robotframework', 'robotframework-selenium2library', 'robotframework-debuglibrary', 'robotframework-selenium2screenshots', 'Pillow', 'iso8601', 'PyYAML', 'munch', 'fake-factory', 'dpath', 'jsonpath-rw', 'dateutils', 'pytz', 'parse', 'chromedriver', 'barbecue', 'haversine' ], entry_points={ 'console_scripts': [ 'openprocurement_tests = op_robot_tests.runner:runner', ], } ) Add a short alias for bin/openprocurement_tests Alias is: bin/op_tests
from setuptools import find_packages, setup version = '2.3' setup(name='op_robot_tests', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'robotframework', 'robotframework-selenium2library', 'robotframework-debuglibrary', 'robotframework-selenium2screenshots', 'Pillow', 'iso8601', 'PyYAML', 'munch', 'fake-factory', 'dpath', 'jsonpath-rw', 'dateutils', 'pytz', 'parse', 'chromedriver', 'barbecue', 'haversine' ], entry_points={ 'console_scripts': [ 'openprocurement_tests = op_robot_tests.runner:runner', 'op_tests = op_robot_tests.runner:runner', ], } )
<commit_before>from setuptools import find_packages, setup version = '2.3' setup(name='op_robot_tests', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'robotframework', 'robotframework-selenium2library', 'robotframework-debuglibrary', 'robotframework-selenium2screenshots', 'Pillow', 'iso8601', 'PyYAML', 'munch', 'fake-factory', 'dpath', 'jsonpath-rw', 'dateutils', 'pytz', 'parse', 'chromedriver', 'barbecue', 'haversine' ], entry_points={ 'console_scripts': [ 'openprocurement_tests = op_robot_tests.runner:runner', ], } ) <commit_msg>Add a short alias for bin/openprocurement_tests Alias is: bin/op_tests<commit_after>
from setuptools import find_packages, setup version = '2.3' setup(name='op_robot_tests', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'robotframework', 'robotframework-selenium2library', 'robotframework-debuglibrary', 'robotframework-selenium2screenshots', 'Pillow', 'iso8601', 'PyYAML', 'munch', 'fake-factory', 'dpath', 'jsonpath-rw', 'dateutils', 'pytz', 'parse', 'chromedriver', 'barbecue', 'haversine' ], entry_points={ 'console_scripts': [ 'openprocurement_tests = op_robot_tests.runner:runner', 'op_tests = op_robot_tests.runner:runner', ], } )
from setuptools import find_packages, setup version = '2.3' setup(name='op_robot_tests', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'robotframework', 'robotframework-selenium2library', 'robotframework-debuglibrary', 'robotframework-selenium2screenshots', 'Pillow', 'iso8601', 'PyYAML', 'munch', 'fake-factory', 'dpath', 'jsonpath-rw', 'dateutils', 'pytz', 'parse', 'chromedriver', 'barbecue', 'haversine' ], entry_points={ 'console_scripts': [ 'openprocurement_tests = op_robot_tests.runner:runner', ], } ) Add a short alias for bin/openprocurement_tests Alias is: bin/op_testsfrom setuptools import find_packages, setup version = '2.3' setup(name='op_robot_tests', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'robotframework', 'robotframework-selenium2library', 'robotframework-debuglibrary', 'robotframework-selenium2screenshots', 'Pillow', 'iso8601', 'PyYAML', 'munch', 'fake-factory', 'dpath', 'jsonpath-rw', 'dateutils', 'pytz', 'parse', 'chromedriver', 'barbecue', 'haversine' ], entry_points={ 'console_scripts': [ 'openprocurement_tests = op_robot_tests.runner:runner', 'op_tests = op_robot_tests.runner:runner', ], } )
<commit_before>from setuptools import find_packages, setup version = '2.3' setup(name='op_robot_tests', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'robotframework', 'robotframework-selenium2library', 'robotframework-debuglibrary', 'robotframework-selenium2screenshots', 'Pillow', 'iso8601', 'PyYAML', 'munch', 'fake-factory', 'dpath', 'jsonpath-rw', 'dateutils', 'pytz', 'parse', 'chromedriver', 'barbecue', 'haversine' ], entry_points={ 'console_scripts': [ 'openprocurement_tests = op_robot_tests.runner:runner', ], } ) <commit_msg>Add a short alias for bin/openprocurement_tests Alias is: bin/op_tests<commit_after>from setuptools import find_packages, setup version = '2.3' setup(name='op_robot_tests', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'robotframework', 'robotframework-selenium2library', 'robotframework-debuglibrary', 'robotframework-selenium2screenshots', 'Pillow', 'iso8601', 'PyYAML', 'munch', 'fake-factory', 'dpath', 'jsonpath-rw', 'dateutils', 'pytz', 'parse', 'chromedriver', 'barbecue', 'haversine' ], entry_points={ 'console_scripts': [ 'openprocurement_tests = op_robot_tests.runner:runner', 'op_tests = op_robot_tests.runner:runner', ], } )
4b2a68638a9045d3a15219d41c7d9981d29e601a
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup with open('README.rst') as file: long_description = file.read() setup(name='parmap', version='1.2.1', description=('map and starmap implementations passing additional', 'arguments and parallelizing if possible'), long_description=long_description, author='Sergio Oller', license='APACHE-2.0', author_email='sergioller@gmail.com', url='https://github.com/zeehio/parmap', py_modules=['parmap'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], )
#!/usr/bin/env python from distutils.core import setup with open('README.rst') as file: long_description = file.read() setup(name='parmap', version='1.2.1', description=('map and starmap implementations passing additional ' 'arguments and parallelizing if possible'), long_description=long_description, author='Sergio Oller', license='APACHE-2.0', author_email='sergioller@gmail.com', url='https://github.com/zeehio/parmap', py_modules=['parmap'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], )
Make description a string, not a tuple.
Make description a string, not a tuple. Fixes #1
Python
apache-2.0
zeehio/parmap
#!/usr/bin/env python from distutils.core import setup with open('README.rst') as file: long_description = file.read() setup(name='parmap', version='1.2.1', description=('map and starmap implementations passing additional', 'arguments and parallelizing if possible'), long_description=long_description, author='Sergio Oller', license='APACHE-2.0', author_email='sergioller@gmail.com', url='https://github.com/zeehio/parmap', py_modules=['parmap'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], ) Make description a string, not a tuple. Fixes #1
#!/usr/bin/env python from distutils.core import setup with open('README.rst') as file: long_description = file.read() setup(name='parmap', version='1.2.1', description=('map and starmap implementations passing additional ' 'arguments and parallelizing if possible'), long_description=long_description, author='Sergio Oller', license='APACHE-2.0', author_email='sergioller@gmail.com', url='https://github.com/zeehio/parmap', py_modules=['parmap'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], )
<commit_before>#!/usr/bin/env python from distutils.core import setup with open('README.rst') as file: long_description = file.read() setup(name='parmap', version='1.2.1', description=('map and starmap implementations passing additional', 'arguments and parallelizing if possible'), long_description=long_description, author='Sergio Oller', license='APACHE-2.0', author_email='sergioller@gmail.com', url='https://github.com/zeehio/parmap', py_modules=['parmap'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], ) <commit_msg>Make description a string, not a tuple. Fixes #1<commit_after>
#!/usr/bin/env python from distutils.core import setup with open('README.rst') as file: long_description = file.read() setup(name='parmap', version='1.2.1', description=('map and starmap implementations passing additional ' 'arguments and parallelizing if possible'), long_description=long_description, author='Sergio Oller', license='APACHE-2.0', author_email='sergioller@gmail.com', url='https://github.com/zeehio/parmap', py_modules=['parmap'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], )
#!/usr/bin/env python from distutils.core import setup with open('README.rst') as file: long_description = file.read() setup(name='parmap', version='1.2.1', description=('map and starmap implementations passing additional', 'arguments and parallelizing if possible'), long_description=long_description, author='Sergio Oller', license='APACHE-2.0', author_email='sergioller@gmail.com', url='https://github.com/zeehio/parmap', py_modules=['parmap'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], ) Make description a string, not a tuple. Fixes #1#!/usr/bin/env python from distutils.core import setup with open('README.rst') as file: long_description = file.read() setup(name='parmap', version='1.2.1', description=('map and starmap implementations passing additional ' 'arguments and parallelizing if possible'), long_description=long_description, author='Sergio Oller', license='APACHE-2.0', author_email='sergioller@gmail.com', url='https://github.com/zeehio/parmap', py_modules=['parmap'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], )
<commit_before>#!/usr/bin/env python from distutils.core import setup with open('README.rst') as file: long_description = file.read() setup(name='parmap', version='1.2.1', description=('map and starmap implementations passing additional', 'arguments and parallelizing if possible'), long_description=long_description, author='Sergio Oller', license='APACHE-2.0', author_email='sergioller@gmail.com', url='https://github.com/zeehio/parmap', py_modules=['parmap'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], ) <commit_msg>Make description a string, not a tuple. Fixes #1<commit_after>#!/usr/bin/env python from distutils.core import setup with open('README.rst') as file: long_description = file.read() setup(name='parmap', version='1.2.1', description=('map and starmap implementations passing additional ' 'arguments and parallelizing if possible'), long_description=long_description, author='Sergio Oller', license='APACHE-2.0', author_email='sergioller@gmail.com', url='https://github.com/zeehio/parmap', py_modules=['parmap'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], )
439b8eea574a9bfa154cbce069367d26faa94368
setup.py
setup.py
from setuptools import find_packages, setup version = '0.1.0' setup( name='django-user-deletion', packages=find_packages(), include_package_data=True, version=version, license='BSD', description='Management commands to notify and delete inactive django users', classifiers=( 'Development Status :: 1 - Planning', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ), author='Incuna Ltd', author_email='admin@incuna.com', url='https://github.com/incuna/django-user-deletion', )
from setuptools import find_packages, setup version = '0.1.0' setup( name='django-user-deletion', packages=find_packages(), include_package_data=True, version=version, license='BSD', description='Management commands to notify and delete inactive django users', classifiers=[ 'Development Status :: 1 - Planning', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], author='Incuna Ltd', author_email='admin@incuna.com', url='https://github.com/incuna/django-user-deletion', )
Use a list for classifiers
Use a list for classifiers
Python
bsd-2-clause
incuna/django-user-deletion
from setuptools import find_packages, setup version = '0.1.0' setup( name='django-user-deletion', packages=find_packages(), include_package_data=True, version=version, license='BSD', description='Management commands to notify and delete inactive django users', classifiers=( 'Development Status :: 1 - Planning', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ), author='Incuna Ltd', author_email='admin@incuna.com', url='https://github.com/incuna/django-user-deletion', ) Use a list for classifiers
from setuptools import find_packages, setup version = '0.1.0' setup( name='django-user-deletion', packages=find_packages(), include_package_data=True, version=version, license='BSD', description='Management commands to notify and delete inactive django users', classifiers=[ 'Development Status :: 1 - Planning', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], author='Incuna Ltd', author_email='admin@incuna.com', url='https://github.com/incuna/django-user-deletion', )
<commit_before>from setuptools import find_packages, setup version = '0.1.0' setup( name='django-user-deletion', packages=find_packages(), include_package_data=True, version=version, license='BSD', description='Management commands to notify and delete inactive django users', classifiers=( 'Development Status :: 1 - Planning', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ), author='Incuna Ltd', author_email='admin@incuna.com', url='https://github.com/incuna/django-user-deletion', ) <commit_msg>Use a list for classifiers<commit_after>
from setuptools import find_packages, setup version = '0.1.0' setup( name='django-user-deletion', packages=find_packages(), include_package_data=True, version=version, license='BSD', description='Management commands to notify and delete inactive django users', classifiers=[ 'Development Status :: 1 - Planning', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], author='Incuna Ltd', author_email='admin@incuna.com', url='https://github.com/incuna/django-user-deletion', )
from setuptools import find_packages, setup version = '0.1.0' setup( name='django-user-deletion', packages=find_packages(), include_package_data=True, version=version, license='BSD', description='Management commands to notify and delete inactive django users', classifiers=( 'Development Status :: 1 - Planning', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ), author='Incuna Ltd', author_email='admin@incuna.com', url='https://github.com/incuna/django-user-deletion', ) Use a list for classifiersfrom setuptools import find_packages, setup version = '0.1.0' setup( name='django-user-deletion', packages=find_packages(), include_package_data=True, version=version, license='BSD', description='Management commands to notify and delete inactive django users', classifiers=[ 'Development Status :: 1 - Planning', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], author='Incuna Ltd', author_email='admin@incuna.com', url='https://github.com/incuna/django-user-deletion', )
<commit_before>from setuptools import find_packages, setup version = '0.1.0' setup( name='django-user-deletion', packages=find_packages(), include_package_data=True, version=version, license='BSD', description='Management commands to notify and delete inactive django users', classifiers=( 'Development Status :: 1 - Planning', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ), author='Incuna Ltd', author_email='admin@incuna.com', url='https://github.com/incuna/django-user-deletion', ) <commit_msg>Use a list for classifiers<commit_after>from setuptools import find_packages, setup version = '0.1.0' setup( name='django-user-deletion', packages=find_packages(), include_package_data=True, version=version, license='BSD', description='Management commands to notify and delete inactive django users', classifiers=[ 'Development Status :: 1 - Planning', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], author='Incuna Ltd', author_email='admin@incuna.com', url='https://github.com/incuna/django-user-deletion', )
26d64b98fab7fa90a6504e556a0a41892e99f8a8
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='sysenv', version='0.1.0', description='Simple handling of system environment variables for application deployment.', long_description=readme + '\n\n' + history, author='Ben Lopatin', author_email='ben@wellfire.co', url='https://gitthub.com/bennylope/sysenv', packages=[ 'sysenv', ], package_dir={'sysenv': 'sysenv'}, include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='sysenv', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', )
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='sysenv', version='0.1.0', description='Simple handling of system environment variables for application deployment.', long_description=readme + '\n\n' + history, author='Ben Lopatin', author_email='ben@wellfire.co', url='https://github.com/bennylope/sysenv', packages=[ 'sysenv', ], package_dir={'sysenv': 'sysenv'}, include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='sysenv', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', )
Fix a small typo in the github url
Fix a small typo in the github url Signed-off-by: Ben Lopatin <91803bfd2e5cab57e71a67949d71dc9d68ed4677@wellfireinteractive.com>
Python
bsd-3-clause
bennylope/sysenv,bennylope/sysenv
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='sysenv', version='0.1.0', description='Simple handling of system environment variables for application deployment.', long_description=readme + '\n\n' + history, author='Ben Lopatin', author_email='ben@wellfire.co', url='https://gitthub.com/bennylope/sysenv', packages=[ 'sysenv', ], package_dir={'sysenv': 'sysenv'}, include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='sysenv', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', ) Fix a small typo in the github url Signed-off-by: Ben Lopatin <91803bfd2e5cab57e71a67949d71dc9d68ed4677@wellfireinteractive.com>
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='sysenv', version='0.1.0', description='Simple handling of system environment variables for application deployment.', long_description=readme + '\n\n' + history, author='Ben Lopatin', author_email='ben@wellfire.co', url='https://github.com/bennylope/sysenv', packages=[ 'sysenv', ], package_dir={'sysenv': 'sysenv'}, include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='sysenv', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', )
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='sysenv', version='0.1.0', description='Simple handling of system environment variables for application deployment.', long_description=readme + '\n\n' + history, author='Ben Lopatin', author_email='ben@wellfire.co', url='https://gitthub.com/bennylope/sysenv', packages=[ 'sysenv', ], package_dir={'sysenv': 'sysenv'}, include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='sysenv', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', ) <commit_msg>Fix a small typo in the github url Signed-off-by: Ben Lopatin <91803bfd2e5cab57e71a67949d71dc9d68ed4677@wellfireinteractive.com><commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='sysenv', version='0.1.0', description='Simple handling of system environment variables for application deployment.', long_description=readme + '\n\n' + history, author='Ben Lopatin', author_email='ben@wellfire.co', url='https://github.com/bennylope/sysenv', packages=[ 'sysenv', ], package_dir={'sysenv': 'sysenv'}, include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='sysenv', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', )
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='sysenv', version='0.1.0', description='Simple handling of system environment variables for application deployment.', long_description=readme + '\n\n' + history, author='Ben Lopatin', author_email='ben@wellfire.co', url='https://gitthub.com/bennylope/sysenv', packages=[ 'sysenv', ], package_dir={'sysenv': 'sysenv'}, include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='sysenv', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', ) Fix a small typo in the github url Signed-off-by: Ben Lopatin <91803bfd2e5cab57e71a67949d71dc9d68ed4677@wellfireinteractive.com>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='sysenv', version='0.1.0', description='Simple handling of system environment variables for application deployment.', long_description=readme + '\n\n' + history, author='Ben Lopatin', author_email='ben@wellfire.co', url='https://github.com/bennylope/sysenv', packages=[ 'sysenv', ], package_dir={'sysenv': 'sysenv'}, include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='sysenv', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', )
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='sysenv', version='0.1.0', description='Simple handling of system environment variables for application deployment.', long_description=readme + '\n\n' + history, author='Ben Lopatin', author_email='ben@wellfire.co', url='https://gitthub.com/bennylope/sysenv', packages=[ 'sysenv', ], package_dir={'sysenv': 'sysenv'}, include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='sysenv', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', ) <commit_msg>Fix a small typo in the github url Signed-off-by: Ben Lopatin <91803bfd2e5cab57e71a67949d71dc9d68ed4677@wellfireinteractive.com><commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='sysenv', version='0.1.0', description='Simple handling of system environment variables for application deployment.', long_description=readme + '\n\n' + history, author='Ben Lopatin', author_email='ben@wellfire.co', url='https://github.com/bennylope/sysenv', packages=[ 'sysenv', ], package_dir={'sysenv': 'sysenv'}, include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='sysenv', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', )
588060454795c92f76dc623bb03b9ef17b585f81
setup.py
setup.py
from setuptools import setup, find_packages setup( name='zeit.content.portraitbox', version='1.22.10dev', author='gocept', author_email='mail@gocept.com', url='https://svn.gocept.com/repos/gocept-int/zeit.cms', description="ZEIT portraitbox", packages=find_packages('src'), package_dir = {'': 'src'}, include_package_data = True, zip_safe=False, license='gocept proprietary', namespace_packages = ['zeit', 'zeit.content'], install_requires=[ 'gocept.form', 'mock', 'setuptools', 'zeit.cms>1.40.3', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], )
from setuptools import setup, find_packages setup( name='zeit.content.portraitbox', version='1.22.10dev', author='gocept', author_email='mail@gocept.com', url='https://svn.gocept.com/repos/gocept-int/zeit.cms', description="ZEIT portraitbox", packages=find_packages('src'), package_dir = {'': 'src'}, include_package_data = True, zip_safe=False, license='gocept proprietary', namespace_packages = ['zeit', 'zeit.content'], install_requires=[ 'gocept.form', 'mock', 'setuptools', 'zeit.cms>=1.53.0.dev', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], )
Declare required version of zeit.cms
Declare required version of zeit.cms
Python
bsd-3-clause
ZeitOnline/zeit.content.portraitbox
from setuptools import setup, find_packages setup( name='zeit.content.portraitbox', version='1.22.10dev', author='gocept', author_email='mail@gocept.com', url='https://svn.gocept.com/repos/gocept-int/zeit.cms', description="ZEIT portraitbox", packages=find_packages('src'), package_dir = {'': 'src'}, include_package_data = True, zip_safe=False, license='gocept proprietary', namespace_packages = ['zeit', 'zeit.content'], install_requires=[ 'gocept.form', 'mock', 'setuptools', 'zeit.cms>1.40.3', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], ) Declare required version of zeit.cms
from setuptools import setup, find_packages setup( name='zeit.content.portraitbox', version='1.22.10dev', author='gocept', author_email='mail@gocept.com', url='https://svn.gocept.com/repos/gocept-int/zeit.cms', description="ZEIT portraitbox", packages=find_packages('src'), package_dir = {'': 'src'}, include_package_data = True, zip_safe=False, license='gocept proprietary', namespace_packages = ['zeit', 'zeit.content'], install_requires=[ 'gocept.form', 'mock', 'setuptools', 'zeit.cms>=1.53.0.dev', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], )
<commit_before>from setuptools import setup, find_packages setup( name='zeit.content.portraitbox', version='1.22.10dev', author='gocept', author_email='mail@gocept.com', url='https://svn.gocept.com/repos/gocept-int/zeit.cms', description="ZEIT portraitbox", packages=find_packages('src'), package_dir = {'': 'src'}, include_package_data = True, zip_safe=False, license='gocept proprietary', namespace_packages = ['zeit', 'zeit.content'], install_requires=[ 'gocept.form', 'mock', 'setuptools', 'zeit.cms>1.40.3', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], ) <commit_msg>Declare required version of zeit.cms<commit_after>
from setuptools import setup, find_packages setup( name='zeit.content.portraitbox', version='1.22.10dev', author='gocept', author_email='mail@gocept.com', url='https://svn.gocept.com/repos/gocept-int/zeit.cms', description="ZEIT portraitbox", packages=find_packages('src'), package_dir = {'': 'src'}, include_package_data = True, zip_safe=False, license='gocept proprietary', namespace_packages = ['zeit', 'zeit.content'], install_requires=[ 'gocept.form', 'mock', 'setuptools', 'zeit.cms>=1.53.0.dev', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], )
from setuptools import setup, find_packages setup( name='zeit.content.portraitbox', version='1.22.10dev', author='gocept', author_email='mail@gocept.com', url='https://svn.gocept.com/repos/gocept-int/zeit.cms', description="ZEIT portraitbox", packages=find_packages('src'), package_dir = {'': 'src'}, include_package_data = True, zip_safe=False, license='gocept proprietary', namespace_packages = ['zeit', 'zeit.content'], install_requires=[ 'gocept.form', 'mock', 'setuptools', 'zeit.cms>1.40.3', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], ) Declare required version of zeit.cmsfrom setuptools import setup, find_packages setup( name='zeit.content.portraitbox', version='1.22.10dev', author='gocept', author_email='mail@gocept.com', url='https://svn.gocept.com/repos/gocept-int/zeit.cms', description="ZEIT portraitbox", packages=find_packages('src'), package_dir = {'': 'src'}, include_package_data = True, zip_safe=False, license='gocept proprietary', namespace_packages = ['zeit', 'zeit.content'], install_requires=[ 'gocept.form', 'mock', 'setuptools', 'zeit.cms>=1.53.0.dev', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], )
<commit_before>from setuptools import setup, find_packages setup( name='zeit.content.portraitbox', version='1.22.10dev', author='gocept', author_email='mail@gocept.com', url='https://svn.gocept.com/repos/gocept-int/zeit.cms', description="ZEIT portraitbox", packages=find_packages('src'), package_dir = {'': 'src'}, include_package_data = True, zip_safe=False, license='gocept proprietary', namespace_packages = ['zeit', 'zeit.content'], install_requires=[ 'gocept.form', 'mock', 'setuptools', 'zeit.cms>1.40.3', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], ) <commit_msg>Declare required version of zeit.cms<commit_after>from setuptools import setup, find_packages setup( name='zeit.content.portraitbox', version='1.22.10dev', author='gocept', author_email='mail@gocept.com', url='https://svn.gocept.com/repos/gocept-int/zeit.cms', description="ZEIT portraitbox", packages=find_packages('src'), package_dir = {'': 'src'}, include_package_data = True, zip_safe=False, license='gocept proprietary', namespace_packages = ['zeit', 'zeit.content'], install_requires=[ 'gocept.form', 'mock', 'setuptools', 'zeit.cms>=1.53.0.dev', 'zeit.wysiwyg', 'zope.app.appsetup', 'zope.app.testing', 'zope.component', 'zope.formlib', 'zope.interface', 'zope.publisher', 'zope.security', 'zope.testing', ], )
d3d084f3030946217dd0c29a452ff002768cf381
setup.py
setup.py
import setuptools with open("README.md", "r") as fin: long_description = fin.read() setuptools.setup( name="geneagrapher", version="1.0", author="David Alber", author_email="alber.david@gmail.com", description="Mathematical genealogy grapher.", entry_points={ 'console_scripts': ['ggrapher=geneagrapher.geneagrapher:ggrapher'] }, install_requires=['beautifulsoup4==4.6.3', 'lxml==4.2.5'], long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/davidalber/geneagrapher", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
import re import setuptools with open("README.md", "r") as fin: long_description = fin.read() long_description = re.sub( "^(!\[.*\]\()(.*\))", lambda m: m.group(1) + "https://github.com/davidalber/geneagrapher/raw/master/" + m.group(2), long_description, flags=re.MULTILINE ) setuptools.setup( name="geneagrapher", version="1.0", author="David Alber", author_email="alber.david@gmail.com", description="Mathematical genealogy grapher.", entry_points={ 'console_scripts': ['ggrapher=geneagrapher.geneagrapher:ggrapher'] }, install_requires=['beautifulsoup4==4.6.3', 'lxml==4.2.5'], long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/davidalber/geneagrapher", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
Replace relative links with absolute links
Replace relative links with absolute links
Python
mit
davidalber/Geneagrapher,davidalber/Geneagrapher
import setuptools with open("README.md", "r") as fin: long_description = fin.read() setuptools.setup( name="geneagrapher", version="1.0", author="David Alber", author_email="alber.david@gmail.com", description="Mathematical genealogy grapher.", entry_points={ 'console_scripts': ['ggrapher=geneagrapher.geneagrapher:ggrapher'] }, install_requires=['beautifulsoup4==4.6.3', 'lxml==4.2.5'], long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/davidalber/geneagrapher", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], ) Replace relative links with absolute links
import re import setuptools with open("README.md", "r") as fin: long_description = fin.read() long_description = re.sub( "^(!\[.*\]\()(.*\))", lambda m: m.group(1) + "https://github.com/davidalber/geneagrapher/raw/master/" + m.group(2), long_description, flags=re.MULTILINE ) setuptools.setup( name="geneagrapher", version="1.0", author="David Alber", author_email="alber.david@gmail.com", description="Mathematical genealogy grapher.", entry_points={ 'console_scripts': ['ggrapher=geneagrapher.geneagrapher:ggrapher'] }, install_requires=['beautifulsoup4==4.6.3', 'lxml==4.2.5'], long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/davidalber/geneagrapher", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
<commit_before>import setuptools with open("README.md", "r") as fin: long_description = fin.read() setuptools.setup( name="geneagrapher", version="1.0", author="David Alber", author_email="alber.david@gmail.com", description="Mathematical genealogy grapher.", entry_points={ 'console_scripts': ['ggrapher=geneagrapher.geneagrapher:ggrapher'] }, install_requires=['beautifulsoup4==4.6.3', 'lxml==4.2.5'], long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/davidalber/geneagrapher", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], ) <commit_msg>Replace relative links with absolute links<commit_after>
import re import setuptools with open("README.md", "r") as fin: long_description = fin.read() long_description = re.sub( "^(!\[.*\]\()(.*\))", lambda m: m.group(1) + "https://github.com/davidalber/geneagrapher/raw/master/" + m.group(2), long_description, flags=re.MULTILINE ) setuptools.setup( name="geneagrapher", version="1.0", author="David Alber", author_email="alber.david@gmail.com", description="Mathematical genealogy grapher.", entry_points={ 'console_scripts': ['ggrapher=geneagrapher.geneagrapher:ggrapher'] }, install_requires=['beautifulsoup4==4.6.3', 'lxml==4.2.5'], long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/davidalber/geneagrapher", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
import setuptools with open("README.md", "r") as fin: long_description = fin.read() setuptools.setup( name="geneagrapher", version="1.0", author="David Alber", author_email="alber.david@gmail.com", description="Mathematical genealogy grapher.", entry_points={ 'console_scripts': ['ggrapher=geneagrapher.geneagrapher:ggrapher'] }, install_requires=['beautifulsoup4==4.6.3', 'lxml==4.2.5'], long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/davidalber/geneagrapher", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], ) Replace relative links with absolute linksimport re import setuptools with open("README.md", "r") as fin: long_description = fin.read() long_description = re.sub( "^(!\[.*\]\()(.*\))", lambda m: m.group(1) + "https://github.com/davidalber/geneagrapher/raw/master/" + m.group(2), long_description, flags=re.MULTILINE ) setuptools.setup( name="geneagrapher", version="1.0", author="David Alber", author_email="alber.david@gmail.com", description="Mathematical genealogy grapher.", entry_points={ 'console_scripts': ['ggrapher=geneagrapher.geneagrapher:ggrapher'] }, install_requires=['beautifulsoup4==4.6.3', 'lxml==4.2.5'], long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/davidalber/geneagrapher", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
<commit_before>import setuptools with open("README.md", "r") as fin: long_description = fin.read() setuptools.setup( name="geneagrapher", version="1.0", author="David Alber", author_email="alber.david@gmail.com", description="Mathematical genealogy grapher.", entry_points={ 'console_scripts': ['ggrapher=geneagrapher.geneagrapher:ggrapher'] }, install_requires=['beautifulsoup4==4.6.3', 'lxml==4.2.5'], long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/davidalber/geneagrapher", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], ) <commit_msg>Replace relative links with absolute links<commit_after>import re import setuptools with open("README.md", "r") as fin: long_description = fin.read() long_description = re.sub( "^(!\[.*\]\()(.*\))", lambda m: m.group(1) + "https://github.com/davidalber/geneagrapher/raw/master/" + m.group(2), long_description, flags=re.MULTILINE ) setuptools.setup( name="geneagrapher", version="1.0", author="David Alber", author_email="alber.david@gmail.com", description="Mathematical genealogy grapher.", entry_points={ 'console_scripts': ['ggrapher=geneagrapher.geneagrapher:ggrapher'] }, install_requires=['beautifulsoup4==4.6.3', 'lxml==4.2.5'], long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/davidalber/geneagrapher", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 2.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
4d246e9e08f03f1ca77bc7d8aa78d74f21d9fbfb
setup.py
setup.py
import os from setuptools import setup, find_packages version = __import__('aws_status').__version__ def read(path): """Return the content of a file.""" with open(path, 'r') as f: return f.read() setup( name='aws-status', version=version, description='Wraps AWS status informations obtained via the status page.', long_description=(read('README.rst')), url='http://github.com/jbbarth/aws-status', license='MIT', author='Jean-Baptiste Barth', author_email='jeanbaptiste.barth@gmail.com', packages=find_packages(exclude=['tests*']), scripts=[ 'bin/aws-status-list', ], install_requires=[ 'feedparser>=5.1.3', ], include_package_data=True, #see http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: System :: Monitoring', ], )
import os from setuptools import setup, find_packages version = __import__('aws_status').__version__ def read(path): """Return the content of a file.""" with open(path, 'r') as f: return f.read() setup( name='aws-status', version=version, description='Wraps AWS status informations obtained via the status page.', long_description=(read('README.rst')), url='http://github.com/jbbarth/aws-status', license='MIT', author='Jean-Baptiste Barth', author_email='jeanbaptiste.barth@gmail.com', packages=find_packages(exclude=['tests*']), scripts=[ 'bin/aws-status-check', 'bin/aws-status-list', ], install_requires=[ 'feedparser>=5.1.3', ], include_package_data=True, #see http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: System :: Monitoring', ], )
Add aws-status-check to declared binaries
Add aws-status-check to declared binaries
Python
mit
jbbarth/aws-status,jbbarth/aws-status
import os from setuptools import setup, find_packages version = __import__('aws_status').__version__ def read(path): """Return the content of a file.""" with open(path, 'r') as f: return f.read() setup( name='aws-status', version=version, description='Wraps AWS status informations obtained via the status page.', long_description=(read('README.rst')), url='http://github.com/jbbarth/aws-status', license='MIT', author='Jean-Baptiste Barth', author_email='jeanbaptiste.barth@gmail.com', packages=find_packages(exclude=['tests*']), scripts=[ 'bin/aws-status-list', ], install_requires=[ 'feedparser>=5.1.3', ], include_package_data=True, #see http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: System :: Monitoring', ], ) Add aws-status-check to declared binaries
import os from setuptools import setup, find_packages version = __import__('aws_status').__version__ def read(path): """Return the content of a file.""" with open(path, 'r') as f: return f.read() setup( name='aws-status', version=version, description='Wraps AWS status informations obtained via the status page.', long_description=(read('README.rst')), url='http://github.com/jbbarth/aws-status', license='MIT', author='Jean-Baptiste Barth', author_email='jeanbaptiste.barth@gmail.com', packages=find_packages(exclude=['tests*']), scripts=[ 'bin/aws-status-check', 'bin/aws-status-list', ], install_requires=[ 'feedparser>=5.1.3', ], include_package_data=True, #see http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: System :: Monitoring', ], )
<commit_before>import os from setuptools import setup, find_packages version = __import__('aws_status').__version__ def read(path): """Return the content of a file.""" with open(path, 'r') as f: return f.read() setup( name='aws-status', version=version, description='Wraps AWS status informations obtained via the status page.', long_description=(read('README.rst')), url='http://github.com/jbbarth/aws-status', license='MIT', author='Jean-Baptiste Barth', author_email='jeanbaptiste.barth@gmail.com', packages=find_packages(exclude=['tests*']), scripts=[ 'bin/aws-status-list', ], install_requires=[ 'feedparser>=5.1.3', ], include_package_data=True, #see http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: System :: Monitoring', ], ) <commit_msg>Add aws-status-check to declared binaries<commit_after>
import os from setuptools import setup, find_packages version = __import__('aws_status').__version__ def read(path): """Return the content of a file.""" with open(path, 'r') as f: return f.read() setup( name='aws-status', version=version, description='Wraps AWS status informations obtained via the status page.', long_description=(read('README.rst')), url='http://github.com/jbbarth/aws-status', license='MIT', author='Jean-Baptiste Barth', author_email='jeanbaptiste.barth@gmail.com', packages=find_packages(exclude=['tests*']), scripts=[ 'bin/aws-status-check', 'bin/aws-status-list', ], install_requires=[ 'feedparser>=5.1.3', ], include_package_data=True, #see http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: System :: Monitoring', ], )
import os from setuptools import setup, find_packages version = __import__('aws_status').__version__ def read(path): """Return the content of a file.""" with open(path, 'r') as f: return f.read() setup( name='aws-status', version=version, description='Wraps AWS status informations obtained via the status page.', long_description=(read('README.rst')), url='http://github.com/jbbarth/aws-status', license='MIT', author='Jean-Baptiste Barth', author_email='jeanbaptiste.barth@gmail.com', packages=find_packages(exclude=['tests*']), scripts=[ 'bin/aws-status-list', ], install_requires=[ 'feedparser>=5.1.3', ], include_package_data=True, #see http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: System :: Monitoring', ], ) Add aws-status-check to declared binariesimport os from setuptools import setup, find_packages version = __import__('aws_status').__version__ def read(path): """Return the content of a file.""" with open(path, 'r') as f: return f.read() setup( name='aws-status', version=version, description='Wraps AWS status informations obtained via the status page.', long_description=(read('README.rst')), url='http://github.com/jbbarth/aws-status', license='MIT', author='Jean-Baptiste Barth', author_email='jeanbaptiste.barth@gmail.com', packages=find_packages(exclude=['tests*']), scripts=[ 'bin/aws-status-check', 'bin/aws-status-list', ], install_requires=[ 'feedparser>=5.1.3', ], include_package_data=True, #see http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: System :: Monitoring', ], )
<commit_before>import os from setuptools import setup, find_packages version = __import__('aws_status').__version__ def read(path): """Return the content of a file.""" with open(path, 'r') as f: return f.read() setup( name='aws-status', version=version, description='Wraps AWS status informations obtained via the status page.', long_description=(read('README.rst')), url='http://github.com/jbbarth/aws-status', license='MIT', author='Jean-Baptiste Barth', author_email='jeanbaptiste.barth@gmail.com', packages=find_packages(exclude=['tests*']), scripts=[ 'bin/aws-status-list', ], install_requires=[ 'feedparser>=5.1.3', ], include_package_data=True, #see http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: System :: Monitoring', ], ) <commit_msg>Add aws-status-check to declared binaries<commit_after>import os from setuptools import setup, find_packages version = __import__('aws_status').__version__ def read(path): """Return the content of a file.""" with open(path, 'r') as f: return f.read() setup( name='aws-status', version=version, description='Wraps AWS status informations obtained via the status page.', long_description=(read('README.rst')), url='http://github.com/jbbarth/aws-status', license='MIT', author='Jean-Baptiste Barth', author_email='jeanbaptiste.barth@gmail.com', packages=find_packages(exclude=['tests*']), scripts=[ 'bin/aws-status-check', 'bin/aws-status-list', ], install_requires=[ 'feedparser>=5.1.3', ], include_package_data=True, #see http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: System :: Monitoring', ], )
d06f4466cf9ccb6f88df96798d96df8880a94276
setup.py
setup.py
import os from setuptools import setup, find_packages __version__ = '0.1' HERE = os.path.dirname(__file__) try: long_description = open(os.path.join(HERE, 'README.rst')).read() except: long_description = None setup( name='rubberjack-cli', version=__version__, packages=find_packages(exclude=['test*']), include_package_data=True, zip_safe=True, # metadata for upload to PyPI author='LaterPay GmbH', author_email='django12factor@doismellburning.co.uk', url='https://github.com/laterpay/rubberjack-cli', description='RubberJack manages (AWS) Elastic Beanstalks', long_description=long_description, license='MIT', keywords='aws', install_requires=[ ], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], )
import os from setuptools import setup, find_packages __version__ = '0.1' HERE = os.path.dirname(__file__) try: long_description = open(os.path.join(HERE, 'README.rst')).read() except: long_description = None setup( name='rubberjack-cli', version=__version__, packages=find_packages(exclude=['test*']), include_package_data=True, zip_safe=True, # metadata for upload to PyPI author='LaterPay GmbH', url='https://github.com/laterpay/rubberjack-cli', description='RubberJack manages (AWS) Elastic Beanstalks', long_description=long_description, license='MIT', keywords='aws', install_requires=[ ], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], )
Drop `author_email` - oops, excessive copy-paste
Drop `author_email` - oops, excessive copy-paste
Python
mit
laterpay/rubberjack-cli
import os from setuptools import setup, find_packages __version__ = '0.1' HERE = os.path.dirname(__file__) try: long_description = open(os.path.join(HERE, 'README.rst')).read() except: long_description = None setup( name='rubberjack-cli', version=__version__, packages=find_packages(exclude=['test*']), include_package_data=True, zip_safe=True, # metadata for upload to PyPI author='LaterPay GmbH', author_email='django12factor@doismellburning.co.uk', url='https://github.com/laterpay/rubberjack-cli', description='RubberJack manages (AWS) Elastic Beanstalks', long_description=long_description, license='MIT', keywords='aws', install_requires=[ ], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], ) Drop `author_email` - oops, excessive copy-paste
import os from setuptools import setup, find_packages __version__ = '0.1' HERE = os.path.dirname(__file__) try: long_description = open(os.path.join(HERE, 'README.rst')).read() except: long_description = None setup( name='rubberjack-cli', version=__version__, packages=find_packages(exclude=['test*']), include_package_data=True, zip_safe=True, # metadata for upload to PyPI author='LaterPay GmbH', url='https://github.com/laterpay/rubberjack-cli', description='RubberJack manages (AWS) Elastic Beanstalks', long_description=long_description, license='MIT', keywords='aws', install_requires=[ ], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], )
<commit_before>import os from setuptools import setup, find_packages __version__ = '0.1' HERE = os.path.dirname(__file__) try: long_description = open(os.path.join(HERE, 'README.rst')).read() except: long_description = None setup( name='rubberjack-cli', version=__version__, packages=find_packages(exclude=['test*']), include_package_data=True, zip_safe=True, # metadata for upload to PyPI author='LaterPay GmbH', author_email='django12factor@doismellburning.co.uk', url='https://github.com/laterpay/rubberjack-cli', description='RubberJack manages (AWS) Elastic Beanstalks', long_description=long_description, license='MIT', keywords='aws', install_requires=[ ], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], ) <commit_msg>Drop `author_email` - oops, excessive copy-paste<commit_after>
import os from setuptools import setup, find_packages __version__ = '0.1' HERE = os.path.dirname(__file__) try: long_description = open(os.path.join(HERE, 'README.rst')).read() except: long_description = None setup( name='rubberjack-cli', version=__version__, packages=find_packages(exclude=['test*']), include_package_data=True, zip_safe=True, # metadata for upload to PyPI author='LaterPay GmbH', url='https://github.com/laterpay/rubberjack-cli', description='RubberJack manages (AWS) Elastic Beanstalks', long_description=long_description, license='MIT', keywords='aws', install_requires=[ ], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], )
import os from setuptools import setup, find_packages __version__ = '0.1' HERE = os.path.dirname(__file__) try: long_description = open(os.path.join(HERE, 'README.rst')).read() except: long_description = None setup( name='rubberjack-cli', version=__version__, packages=find_packages(exclude=['test*']), include_package_data=True, zip_safe=True, # metadata for upload to PyPI author='LaterPay GmbH', author_email='django12factor@doismellburning.co.uk', url='https://github.com/laterpay/rubberjack-cli', description='RubberJack manages (AWS) Elastic Beanstalks', long_description=long_description, license='MIT', keywords='aws', install_requires=[ ], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], ) Drop `author_email` - oops, excessive copy-pasteimport os from setuptools import setup, find_packages __version__ = '0.1' HERE = os.path.dirname(__file__) try: long_description = open(os.path.join(HERE, 'README.rst')).read() except: long_description = None setup( name='rubberjack-cli', version=__version__, packages=find_packages(exclude=['test*']), include_package_data=True, zip_safe=True, # metadata for upload to PyPI author='LaterPay GmbH', url='https://github.com/laterpay/rubberjack-cli', description='RubberJack manages (AWS) Elastic Beanstalks', long_description=long_description, license='MIT', keywords='aws', install_requires=[ ], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], )
<commit_before>import os from setuptools import setup, find_packages __version__ = '0.1' HERE = os.path.dirname(__file__) try: long_description = open(os.path.join(HERE, 'README.rst')).read() except: long_description = None setup( name='rubberjack-cli', version=__version__, packages=find_packages(exclude=['test*']), include_package_data=True, zip_safe=True, # metadata for upload to PyPI author='LaterPay GmbH', author_email='django12factor@doismellburning.co.uk', url='https://github.com/laterpay/rubberjack-cli', description='RubberJack manages (AWS) Elastic Beanstalks', long_description=long_description, license='MIT', keywords='aws', install_requires=[ ], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], ) <commit_msg>Drop `author_email` - oops, excessive copy-paste<commit_after>import os from setuptools import setup, find_packages __version__ = '0.1' HERE = os.path.dirname(__file__) try: long_description = open(os.path.join(HERE, 'README.rst')).read() except: long_description = None setup( name='rubberjack-cli', version=__version__, packages=find_packages(exclude=['test*']), include_package_data=True, zip_safe=True, # metadata for upload to PyPI author='LaterPay GmbH', url='https://github.com/laterpay/rubberjack-cli', description='RubberJack manages (AWS) Elastic Beanstalks', long_description=long_description, license='MIT', keywords='aws', install_requires=[ ], classifiers=[ "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ], )
dcdaef9fb950a8082dcd46fc6a43c965b09f43b5
places/views.py
places/views.py
from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView, View from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView from django.views.generic.list import ListView from places.models import Restaurant class HomeView(TemplateView): template_name = "places/home.html" class RestaurantListView(ListView): model = Restaurant context_object_name = "restaurant_list" class RestaurantDetailView(DetailView): model = Restaurant context_object_name = "restaurant" class RestaurantUpdateView(LoginRequiredMixin, UpdateView): model = Restaurant fields = ["name", "description", "address", "min_party", "max_party", "yelp_link"] template_name_suffix = "_update" class RestaurantRandomView(View): def get(self, request): restaurant = Restaurant.objects.order_by("?").first() target_url = reverse("places:restaurant-detail", args=[restaurant.id]) return HttpResponseRedirect(target_url)
from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView, View from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView from django.views.generic.list import ListView from places.models import Restaurant class HomeView(TemplateView): template_name = "places/home.html" class RestaurantListView(ListView): model = Restaurant ordering = ["name"] context_object_name = "restaurant_list" class RestaurantDetailView(DetailView): model = Restaurant context_object_name = "restaurant" class RestaurantUpdateView(LoginRequiredMixin, UpdateView): model = Restaurant fields = ["name", "description", "address", "min_party", "max_party", "yelp_link"] template_name_suffix = "_update" class RestaurantRandomView(View): def get(self, request): restaurant = Restaurant.objects.order_by("?").first() target_url = reverse("places:restaurant-detail", args=[restaurant.id]) return HttpResponseRedirect(target_url)
Order restaurants by name in ListView
Order restaurants by name in ListView
Python
mit
huangsam/chowist,huangsam/chowist,huangsam/chowist
from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView, View from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView from django.views.generic.list import ListView from places.models import Restaurant class HomeView(TemplateView): template_name = "places/home.html" class RestaurantListView(ListView): model = Restaurant context_object_name = "restaurant_list" class RestaurantDetailView(DetailView): model = Restaurant context_object_name = "restaurant" class RestaurantUpdateView(LoginRequiredMixin, UpdateView): model = Restaurant fields = ["name", "description", "address", "min_party", "max_party", "yelp_link"] template_name_suffix = "_update" class RestaurantRandomView(View): def get(self, request): restaurant = Restaurant.objects.order_by("?").first() target_url = reverse("places:restaurant-detail", args=[restaurant.id]) return HttpResponseRedirect(target_url) Order restaurants by name in ListView
from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView, View from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView from django.views.generic.list import ListView from places.models import Restaurant class HomeView(TemplateView): template_name = "places/home.html" class RestaurantListView(ListView): model = Restaurant ordering = ["name"] context_object_name = "restaurant_list" class RestaurantDetailView(DetailView): model = Restaurant context_object_name = "restaurant" class RestaurantUpdateView(LoginRequiredMixin, UpdateView): model = Restaurant fields = ["name", "description", "address", "min_party", "max_party", "yelp_link"] template_name_suffix = "_update" class RestaurantRandomView(View): def get(self, request): restaurant = Restaurant.objects.order_by("?").first() target_url = reverse("places:restaurant-detail", args=[restaurant.id]) return HttpResponseRedirect(target_url)
<commit_before>from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView, View from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView from django.views.generic.list import ListView from places.models import Restaurant class HomeView(TemplateView): template_name = "places/home.html" class RestaurantListView(ListView): model = Restaurant context_object_name = "restaurant_list" class RestaurantDetailView(DetailView): model = Restaurant context_object_name = "restaurant" class RestaurantUpdateView(LoginRequiredMixin, UpdateView): model = Restaurant fields = ["name", "description", "address", "min_party", "max_party", "yelp_link"] template_name_suffix = "_update" class RestaurantRandomView(View): def get(self, request): restaurant = Restaurant.objects.order_by("?").first() target_url = reverse("places:restaurant-detail", args=[restaurant.id]) return HttpResponseRedirect(target_url) <commit_msg>Order restaurants by name in ListView<commit_after>
from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView, View from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView from django.views.generic.list import ListView from places.models import Restaurant class HomeView(TemplateView): template_name = "places/home.html" class RestaurantListView(ListView): model = Restaurant ordering = ["name"] context_object_name = "restaurant_list" class RestaurantDetailView(DetailView): model = Restaurant context_object_name = "restaurant" class RestaurantUpdateView(LoginRequiredMixin, UpdateView): model = Restaurant fields = ["name", "description", "address", "min_party", "max_party", "yelp_link"] template_name_suffix = "_update" class RestaurantRandomView(View): def get(self, request): restaurant = Restaurant.objects.order_by("?").first() target_url = reverse("places:restaurant-detail", args=[restaurant.id]) return HttpResponseRedirect(target_url)
from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView, View from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView from django.views.generic.list import ListView from places.models import Restaurant class HomeView(TemplateView): template_name = "places/home.html" class RestaurantListView(ListView): model = Restaurant context_object_name = "restaurant_list" class RestaurantDetailView(DetailView): model = Restaurant context_object_name = "restaurant" class RestaurantUpdateView(LoginRequiredMixin, UpdateView): model = Restaurant fields = ["name", "description", "address", "min_party", "max_party", "yelp_link"] template_name_suffix = "_update" class RestaurantRandomView(View): def get(self, request): restaurant = Restaurant.objects.order_by("?").first() target_url = reverse("places:restaurant-detail", args=[restaurant.id]) return HttpResponseRedirect(target_url) Order restaurants by name in ListViewfrom django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView, View from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView from django.views.generic.list import ListView from places.models import Restaurant class HomeView(TemplateView): template_name = "places/home.html" class RestaurantListView(ListView): model = Restaurant ordering = ["name"] context_object_name = "restaurant_list" class RestaurantDetailView(DetailView): model = Restaurant context_object_name = "restaurant" class RestaurantUpdateView(LoginRequiredMixin, UpdateView): model = Restaurant fields = ["name", "description", "address", "min_party", "max_party", "yelp_link"] template_name_suffix = "_update" class RestaurantRandomView(View): def get(self, request): restaurant = Restaurant.objects.order_by("?").first() target_url = reverse("places:restaurant-detail", args=[restaurant.id]) return HttpResponseRedirect(target_url)
<commit_before>from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView, View from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView from django.views.generic.list import ListView from places.models import Restaurant class HomeView(TemplateView): template_name = "places/home.html" class RestaurantListView(ListView): model = Restaurant context_object_name = "restaurant_list" class RestaurantDetailView(DetailView): model = Restaurant context_object_name = "restaurant" class RestaurantUpdateView(LoginRequiredMixin, UpdateView): model = Restaurant fields = ["name", "description", "address", "min_party", "max_party", "yelp_link"] template_name_suffix = "_update" class RestaurantRandomView(View): def get(self, request): restaurant = Restaurant.objects.order_by("?").first() target_url = reverse("places:restaurant-detail", args=[restaurant.id]) return HttpResponseRedirect(target_url) <commit_msg>Order restaurants by name in ListView<commit_after>from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import TemplateView, View from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView from django.views.generic.list import ListView from places.models import Restaurant class HomeView(TemplateView): template_name = "places/home.html" class RestaurantListView(ListView): model = Restaurant ordering = ["name"] context_object_name = "restaurant_list" class RestaurantDetailView(DetailView): model = Restaurant context_object_name = "restaurant" class RestaurantUpdateView(LoginRequiredMixin, UpdateView): model = Restaurant fields = ["name", "description", "address", "min_party", "max_party", "yelp_link"] template_name_suffix = "_update" class RestaurantRandomView(View): def get(self, request): restaurant = Restaurant.objects.order_by("?").first() target_url = reverse("places:restaurant-detail", args=[restaurant.id]) return HttpResponseRedirect(target_url)
747dbd3f70838386fda4e8755f44fcbefd5409b3
server/views.py
server/views.py
from rest_framework_mongoengine.viewsets import ModelViewSet from server.documents import Vote, User from server.serializers import VoteSerializer, UserSerializer class VoteViewSet(ModelViewSet): queryset = Vote.objects.all() serializer_class = VoteSerializer lookup_field = "stuff_id" class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = "stuff_id"
from rest_framework_mongoengine.viewsets import ModelViewSet from server.documents import Vote, User from server.serializers import VoteSerializer, UserSerializer class VoteViewSet(ModelViewSet): queryset = Vote.objects.all() serializer_class = VoteSerializer lookup_field = "stuff_id" class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = "twitter_id"
Add twitter_id as lookup for user
Add twitter_id as lookup for user
Python
agpl-3.0
asm-products/pipfix
from rest_framework_mongoengine.viewsets import ModelViewSet from server.documents import Vote, User from server.serializers import VoteSerializer, UserSerializer class VoteViewSet(ModelViewSet): queryset = Vote.objects.all() serializer_class = VoteSerializer lookup_field = "stuff_id" class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = "stuff_id" Add twitter_id as lookup for user
from rest_framework_mongoengine.viewsets import ModelViewSet from server.documents import Vote, User from server.serializers import VoteSerializer, UserSerializer class VoteViewSet(ModelViewSet): queryset = Vote.objects.all() serializer_class = VoteSerializer lookup_field = "stuff_id" class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = "twitter_id"
<commit_before>from rest_framework_mongoengine.viewsets import ModelViewSet from server.documents import Vote, User from server.serializers import VoteSerializer, UserSerializer class VoteViewSet(ModelViewSet): queryset = Vote.objects.all() serializer_class = VoteSerializer lookup_field = "stuff_id" class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = "stuff_id" <commit_msg>Add twitter_id as lookup for user<commit_after>
from rest_framework_mongoengine.viewsets import ModelViewSet from server.documents import Vote, User from server.serializers import VoteSerializer, UserSerializer class VoteViewSet(ModelViewSet): queryset = Vote.objects.all() serializer_class = VoteSerializer lookup_field = "stuff_id" class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = "twitter_id"
from rest_framework_mongoengine.viewsets import ModelViewSet from server.documents import Vote, User from server.serializers import VoteSerializer, UserSerializer class VoteViewSet(ModelViewSet): queryset = Vote.objects.all() serializer_class = VoteSerializer lookup_field = "stuff_id" class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = "stuff_id" Add twitter_id as lookup for userfrom rest_framework_mongoengine.viewsets import ModelViewSet from server.documents import Vote, User from server.serializers import VoteSerializer, UserSerializer class VoteViewSet(ModelViewSet): queryset = Vote.objects.all() serializer_class = VoteSerializer lookup_field = "stuff_id" class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = "twitter_id"
<commit_before>from rest_framework_mongoengine.viewsets import ModelViewSet from server.documents import Vote, User from server.serializers import VoteSerializer, UserSerializer class VoteViewSet(ModelViewSet): queryset = Vote.objects.all() serializer_class = VoteSerializer lookup_field = "stuff_id" class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = "stuff_id" <commit_msg>Add twitter_id as lookup for user<commit_after>from rest_framework_mongoengine.viewsets import ModelViewSet from server.documents import Vote, User from server.serializers import VoteSerializer, UserSerializer class VoteViewSet(ModelViewSet): queryset = Vote.objects.all() serializer_class = VoteSerializer lookup_field = "stuff_id" class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = "twitter_id"
9139a8f02b71acc4b07742bf18388236cffa5c75
settings/dev.py
settings/dev.py
# settings for development from common import * INTERNAL_IPS = ('127.0.0.1',) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) STATICFILES_FINDERS += ( 'compressor.finders.CompressorFinder', ) INSTALLED_APPS += ( 'django.contrib.admin', 'debug_toolbar', 'compressor', 'teracy.html5boilerplate', 'apps.hello', )
# settings for development from common import * INTERNAL_IPS = ('127.0.0.1',) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) STATICFILES_FINDERS += ( 'compressor.finders.CompressorFinder', ) INSTALLED_APPS += ( 'django.contrib.admin', 'debug_toolbar', 'compressor', 'teracy.html5boilerplate', ) INSTALLED_APPS += ( 'apps.hello', )
Add 'apps.hello' as separation of default installed apps
Add 'apps.hello' as separation of default installed apps
Python
bsd-3-clause
teracyhq/django-tutorial,datphan/teracy-tutorial
# settings for development from common import * INTERNAL_IPS = ('127.0.0.1',) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) STATICFILES_FINDERS += ( 'compressor.finders.CompressorFinder', ) INSTALLED_APPS += ( 'django.contrib.admin', 'debug_toolbar', 'compressor', 'teracy.html5boilerplate', 'apps.hello', )Add 'apps.hello' as separation of default installed apps
# settings for development from common import * INTERNAL_IPS = ('127.0.0.1',) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) STATICFILES_FINDERS += ( 'compressor.finders.CompressorFinder', ) INSTALLED_APPS += ( 'django.contrib.admin', 'debug_toolbar', 'compressor', 'teracy.html5boilerplate', ) INSTALLED_APPS += ( 'apps.hello', )
<commit_before># settings for development from common import * INTERNAL_IPS = ('127.0.0.1',) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) STATICFILES_FINDERS += ( 'compressor.finders.CompressorFinder', ) INSTALLED_APPS += ( 'django.contrib.admin', 'debug_toolbar', 'compressor', 'teracy.html5boilerplate', 'apps.hello', )<commit_msg>Add 'apps.hello' as separation of default installed apps<commit_after>
# settings for development from common import * INTERNAL_IPS = ('127.0.0.1',) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) STATICFILES_FINDERS += ( 'compressor.finders.CompressorFinder', ) INSTALLED_APPS += ( 'django.contrib.admin', 'debug_toolbar', 'compressor', 'teracy.html5boilerplate', ) INSTALLED_APPS += ( 'apps.hello', )
# settings for development from common import * INTERNAL_IPS = ('127.0.0.1',) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) STATICFILES_FINDERS += ( 'compressor.finders.CompressorFinder', ) INSTALLED_APPS += ( 'django.contrib.admin', 'debug_toolbar', 'compressor', 'teracy.html5boilerplate', 'apps.hello', )Add 'apps.hello' as separation of default installed apps# settings for development from common import * INTERNAL_IPS = ('127.0.0.1',) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) STATICFILES_FINDERS += ( 'compressor.finders.CompressorFinder', ) INSTALLED_APPS += ( 'django.contrib.admin', 'debug_toolbar', 'compressor', 'teracy.html5boilerplate', ) INSTALLED_APPS += ( 'apps.hello', )
<commit_before># settings for development from common import * INTERNAL_IPS = ('127.0.0.1',) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) STATICFILES_FINDERS += ( 'compressor.finders.CompressorFinder', ) INSTALLED_APPS += ( 'django.contrib.admin', 'debug_toolbar', 'compressor', 'teracy.html5boilerplate', 'apps.hello', )<commit_msg>Add 'apps.hello' as separation of default installed apps<commit_after># settings for development from common import * INTERNAL_IPS = ('127.0.0.1',) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) STATICFILES_FINDERS += ( 'compressor.finders.CompressorFinder', ) INSTALLED_APPS += ( 'django.contrib.admin', 'debug_toolbar', 'compressor', 'teracy.html5boilerplate', ) INSTALLED_APPS += ( 'apps.hello', )
df6f4af9d61ac66450a54c6134a587db0fd93e34
python/simple_types.py
python/simple_types.py
assert(type(5) == int) assert(type(True) == bool) assert(type(5.7) == float) assert(type(9 + 5j) == complex) assert(type((8, 'dog', False)) == tuple) assert(type('hello') == str) assert(type(b'hello') == bytes) assert(type([1, '', False]) == list) assert(type(range(1,10)) == range) assert(type(set([1, 2, 3])) == set) assert(type(frozenset([1, 2, 3])) == frozenset) assert(type({'x': 1, 'y': 2}) == dict) assert(type(int) == type) assert(type(type) == type) assert(type(enumerate([])) == enumerate) assert(type(slice([])) == slice) assert(str(type(None)) == "<class 'NoneType'>") assert(str(type(NotImplemented)) == "<class 'NotImplementedType'>") assert(str(type(abs)) == "<class 'builtin_function_or_method'>")
assert(type(5) == int) assert(type(True) == bool) assert(type(5.7) == float) assert(type(9 + 5j) == complex) assert(type((8, 'dog', False)) == tuple) assert(type('hello') == str) assert(type(b'hello') == bytes) assert(type([1, '', False]) == list) assert(type(range(1,10)) == range) assert(type({1, 2, 3}) == set) assert(type(frozenset([1, 2, 3])) == frozenset) assert(type({'x': 1, 'y': 2}) == dict) assert(type(int) == type) assert(type(type) == type) assert(type(enumerate([])) == enumerate) assert(type(slice([])) == slice) assert(str(type(None)) == "<class 'NoneType'>") assert(str(type(NotImplemented)) == "<class 'NotImplementedType'>") assert(str(type(abs)) == "<class 'builtin_function_or_method'>")
Use braces for Python sets
Use braces for Python sets
Python
mit
rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple
assert(type(5) == int) assert(type(True) == bool) assert(type(5.7) == float) assert(type(9 + 5j) == complex) assert(type((8, 'dog', False)) == tuple) assert(type('hello') == str) assert(type(b'hello') == bytes) assert(type([1, '', False]) == list) assert(type(range(1,10)) == range) assert(type(set([1, 2, 3])) == set) assert(type(frozenset([1, 2, 3])) == frozenset) assert(type({'x': 1, 'y': 2}) == dict) assert(type(int) == type) assert(type(type) == type) assert(type(enumerate([])) == enumerate) assert(type(slice([])) == slice) assert(str(type(None)) == "<class 'NoneType'>") assert(str(type(NotImplemented)) == "<class 'NotImplementedType'>") assert(str(type(abs)) == "<class 'builtin_function_or_method'>") Use braces for Python sets
assert(type(5) == int) assert(type(True) == bool) assert(type(5.7) == float) assert(type(9 + 5j) == complex) assert(type((8, 'dog', False)) == tuple) assert(type('hello') == str) assert(type(b'hello') == bytes) assert(type([1, '', False]) == list) assert(type(range(1,10)) == range) assert(type({1, 2, 3}) == set) assert(type(frozenset([1, 2, 3])) == frozenset) assert(type({'x': 1, 'y': 2}) == dict) assert(type(int) == type) assert(type(type) == type) assert(type(enumerate([])) == enumerate) assert(type(slice([])) == slice) assert(str(type(None)) == "<class 'NoneType'>") assert(str(type(NotImplemented)) == "<class 'NotImplementedType'>") assert(str(type(abs)) == "<class 'builtin_function_or_method'>")
<commit_before>assert(type(5) == int) assert(type(True) == bool) assert(type(5.7) == float) assert(type(9 + 5j) == complex) assert(type((8, 'dog', False)) == tuple) assert(type('hello') == str) assert(type(b'hello') == bytes) assert(type([1, '', False]) == list) assert(type(range(1,10)) == range) assert(type(set([1, 2, 3])) == set) assert(type(frozenset([1, 2, 3])) == frozenset) assert(type({'x': 1, 'y': 2}) == dict) assert(type(int) == type) assert(type(type) == type) assert(type(enumerate([])) == enumerate) assert(type(slice([])) == slice) assert(str(type(None)) == "<class 'NoneType'>") assert(str(type(NotImplemented)) == "<class 'NotImplementedType'>") assert(str(type(abs)) == "<class 'builtin_function_or_method'>") <commit_msg>Use braces for Python sets<commit_after>
assert(type(5) == int) assert(type(True) == bool) assert(type(5.7) == float) assert(type(9 + 5j) == complex) assert(type((8, 'dog', False)) == tuple) assert(type('hello') == str) assert(type(b'hello') == bytes) assert(type([1, '', False]) == list) assert(type(range(1,10)) == range) assert(type({1, 2, 3}) == set) assert(type(frozenset([1, 2, 3])) == frozenset) assert(type({'x': 1, 'y': 2}) == dict) assert(type(int) == type) assert(type(type) == type) assert(type(enumerate([])) == enumerate) assert(type(slice([])) == slice) assert(str(type(None)) == "<class 'NoneType'>") assert(str(type(NotImplemented)) == "<class 'NotImplementedType'>") assert(str(type(abs)) == "<class 'builtin_function_or_method'>")
assert(type(5) == int) assert(type(True) == bool) assert(type(5.7) == float) assert(type(9 + 5j) == complex) assert(type((8, 'dog', False)) == tuple) assert(type('hello') == str) assert(type(b'hello') == bytes) assert(type([1, '', False]) == list) assert(type(range(1,10)) == range) assert(type(set([1, 2, 3])) == set) assert(type(frozenset([1, 2, 3])) == frozenset) assert(type({'x': 1, 'y': 2}) == dict) assert(type(int) == type) assert(type(type) == type) assert(type(enumerate([])) == enumerate) assert(type(slice([])) == slice) assert(str(type(None)) == "<class 'NoneType'>") assert(str(type(NotImplemented)) == "<class 'NotImplementedType'>") assert(str(type(abs)) == "<class 'builtin_function_or_method'>") Use braces for Python setsassert(type(5) == int) assert(type(True) == bool) assert(type(5.7) == float) assert(type(9 + 5j) == complex) assert(type((8, 'dog', False)) == tuple) assert(type('hello') == str) assert(type(b'hello') == bytes) assert(type([1, '', False]) == list) assert(type(range(1,10)) == range) assert(type({1, 2, 3}) == set) assert(type(frozenset([1, 2, 3])) == frozenset) assert(type({'x': 1, 'y': 2}) == dict) assert(type(int) == type) assert(type(type) == type) assert(type(enumerate([])) == enumerate) assert(type(slice([])) == slice) assert(str(type(None)) == "<class 'NoneType'>") assert(str(type(NotImplemented)) == "<class 'NotImplementedType'>") assert(str(type(abs)) == "<class 'builtin_function_or_method'>")
<commit_before>assert(type(5) == int) assert(type(True) == bool) assert(type(5.7) == float) assert(type(9 + 5j) == complex) assert(type((8, 'dog', False)) == tuple) assert(type('hello') == str) assert(type(b'hello') == bytes) assert(type([1, '', False]) == list) assert(type(range(1,10)) == range) assert(type(set([1, 2, 3])) == set) assert(type(frozenset([1, 2, 3])) == frozenset) assert(type({'x': 1, 'y': 2}) == dict) assert(type(int) == type) assert(type(type) == type) assert(type(enumerate([])) == enumerate) assert(type(slice([])) == slice) assert(str(type(None)) == "<class 'NoneType'>") assert(str(type(NotImplemented)) == "<class 'NotImplementedType'>") assert(str(type(abs)) == "<class 'builtin_function_or_method'>") <commit_msg>Use braces for Python sets<commit_after>assert(type(5) == int) assert(type(True) == bool) assert(type(5.7) == float) assert(type(9 + 5j) == complex) assert(type((8, 'dog', False)) == tuple) assert(type('hello') == str) assert(type(b'hello') == bytes) assert(type([1, '', False]) == list) assert(type(range(1,10)) == range) assert(type({1, 2, 3}) == set) assert(type(frozenset([1, 2, 3])) == frozenset) assert(type({'x': 1, 'y': 2}) == dict) assert(type(int) == type) assert(type(type) == type) assert(type(enumerate([])) == enumerate) assert(type(slice([])) == slice) assert(str(type(None)) == "<class 'NoneType'>") assert(str(type(NotImplemented)) == "<class 'NotImplementedType'>") assert(str(type(abs)) == "<class 'builtin_function_or_method'>")
08e84dcc0bce7a1914bc7fa734ca51c0dde362d1
lab/monitors/nova_service_list.py
lab/monitors/nova_service_list.py
def start(lab, log, args): import time from fabric.context_managers import shell_env grep_host = args.get('grep_host', 'overcloud-') duration = args['duration'] period = args['period'] statuses = {'up': 1, 'down': 0} server = lab.director() start_time = time.time() while start_time + duration > time.time(): with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant): res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True) results = [line.split() for line in res.split('\n')] msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results]) log.info('{1}'.format(grep_host, msg)) time.sleep(period)
def start(lab, log, args): from fabric.context_managers import shell_env grep_host = args.get('grep_host', 'overcloud-') statuses = {'up': 1, 'down': 0} server = lab.director() with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant): res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True) results = [line.split() for line in res.split('\n')] msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results]) log.info('{1}'.format(grep_host, msg))
Verify services status if FI is rebooted
Verify services status if FI is rebooted Change-Id: Ia02ef16d53fbb7b55a8de884ff16a4bef345a1f2
Python
apache-2.0
CiscoSystems/os-sqe,CiscoSystems/os-sqe,CiscoSystems/os-sqe
def start(lab, log, args): import time from fabric.context_managers import shell_env grep_host = args.get('grep_host', 'overcloud-') duration = args['duration'] period = args['period'] statuses = {'up': 1, 'down': 0} server = lab.director() start_time = time.time() while start_time + duration > time.time(): with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant): res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True) results = [line.split() for line in res.split('\n')] msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results]) log.info('{1}'.format(grep_host, msg)) time.sleep(period) Verify services status if FI is rebooted Change-Id: Ia02ef16d53fbb7b55a8de884ff16a4bef345a1f2
def start(lab, log, args): from fabric.context_managers import shell_env grep_host = args.get('grep_host', 'overcloud-') statuses = {'up': 1, 'down': 0} server = lab.director() with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant): res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True) results = [line.split() for line in res.split('\n')] msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results]) log.info('{1}'.format(grep_host, msg))
<commit_before>def start(lab, log, args): import time from fabric.context_managers import shell_env grep_host = args.get('grep_host', 'overcloud-') duration = args['duration'] period = args['period'] statuses = {'up': 1, 'down': 0} server = lab.director() start_time = time.time() while start_time + duration > time.time(): with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant): res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True) results = [line.split() for line in res.split('\n')] msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results]) log.info('{1}'.format(grep_host, msg)) time.sleep(period) <commit_msg>Verify services status if FI is rebooted Change-Id: Ia02ef16d53fbb7b55a8de884ff16a4bef345a1f2<commit_after>
def start(lab, log, args): from fabric.context_managers import shell_env grep_host = args.get('grep_host', 'overcloud-') statuses = {'up': 1, 'down': 0} server = lab.director() with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant): res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True) results = [line.split() for line in res.split('\n')] msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results]) log.info('{1}'.format(grep_host, msg))
def start(lab, log, args): import time from fabric.context_managers import shell_env grep_host = args.get('grep_host', 'overcloud-') duration = args['duration'] period = args['period'] statuses = {'up': 1, 'down': 0} server = lab.director() start_time = time.time() while start_time + duration > time.time(): with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant): res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True) results = [line.split() for line in res.split('\n')] msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results]) log.info('{1}'.format(grep_host, msg)) time.sleep(period) Verify services status if FI is rebooted Change-Id: Ia02ef16d53fbb7b55a8de884ff16a4bef345a1f2def start(lab, log, args): from fabric.context_managers import shell_env grep_host = args.get('grep_host', 'overcloud-') statuses = {'up': 1, 'down': 0} server = lab.director() with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant): res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True) results = [line.split() for line in res.split('\n')] msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results]) log.info('{1}'.format(grep_host, msg))
<commit_before>def start(lab, log, args): import time from fabric.context_managers import shell_env grep_host = args.get('grep_host', 'overcloud-') duration = args['duration'] period = args['period'] statuses = {'up': 1, 'down': 0} server = lab.director() start_time = time.time() while start_time + duration > time.time(): with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant): res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True) results = [line.split() for line in res.split('\n')] msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results]) log.info('{1}'.format(grep_host, msg)) time.sleep(period) <commit_msg>Verify services status if FI is rebooted Change-Id: Ia02ef16d53fbb7b55a8de884ff16a4bef345a1f2<commit_after>def start(lab, log, args): from fabric.context_managers import shell_env grep_host = args.get('grep_host', 'overcloud-') statuses = {'up': 1, 'down': 0} server = lab.director() with shell_env(OS_AUTH_URL=lab.cloud.end_point, OS_USERNAME=lab.cloud.user, OS_PASSWORD=lab.cloud.password, OS_TENANT_NAME=lab.cloud.tenant): res = server.run("nova service-list | grep {0} | awk '{{print $4 \" \" $6 \" \" $12}}'".format(grep_host), warn_only=True) results = [line.split() for line in res.split('\n')] msg = ' '.join(['{1}:{0}={2}'.format(r[0], r[1], statuses[r[2]]) for r in results]) log.info('{1}'.format(grep_host, msg))
84953a5595598f08741d49da22b01aaca2459bc2
server/bottle_drone.py
server/bottle_drone.py
"""Set up a bottle server to accept post requests commanding the drone.""" from bottle import post, run, hook, response, get, abort from venthur_api import libardrone drone = libardrone.ARDrone() @hook('after_request') def enable_cors(): """Allow control headers.""" response.headers['Access-Control-Allow-Origin'] = '*' @get('/navdata') def navdata(): """Return packet of navdata.""" print(type(drone.image)) return drone.image @get('/imgdata') def navdata(): """Return packet of navdata.""" print(drone.navdata) return drone.navdata @post('/do/<command>') def do(command): """Execute the given command from the route.""" try: print('Command received: {}'.format(command)) getattr(drone, command)() print('Command executed: {}'.format(command)) return 'Command executed: {}'.format(command) except AttributeError: print('Bad Command: {}'.format(command)) abort(404, 'Bad Command: {}'.format(command)) try: run(host='127.0.0.1', port=8080) finally: drone.land() drone.halt()
"""Set up a bottle server to accept post requests commanding the drone.""" from bottle import post, run, hook, response, get, abort from venthur_api import libardrone drone = libardrone.ARDrone() @hook('after_request') def enable_cors(): """Allow control headers.""" response.headers['Access-Control-Allow-Origin'] = '*' @get('/imgdata') def imgdata(): """Return the current drone image.""" print(type(drone.image)) return drone.image @get('/navdata') def navdata(): """Return packet of navdata.""" response.content_type = 'image/x-rgb' print(drone.navdata) return drone.navdata @post('/do/<command>') def do(command): """Execute the given command from the route.""" try: print('Command received: {}'.format(command)) getattr(drone, command)() print('Command executed: {}'.format(command)) return 'Command executed: {}'.format(command) except AttributeError: print('Bad Command: {}'.format(command)) abort(404, 'Bad Command: {}'.format(command)) try: run(host='127.0.0.1', port=8080) finally: drone.land() drone.halt()
Set up a imgdata route to fetch latest image.
Set up a imgdata route to fetch latest image.
Python
mit
DroneQuest/drone-quest,DroneQuest/drone-quest
"""Set up a bottle server to accept post requests commanding the drone.""" from bottle import post, run, hook, response, get, abort from venthur_api import libardrone drone = libardrone.ARDrone() @hook('after_request') def enable_cors(): """Allow control headers.""" response.headers['Access-Control-Allow-Origin'] = '*' @get('/navdata') def navdata(): """Return packet of navdata.""" print(type(drone.image)) return drone.image @get('/imgdata') def navdata(): """Return packet of navdata.""" print(drone.navdata) return drone.navdata @post('/do/<command>') def do(command): """Execute the given command from the route.""" try: print('Command received: {}'.format(command)) getattr(drone, command)() print('Command executed: {}'.format(command)) return 'Command executed: {}'.format(command) except AttributeError: print('Bad Command: {}'.format(command)) abort(404, 'Bad Command: {}'.format(command)) try: run(host='127.0.0.1', port=8080) finally: drone.land() drone.halt() Set up a imgdata route to fetch latest image.
"""Set up a bottle server to accept post requests commanding the drone.""" from bottle import post, run, hook, response, get, abort from venthur_api import libardrone drone = libardrone.ARDrone() @hook('after_request') def enable_cors(): """Allow control headers.""" response.headers['Access-Control-Allow-Origin'] = '*' @get('/imgdata') def imgdata(): """Return the current drone image.""" print(type(drone.image)) return drone.image @get('/navdata') def navdata(): """Return packet of navdata.""" response.content_type = 'image/x-rgb' print(drone.navdata) return drone.navdata @post('/do/<command>') def do(command): """Execute the given command from the route.""" try: print('Command received: {}'.format(command)) getattr(drone, command)() print('Command executed: {}'.format(command)) return 'Command executed: {}'.format(command) except AttributeError: print('Bad Command: {}'.format(command)) abort(404, 'Bad Command: {}'.format(command)) try: run(host='127.0.0.1', port=8080) finally: drone.land() drone.halt()
<commit_before>"""Set up a bottle server to accept post requests commanding the drone.""" from bottle import post, run, hook, response, get, abort from venthur_api import libardrone drone = libardrone.ARDrone() @hook('after_request') def enable_cors(): """Allow control headers.""" response.headers['Access-Control-Allow-Origin'] = '*' @get('/navdata') def navdata(): """Return packet of navdata.""" print(type(drone.image)) return drone.image @get('/imgdata') def navdata(): """Return packet of navdata.""" print(drone.navdata) return drone.navdata @post('/do/<command>') def do(command): """Execute the given command from the route.""" try: print('Command received: {}'.format(command)) getattr(drone, command)() print('Command executed: {}'.format(command)) return 'Command executed: {}'.format(command) except AttributeError: print('Bad Command: {}'.format(command)) abort(404, 'Bad Command: {}'.format(command)) try: run(host='127.0.0.1', port=8080) finally: drone.land() drone.halt() <commit_msg>Set up a imgdata route to fetch latest image.<commit_after>
"""Set up a bottle server to accept post requests commanding the drone.""" from bottle import post, run, hook, response, get, abort from venthur_api import libardrone drone = libardrone.ARDrone() @hook('after_request') def enable_cors(): """Allow control headers.""" response.headers['Access-Control-Allow-Origin'] = '*' @get('/imgdata') def imgdata(): """Return the current drone image.""" print(type(drone.image)) return drone.image @get('/navdata') def navdata(): """Return packet of navdata.""" response.content_type = 'image/x-rgb' print(drone.navdata) return drone.navdata @post('/do/<command>') def do(command): """Execute the given command from the route.""" try: print('Command received: {}'.format(command)) getattr(drone, command)() print('Command executed: {}'.format(command)) return 'Command executed: {}'.format(command) except AttributeError: print('Bad Command: {}'.format(command)) abort(404, 'Bad Command: {}'.format(command)) try: run(host='127.0.0.1', port=8080) finally: drone.land() drone.halt()
"""Set up a bottle server to accept post requests commanding the drone.""" from bottle import post, run, hook, response, get, abort from venthur_api import libardrone drone = libardrone.ARDrone() @hook('after_request') def enable_cors(): """Allow control headers.""" response.headers['Access-Control-Allow-Origin'] = '*' @get('/navdata') def navdata(): """Return packet of navdata.""" print(type(drone.image)) return drone.image @get('/imgdata') def navdata(): """Return packet of navdata.""" print(drone.navdata) return drone.navdata @post('/do/<command>') def do(command): """Execute the given command from the route.""" try: print('Command received: {}'.format(command)) getattr(drone, command)() print('Command executed: {}'.format(command)) return 'Command executed: {}'.format(command) except AttributeError: print('Bad Command: {}'.format(command)) abort(404, 'Bad Command: {}'.format(command)) try: run(host='127.0.0.1', port=8080) finally: drone.land() drone.halt() Set up a imgdata route to fetch latest image."""Set up a bottle server to accept post requests commanding the drone.""" from bottle import post, run, hook, response, get, abort from venthur_api import libardrone drone = libardrone.ARDrone() @hook('after_request') def enable_cors(): """Allow control headers.""" response.headers['Access-Control-Allow-Origin'] = '*' @get('/imgdata') def imgdata(): """Return the current drone image.""" print(type(drone.image)) return drone.image @get('/navdata') def navdata(): """Return packet of navdata.""" response.content_type = 'image/x-rgb' print(drone.navdata) return drone.navdata @post('/do/<command>') def do(command): """Execute the given command from the route.""" try: print('Command received: {}'.format(command)) getattr(drone, command)() print('Command executed: {}'.format(command)) return 'Command executed: {}'.format(command) except AttributeError: print('Bad Command: {}'.format(command)) abort(404, 'Bad Command: {}'.format(command)) try: run(host='127.0.0.1', port=8080) finally: drone.land() drone.halt()
<commit_before>"""Set up a bottle server to accept post requests commanding the drone.""" from bottle import post, run, hook, response, get, abort from venthur_api import libardrone drone = libardrone.ARDrone() @hook('after_request') def enable_cors(): """Allow control headers.""" response.headers['Access-Control-Allow-Origin'] = '*' @get('/navdata') def navdata(): """Return packet of navdata.""" print(type(drone.image)) return drone.image @get('/imgdata') def navdata(): """Return packet of navdata.""" print(drone.navdata) return drone.navdata @post('/do/<command>') def do(command): """Execute the given command from the route.""" try: print('Command received: {}'.format(command)) getattr(drone, command)() print('Command executed: {}'.format(command)) return 'Command executed: {}'.format(command) except AttributeError: print('Bad Command: {}'.format(command)) abort(404, 'Bad Command: {}'.format(command)) try: run(host='127.0.0.1', port=8080) finally: drone.land() drone.halt() <commit_msg>Set up a imgdata route to fetch latest image.<commit_after>"""Set up a bottle server to accept post requests commanding the drone.""" from bottle import post, run, hook, response, get, abort from venthur_api import libardrone drone = libardrone.ARDrone() @hook('after_request') def enable_cors(): """Allow control headers.""" response.headers['Access-Control-Allow-Origin'] = '*' @get('/imgdata') def imgdata(): """Return the current drone image.""" print(type(drone.image)) return drone.image @get('/navdata') def navdata(): """Return packet of navdata.""" response.content_type = 'image/x-rgb' print(drone.navdata) return drone.navdata @post('/do/<command>') def do(command): """Execute the given command from the route.""" try: print('Command received: {}'.format(command)) getattr(drone, command)() print('Command executed: {}'.format(command)) return 'Command executed: {}'.format(command) except AttributeError: print('Bad Command: {}'.format(command)) abort(404, 'Bad Command: {}'.format(command)) try: run(host='127.0.0.1', port=8080) finally: drone.land() drone.halt()
0449b604691b78d41ba588c43fe6f9646ebfc2e4
OIPA/api/permissions/serializers.py
OIPA/api/permissions/serializers.py
from rest_framework import serializers from django.contrib.auth.models import Group from iati.permissions.models import OrganisationUser, OrganisationAdminGroup, OrganisationGroup from api.publisher.serializers import PublisherSerializer class OrganisationUserSerializer(serializers.ModelSerializer): admin_groups = serializers.SerializerMethodField() organisation_groups = serializers.SerializerMethodField() def get_admin_groups(self, user): qs = OrganisationAdminGroup.objects.filter(user=user) serializer = OrganisationAdminGroupSerializer(instance=qs, many=True) return serializer.data def get_organisation_groups(self, user): qs = OrganisationGroup.objects.filter(user=user) serializer = OrganisationGroupSerializer(instance=qs, many=True) return serializer.data class Meta: model = OrganisationUser fields = ('username', 'email', 'organisation_groups', 'admin_groups') class OrganisationGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationGroup fields = ('name', 'publisher') class OrganisationAdminGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationAdminGroup fields = ('name', 'publisher',)
from rest_framework import serializers from django.contrib.auth.models import Group from iati.permissions.models import OrganisationUser, OrganisationAdminGroup, OrganisationGroup from api.publisher.serializers import PublisherSerializer class OrganisationUserSerializer(serializers.ModelSerializer): admin_groups = serializers.SerializerMethodField() organisation_groups = serializers.SerializerMethodField() is_validated = serializers.SerializerMethodField() def get_admin_groups(self, user): qs = OrganisationAdminGroup.objects.filter(user=user) serializer = OrganisationAdminGroupSerializer(instance=qs, many=True) return serializer.data def get_organisation_groups(self, user): qs = OrganisationGroup.objects.filter(user=user) serializer = OrganisationGroupSerializer(instance=qs, many=True) return serializer.data def get_is_validated(self, user): return bool(user.iati_api_key) class Meta: model = OrganisationUser fields = ('username', 'email', 'organisation_groups', 'admin_groups', 'is_validated') class OrganisationGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationGroup fields = ('name', 'publisher') class OrganisationAdminGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationAdminGroup fields = ('name', 'publisher',)
Add an is_validated key t OrganisationUserSerializer.
Add an is_validated key t OrganisationUserSerializer.
Python
agpl-3.0
zimmerman-zimmerman/OIPA,zimmerman-zimmerman/OIPA,zimmerman-zimmerman/OIPA,openaid-IATI/OIPA,openaid-IATI/OIPA,zimmerman-zimmerman/OIPA,openaid-IATI/OIPA,openaid-IATI/OIPA,zimmerman-zimmerman/OIPA,openaid-IATI/OIPA
from rest_framework import serializers from django.contrib.auth.models import Group from iati.permissions.models import OrganisationUser, OrganisationAdminGroup, OrganisationGroup from api.publisher.serializers import PublisherSerializer class OrganisationUserSerializer(serializers.ModelSerializer): admin_groups = serializers.SerializerMethodField() organisation_groups = serializers.SerializerMethodField() def get_admin_groups(self, user): qs = OrganisationAdminGroup.objects.filter(user=user) serializer = OrganisationAdminGroupSerializer(instance=qs, many=True) return serializer.data def get_organisation_groups(self, user): qs = OrganisationGroup.objects.filter(user=user) serializer = OrganisationGroupSerializer(instance=qs, many=True) return serializer.data class Meta: model = OrganisationUser fields = ('username', 'email', 'organisation_groups', 'admin_groups') class OrganisationGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationGroup fields = ('name', 'publisher') class OrganisationAdminGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationAdminGroup fields = ('name', 'publisher',) Add an is_validated key t OrganisationUserSerializer.
from rest_framework import serializers from django.contrib.auth.models import Group from iati.permissions.models import OrganisationUser, OrganisationAdminGroup, OrganisationGroup from api.publisher.serializers import PublisherSerializer class OrganisationUserSerializer(serializers.ModelSerializer): admin_groups = serializers.SerializerMethodField() organisation_groups = serializers.SerializerMethodField() is_validated = serializers.SerializerMethodField() def get_admin_groups(self, user): qs = OrganisationAdminGroup.objects.filter(user=user) serializer = OrganisationAdminGroupSerializer(instance=qs, many=True) return serializer.data def get_organisation_groups(self, user): qs = OrganisationGroup.objects.filter(user=user) serializer = OrganisationGroupSerializer(instance=qs, many=True) return serializer.data def get_is_validated(self, user): return bool(user.iati_api_key) class Meta: model = OrganisationUser fields = ('username', 'email', 'organisation_groups', 'admin_groups', 'is_validated') class OrganisationGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationGroup fields = ('name', 'publisher') class OrganisationAdminGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationAdminGroup fields = ('name', 'publisher',)
<commit_before>from rest_framework import serializers from django.contrib.auth.models import Group from iati.permissions.models import OrganisationUser, OrganisationAdminGroup, OrganisationGroup from api.publisher.serializers import PublisherSerializer class OrganisationUserSerializer(serializers.ModelSerializer): admin_groups = serializers.SerializerMethodField() organisation_groups = serializers.SerializerMethodField() def get_admin_groups(self, user): qs = OrganisationAdminGroup.objects.filter(user=user) serializer = OrganisationAdminGroupSerializer(instance=qs, many=True) return serializer.data def get_organisation_groups(self, user): qs = OrganisationGroup.objects.filter(user=user) serializer = OrganisationGroupSerializer(instance=qs, many=True) return serializer.data class Meta: model = OrganisationUser fields = ('username', 'email', 'organisation_groups', 'admin_groups') class OrganisationGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationGroup fields = ('name', 'publisher') class OrganisationAdminGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationAdminGroup fields = ('name', 'publisher',) <commit_msg>Add an is_validated key t OrganisationUserSerializer.<commit_after>
from rest_framework import serializers from django.contrib.auth.models import Group from iati.permissions.models import OrganisationUser, OrganisationAdminGroup, OrganisationGroup from api.publisher.serializers import PublisherSerializer class OrganisationUserSerializer(serializers.ModelSerializer): admin_groups = serializers.SerializerMethodField() organisation_groups = serializers.SerializerMethodField() is_validated = serializers.SerializerMethodField() def get_admin_groups(self, user): qs = OrganisationAdminGroup.objects.filter(user=user) serializer = OrganisationAdminGroupSerializer(instance=qs, many=True) return serializer.data def get_organisation_groups(self, user): qs = OrganisationGroup.objects.filter(user=user) serializer = OrganisationGroupSerializer(instance=qs, many=True) return serializer.data def get_is_validated(self, user): return bool(user.iati_api_key) class Meta: model = OrganisationUser fields = ('username', 'email', 'organisation_groups', 'admin_groups', 'is_validated') class OrganisationGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationGroup fields = ('name', 'publisher') class OrganisationAdminGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationAdminGroup fields = ('name', 'publisher',)
from rest_framework import serializers from django.contrib.auth.models import Group from iati.permissions.models import OrganisationUser, OrganisationAdminGroup, OrganisationGroup from api.publisher.serializers import PublisherSerializer class OrganisationUserSerializer(serializers.ModelSerializer): admin_groups = serializers.SerializerMethodField() organisation_groups = serializers.SerializerMethodField() def get_admin_groups(self, user): qs = OrganisationAdminGroup.objects.filter(user=user) serializer = OrganisationAdminGroupSerializer(instance=qs, many=True) return serializer.data def get_organisation_groups(self, user): qs = OrganisationGroup.objects.filter(user=user) serializer = OrganisationGroupSerializer(instance=qs, many=True) return serializer.data class Meta: model = OrganisationUser fields = ('username', 'email', 'organisation_groups', 'admin_groups') class OrganisationGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationGroup fields = ('name', 'publisher') class OrganisationAdminGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationAdminGroup fields = ('name', 'publisher',) Add an is_validated key t OrganisationUserSerializer.from rest_framework import serializers from django.contrib.auth.models import Group from iati.permissions.models import OrganisationUser, OrganisationAdminGroup, OrganisationGroup from api.publisher.serializers import PublisherSerializer class OrganisationUserSerializer(serializers.ModelSerializer): admin_groups = serializers.SerializerMethodField() organisation_groups = serializers.SerializerMethodField() is_validated = serializers.SerializerMethodField() def get_admin_groups(self, user): qs = OrganisationAdminGroup.objects.filter(user=user) serializer = OrganisationAdminGroupSerializer(instance=qs, many=True) return serializer.data def get_organisation_groups(self, user): qs = OrganisationGroup.objects.filter(user=user) serializer = OrganisationGroupSerializer(instance=qs, many=True) return serializer.data def get_is_validated(self, user): return bool(user.iati_api_key) class Meta: model = OrganisationUser fields = ('username', 'email', 'organisation_groups', 'admin_groups', 'is_validated') class OrganisationGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationGroup fields = ('name', 'publisher') class OrganisationAdminGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationAdminGroup fields = ('name', 'publisher',)
<commit_before>from rest_framework import serializers from django.contrib.auth.models import Group from iati.permissions.models import OrganisationUser, OrganisationAdminGroup, OrganisationGroup from api.publisher.serializers import PublisherSerializer class OrganisationUserSerializer(serializers.ModelSerializer): admin_groups = serializers.SerializerMethodField() organisation_groups = serializers.SerializerMethodField() def get_admin_groups(self, user): qs = OrganisationAdminGroup.objects.filter(user=user) serializer = OrganisationAdminGroupSerializer(instance=qs, many=True) return serializer.data def get_organisation_groups(self, user): qs = OrganisationGroup.objects.filter(user=user) serializer = OrganisationGroupSerializer(instance=qs, many=True) return serializer.data class Meta: model = OrganisationUser fields = ('username', 'email', 'organisation_groups', 'admin_groups') class OrganisationGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationGroup fields = ('name', 'publisher') class OrganisationAdminGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationAdminGroup fields = ('name', 'publisher',) <commit_msg>Add an is_validated key t OrganisationUserSerializer.<commit_after>from rest_framework import serializers from django.contrib.auth.models import Group from iati.permissions.models import OrganisationUser, OrganisationAdminGroup, OrganisationGroup from api.publisher.serializers import PublisherSerializer class OrganisationUserSerializer(serializers.ModelSerializer): admin_groups = serializers.SerializerMethodField() organisation_groups = serializers.SerializerMethodField() is_validated = serializers.SerializerMethodField() def get_admin_groups(self, user): qs = OrganisationAdminGroup.objects.filter(user=user) serializer = OrganisationAdminGroupSerializer(instance=qs, many=True) return serializer.data def get_organisation_groups(self, user): qs = OrganisationGroup.objects.filter(user=user) serializer = OrganisationGroupSerializer(instance=qs, many=True) return serializer.data def get_is_validated(self, user): return bool(user.iati_api_key) class Meta: model = OrganisationUser fields = ('username', 'email', 'organisation_groups', 'admin_groups', 'is_validated') class OrganisationGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationGroup fields = ('name', 'publisher') class OrganisationAdminGroupSerializer(serializers.ModelSerializer): publisher = PublisherSerializer() class Meta: model = OrganisationAdminGroup fields = ('name', 'publisher',)
914e9dd1e9dd9fb3a0847d7b57095a4d571d17cd
keras_cv/__init__.py
keras_cv/__init__.py
# Copyright 2022 The KerasCV Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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 keras_cv import layers from keras_cv import metrics from keras_cv import utils from keras_cv import version_check from keras_cv.core import ConstantFactorSampler from keras_cv.core import FactorSampler from keras_cv.core import NormalFactorSampler from keras_cv.core import UniformFactorSampler version_check.check_tf_version() __version__ = "0.2.0"
# Copyright 2022 The KerasCV Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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 keras_cv import layers from keras_cv import metrics from keras_cv import utils from keras_cv import version_check from keras_cv.core import ConstantFactorSampler from keras_cv.core import FactorSampler from keras_cv.core import NormalFactorSampler from keras_cv.core import UniformFactorSampler version_check.check_tf_version() __version__ = "0.2.0dev"
Update back to dev tag
Update back to dev tag
Python
apache-2.0
keras-team/keras-cv,keras-team/keras-cv,keras-team/keras-cv
# Copyright 2022 The KerasCV Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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 keras_cv import layers from keras_cv import metrics from keras_cv import utils from keras_cv import version_check from keras_cv.core import ConstantFactorSampler from keras_cv.core import FactorSampler from keras_cv.core import NormalFactorSampler from keras_cv.core import UniformFactorSampler version_check.check_tf_version() __version__ = "0.2.0" Update back to dev tag
# Copyright 2022 The KerasCV Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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 keras_cv import layers from keras_cv import metrics from keras_cv import utils from keras_cv import version_check from keras_cv.core import ConstantFactorSampler from keras_cv.core import FactorSampler from keras_cv.core import NormalFactorSampler from keras_cv.core import UniformFactorSampler version_check.check_tf_version() __version__ = "0.2.0dev"
<commit_before># Copyright 2022 The KerasCV Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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 keras_cv import layers from keras_cv import metrics from keras_cv import utils from keras_cv import version_check from keras_cv.core import ConstantFactorSampler from keras_cv.core import FactorSampler from keras_cv.core import NormalFactorSampler from keras_cv.core import UniformFactorSampler version_check.check_tf_version() __version__ = "0.2.0" <commit_msg>Update back to dev tag<commit_after>
# Copyright 2022 The KerasCV Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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 keras_cv import layers from keras_cv import metrics from keras_cv import utils from keras_cv import version_check from keras_cv.core import ConstantFactorSampler from keras_cv.core import FactorSampler from keras_cv.core import NormalFactorSampler from keras_cv.core import UniformFactorSampler version_check.check_tf_version() __version__ = "0.2.0dev"
# Copyright 2022 The KerasCV Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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 keras_cv import layers from keras_cv import metrics from keras_cv import utils from keras_cv import version_check from keras_cv.core import ConstantFactorSampler from keras_cv.core import FactorSampler from keras_cv.core import NormalFactorSampler from keras_cv.core import UniformFactorSampler version_check.check_tf_version() __version__ = "0.2.0" Update back to dev tag# Copyright 2022 The KerasCV Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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 keras_cv import layers from keras_cv import metrics from keras_cv import utils from keras_cv import version_check from keras_cv.core import ConstantFactorSampler from keras_cv.core import FactorSampler from keras_cv.core import NormalFactorSampler from keras_cv.core import UniformFactorSampler version_check.check_tf_version() __version__ = "0.2.0dev"
<commit_before># Copyright 2022 The KerasCV Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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 keras_cv import layers from keras_cv import metrics from keras_cv import utils from keras_cv import version_check from keras_cv.core import ConstantFactorSampler from keras_cv.core import FactorSampler from keras_cv.core import NormalFactorSampler from keras_cv.core import UniformFactorSampler version_check.check_tf_version() __version__ = "0.2.0" <commit_msg>Update back to dev tag<commit_after># Copyright 2022 The KerasCV Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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 keras_cv import layers from keras_cv import metrics from keras_cv import utils from keras_cv import version_check from keras_cv.core import ConstantFactorSampler from keras_cv.core import FactorSampler from keras_cv.core import NormalFactorSampler from keras_cv.core import UniformFactorSampler version_check.check_tf_version() __version__ = "0.2.0dev"
a6e6c32fc8455303c44cebdfa7507300d298aa24
mediacrush/mcmanage/files.py
mediacrush/mcmanage/files.py
from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] f = File.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.")
from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] if hash.startswith("./"): hash = hash[2:] f = File.from_hash(hash) if not f: print("%r is not a valid file." % hash) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.")
Add support for ./hash to mcmanage
Add support for ./hash to mcmanage
Python
mit
roderickm/MediaCrush,roderickm/MediaCrush,nerdzeu/NERDZCrush,roderickm/MediaCrush,MediaCrush/MediaCrush,nerdzeu/NERDZCrush,MediaCrush/MediaCrush,nerdzeu/NERDZCrush
from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] f = File.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.") Add support for ./hash to mcmanage
from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] if hash.startswith("./"): hash = hash[2:] f = File.from_hash(hash) if not f: print("%r is not a valid file." % hash) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.")
<commit_before>from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] f = File.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.") <commit_msg>Add support for ./hash to mcmanage<commit_after>
from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] if hash.startswith("./"): hash = hash[2:] f = File.from_hash(hash) if not f: print("%r is not a valid file." % hash) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.")
from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] f = File.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.") Add support for ./hash to mcmanagefrom ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] if hash.startswith("./"): hash = hash[2:] f = File.from_hash(hash) if not f: print("%r is not a valid file." % hash) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.")
<commit_before>from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] f = File.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.") <commit_msg>Add support for ./hash to mcmanage<commit_after>from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] if hash.startswith("./"): hash = hash[2:] f = File.from_hash(hash) if not f: print("%r is not a valid file." % hash) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.")
34fbab0a31956af0572c31612f359608a8819360
models/phase3_eval/assemble_cx.py
models/phase3_eval/assemble_cx.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from os.path import join as pjoin from indra.assemblers import CxAssembler import indra.tools.assemble_corpus as ac def assemble_cx(stmts, out_file): """Return a CX assembler.""" stmts = ac.filter_belief(stmts, 0.95) stmts = ac.filter_top_level(stmts) stmts = ac.strip_agent_context(stmts) ca = CxAssembler() ca.add_statements(stmts) model = ca.make_model() ca.save_model(out_file) return ca
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from os.path import join as pjoin from indra.assemblers import CxAssembler import indra.tools.assemble_corpus as ac def assemble_cx(stmts, out_file): """Return a CX assembler.""" stmts = ac.filter_belief(stmts, 0.95) stmts = ac.filter_top_level(stmts) ca = CxAssembler() ca.add_statements(stmts) model = ca.make_model() ca.save_model(out_file) return ca
Remove strip context for CX assembly
Remove strip context for CX assembly
Python
bsd-2-clause
pvtodorov/indra,bgyori/indra,pvtodorov/indra,johnbachman/belpy,pvtodorov/indra,johnbachman/belpy,johnbachman/belpy,sorgerlab/indra,sorgerlab/indra,pvtodorov/indra,bgyori/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/belpy,johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/belpy
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from os.path import join as pjoin from indra.assemblers import CxAssembler import indra.tools.assemble_corpus as ac def assemble_cx(stmts, out_file): """Return a CX assembler.""" stmts = ac.filter_belief(stmts, 0.95) stmts = ac.filter_top_level(stmts) stmts = ac.strip_agent_context(stmts) ca = CxAssembler() ca.add_statements(stmts) model = ca.make_model() ca.save_model(out_file) return ca Remove strip context for CX assembly
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from os.path import join as pjoin from indra.assemblers import CxAssembler import indra.tools.assemble_corpus as ac def assemble_cx(stmts, out_file): """Return a CX assembler.""" stmts = ac.filter_belief(stmts, 0.95) stmts = ac.filter_top_level(stmts) ca = CxAssembler() ca.add_statements(stmts) model = ca.make_model() ca.save_model(out_file) return ca
<commit_before>from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from os.path import join as pjoin from indra.assemblers import CxAssembler import indra.tools.assemble_corpus as ac def assemble_cx(stmts, out_file): """Return a CX assembler.""" stmts = ac.filter_belief(stmts, 0.95) stmts = ac.filter_top_level(stmts) stmts = ac.strip_agent_context(stmts) ca = CxAssembler() ca.add_statements(stmts) model = ca.make_model() ca.save_model(out_file) return ca <commit_msg>Remove strip context for CX assembly<commit_after>
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from os.path import join as pjoin from indra.assemblers import CxAssembler import indra.tools.assemble_corpus as ac def assemble_cx(stmts, out_file): """Return a CX assembler.""" stmts = ac.filter_belief(stmts, 0.95) stmts = ac.filter_top_level(stmts) ca = CxAssembler() ca.add_statements(stmts) model = ca.make_model() ca.save_model(out_file) return ca
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from os.path import join as pjoin from indra.assemblers import CxAssembler import indra.tools.assemble_corpus as ac def assemble_cx(stmts, out_file): """Return a CX assembler.""" stmts = ac.filter_belief(stmts, 0.95) stmts = ac.filter_top_level(stmts) stmts = ac.strip_agent_context(stmts) ca = CxAssembler() ca.add_statements(stmts) model = ca.make_model() ca.save_model(out_file) return ca Remove strip context for CX assemblyfrom __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from os.path import join as pjoin from indra.assemblers import CxAssembler import indra.tools.assemble_corpus as ac def assemble_cx(stmts, out_file): """Return a CX assembler.""" stmts = ac.filter_belief(stmts, 0.95) stmts = ac.filter_top_level(stmts) ca = CxAssembler() ca.add_statements(stmts) model = ca.make_model() ca.save_model(out_file) return ca
<commit_before>from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from os.path import join as pjoin from indra.assemblers import CxAssembler import indra.tools.assemble_corpus as ac def assemble_cx(stmts, out_file): """Return a CX assembler.""" stmts = ac.filter_belief(stmts, 0.95) stmts = ac.filter_top_level(stmts) stmts = ac.strip_agent_context(stmts) ca = CxAssembler() ca.add_statements(stmts) model = ca.make_model() ca.save_model(out_file) return ca <commit_msg>Remove strip context for CX assembly<commit_after>from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from os.path import join as pjoin from indra.assemblers import CxAssembler import indra.tools.assemble_corpus as ac def assemble_cx(stmts, out_file): """Return a CX assembler.""" stmts = ac.filter_belief(stmts, 0.95) stmts = ac.filter_top_level(stmts) ca = CxAssembler() ca.add_statements(stmts) model = ca.make_model() ca.save_model(out_file) return ca
19f09bb432a9e2232f0c23743d75315bb2ad2295
cfgov/sheerlike/external_links.py
cfgov/sheerlike/external_links.py
import warnings from bs4 import BeautifulSoup from v1 import parse_links def process_external_links(doc): warnings.filterwarnings('ignore') for key, value in doc.iteritems(): doc[key] = _process_data(value) warnings.resetwarnings() return doc def _process_data(field): if isinstance(field, basestring): soup = BeautifulSoup(field, 'html.parser') field = parse_links(soup).encode(formatter="html") elif isinstance(field, list): for i, value in enumerate(field): field[i] = _process_data(value) elif isinstance(field, dict): for key, value in field.iteritems(): field[key] = _process_data(value) return field
import warnings from bs4 import BeautifulSoup from v1 import parse_links def process_external_links(doc): warnings.filterwarnings('ignore') for key, value in doc.iteritems(): doc[key] = _process_data(value) warnings.resetwarnings() return doc def _process_data(field): if isinstance(field, basestring): soup = BeautifulSoup(field, 'html.parser') field = parse_links(soup).encode(formatter=None) elif isinstance(field, list): for i, value in enumerate(field): field[i] = _process_data(value) elif isinstance(field, dict): for key, value in field.iteritems(): field[key] = _process_data(value) return field
Remove output formatting to get back what was put in
Remove output formatting to get back what was put in
Python
cc0-1.0
kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh
import warnings from bs4 import BeautifulSoup from v1 import parse_links def process_external_links(doc): warnings.filterwarnings('ignore') for key, value in doc.iteritems(): doc[key] = _process_data(value) warnings.resetwarnings() return doc def _process_data(field): if isinstance(field, basestring): soup = BeautifulSoup(field, 'html.parser') field = parse_links(soup).encode(formatter="html") elif isinstance(field, list): for i, value in enumerate(field): field[i] = _process_data(value) elif isinstance(field, dict): for key, value in field.iteritems(): field[key] = _process_data(value) return field Remove output formatting to get back what was put in
import warnings from bs4 import BeautifulSoup from v1 import parse_links def process_external_links(doc): warnings.filterwarnings('ignore') for key, value in doc.iteritems(): doc[key] = _process_data(value) warnings.resetwarnings() return doc def _process_data(field): if isinstance(field, basestring): soup = BeautifulSoup(field, 'html.parser') field = parse_links(soup).encode(formatter=None) elif isinstance(field, list): for i, value in enumerate(field): field[i] = _process_data(value) elif isinstance(field, dict): for key, value in field.iteritems(): field[key] = _process_data(value) return field
<commit_before>import warnings from bs4 import BeautifulSoup from v1 import parse_links def process_external_links(doc): warnings.filterwarnings('ignore') for key, value in doc.iteritems(): doc[key] = _process_data(value) warnings.resetwarnings() return doc def _process_data(field): if isinstance(field, basestring): soup = BeautifulSoup(field, 'html.parser') field = parse_links(soup).encode(formatter="html") elif isinstance(field, list): for i, value in enumerate(field): field[i] = _process_data(value) elif isinstance(field, dict): for key, value in field.iteritems(): field[key] = _process_data(value) return field <commit_msg>Remove output formatting to get back what was put in<commit_after>
import warnings from bs4 import BeautifulSoup from v1 import parse_links def process_external_links(doc): warnings.filterwarnings('ignore') for key, value in doc.iteritems(): doc[key] = _process_data(value) warnings.resetwarnings() return doc def _process_data(field): if isinstance(field, basestring): soup = BeautifulSoup(field, 'html.parser') field = parse_links(soup).encode(formatter=None) elif isinstance(field, list): for i, value in enumerate(field): field[i] = _process_data(value) elif isinstance(field, dict): for key, value in field.iteritems(): field[key] = _process_data(value) return field
import warnings from bs4 import BeautifulSoup from v1 import parse_links def process_external_links(doc): warnings.filterwarnings('ignore') for key, value in doc.iteritems(): doc[key] = _process_data(value) warnings.resetwarnings() return doc def _process_data(field): if isinstance(field, basestring): soup = BeautifulSoup(field, 'html.parser') field = parse_links(soup).encode(formatter="html") elif isinstance(field, list): for i, value in enumerate(field): field[i] = _process_data(value) elif isinstance(field, dict): for key, value in field.iteritems(): field[key] = _process_data(value) return field Remove output formatting to get back what was put inimport warnings from bs4 import BeautifulSoup from v1 import parse_links def process_external_links(doc): warnings.filterwarnings('ignore') for key, value in doc.iteritems(): doc[key] = _process_data(value) warnings.resetwarnings() return doc def _process_data(field): if isinstance(field, basestring): soup = BeautifulSoup(field, 'html.parser') field = parse_links(soup).encode(formatter=None) elif isinstance(field, list): for i, value in enumerate(field): field[i] = _process_data(value) elif isinstance(field, dict): for key, value in field.iteritems(): field[key] = _process_data(value) return field
<commit_before>import warnings from bs4 import BeautifulSoup from v1 import parse_links def process_external_links(doc): warnings.filterwarnings('ignore') for key, value in doc.iteritems(): doc[key] = _process_data(value) warnings.resetwarnings() return doc def _process_data(field): if isinstance(field, basestring): soup = BeautifulSoup(field, 'html.parser') field = parse_links(soup).encode(formatter="html") elif isinstance(field, list): for i, value in enumerate(field): field[i] = _process_data(value) elif isinstance(field, dict): for key, value in field.iteritems(): field[key] = _process_data(value) return field <commit_msg>Remove output formatting to get back what was put in<commit_after>import warnings from bs4 import BeautifulSoup from v1 import parse_links def process_external_links(doc): warnings.filterwarnings('ignore') for key, value in doc.iteritems(): doc[key] = _process_data(value) warnings.resetwarnings() return doc def _process_data(field): if isinstance(field, basestring): soup = BeautifulSoup(field, 'html.parser') field = parse_links(soup).encode(formatter=None) elif isinstance(field, list): for i, value in enumerate(field): field[i] = _process_data(value) elif isinstance(field, dict): for key, value in field.iteritems(): field[key] = _process_data(value) return field
f4286480f0fa157eb1b88b144ee57ffef7d1fc03
barython/tests/hooks/test_bspwm.py
barython/tests/hooks/test_bspwm.py
from collections import OrderedDict import pytest from barython.hooks.bspwm import BspwmHook def test_bspwm_hook_parse_event(): bh = BspwmHook() status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:" "mDVI-I-0:Od:LT") expected = OrderedDict([ ('HDMI-0', {'desktops': ['Ou'], 'focused': False, 'layout': 'T'}), ('DVI-D-0', { 'desktops': ['fo', 'f7', 'fDesktop2', 'os', 'Of', 'fp', 'oq', 'fi'], 'focused': True, 'layout': 'T' }), ('DVI-I-0', {'desktops': ['Od'], 'focused': False, 'layout': 'T'}) ]) assert expected == bh.parse_event(status)
from collections import OrderedDict import pytest from barython.hooks.bspwm import BspwmHook def test_bspwm_hook_parse_event(): bh = BspwmHook() status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:" "mDVI-I-0:Od:LT") expected = OrderedDict([ ('HDMI-0', {'desktops': ['Ou'], 'focused': False, 'layout': 'T'}), ('DVI-D-0', { 'desktops': ['fo', 'f7', 'fDesktop2', 'os', 'Of', 'fp', 'oq', 'fi'], 'focused': True, 'layout': 'T' }), ('DVI-I-0', {'desktops': ['Od'], 'focused': False, 'layout': 'T'}) ]) assert expected == bh.parse_event(status)["monitors"]
Add test for bspwm widget
Add test for bspwm widget
Python
bsd-3-clause
Anthony25/barython
from collections import OrderedDict import pytest from barython.hooks.bspwm import BspwmHook def test_bspwm_hook_parse_event(): bh = BspwmHook() status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:" "mDVI-I-0:Od:LT") expected = OrderedDict([ ('HDMI-0', {'desktops': ['Ou'], 'focused': False, 'layout': 'T'}), ('DVI-D-0', { 'desktops': ['fo', 'f7', 'fDesktop2', 'os', 'Of', 'fp', 'oq', 'fi'], 'focused': True, 'layout': 'T' }), ('DVI-I-0', {'desktops': ['Od'], 'focused': False, 'layout': 'T'}) ]) assert expected == bh.parse_event(status) Add test for bspwm widget
from collections import OrderedDict import pytest from barython.hooks.bspwm import BspwmHook def test_bspwm_hook_parse_event(): bh = BspwmHook() status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:" "mDVI-I-0:Od:LT") expected = OrderedDict([ ('HDMI-0', {'desktops': ['Ou'], 'focused': False, 'layout': 'T'}), ('DVI-D-0', { 'desktops': ['fo', 'f7', 'fDesktop2', 'os', 'Of', 'fp', 'oq', 'fi'], 'focused': True, 'layout': 'T' }), ('DVI-I-0', {'desktops': ['Od'], 'focused': False, 'layout': 'T'}) ]) assert expected == bh.parse_event(status)["monitors"]
<commit_before> from collections import OrderedDict import pytest from barython.hooks.bspwm import BspwmHook def test_bspwm_hook_parse_event(): bh = BspwmHook() status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:" "mDVI-I-0:Od:LT") expected = OrderedDict([ ('HDMI-0', {'desktops': ['Ou'], 'focused': False, 'layout': 'T'}), ('DVI-D-0', { 'desktops': ['fo', 'f7', 'fDesktop2', 'os', 'Of', 'fp', 'oq', 'fi'], 'focused': True, 'layout': 'T' }), ('DVI-I-0', {'desktops': ['Od'], 'focused': False, 'layout': 'T'}) ]) assert expected == bh.parse_event(status) <commit_msg>Add test for bspwm widget<commit_after>
from collections import OrderedDict import pytest from barython.hooks.bspwm import BspwmHook def test_bspwm_hook_parse_event(): bh = BspwmHook() status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:" "mDVI-I-0:Od:LT") expected = OrderedDict([ ('HDMI-0', {'desktops': ['Ou'], 'focused': False, 'layout': 'T'}), ('DVI-D-0', { 'desktops': ['fo', 'f7', 'fDesktop2', 'os', 'Of', 'fp', 'oq', 'fi'], 'focused': True, 'layout': 'T' }), ('DVI-I-0', {'desktops': ['Od'], 'focused': False, 'layout': 'T'}) ]) assert expected == bh.parse_event(status)["monitors"]
from collections import OrderedDict import pytest from barython.hooks.bspwm import BspwmHook def test_bspwm_hook_parse_event(): bh = BspwmHook() status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:" "mDVI-I-0:Od:LT") expected = OrderedDict([ ('HDMI-0', {'desktops': ['Ou'], 'focused': False, 'layout': 'T'}), ('DVI-D-0', { 'desktops': ['fo', 'f7', 'fDesktop2', 'os', 'Of', 'fp', 'oq', 'fi'], 'focused': True, 'layout': 'T' }), ('DVI-I-0', {'desktops': ['Od'], 'focused': False, 'layout': 'T'}) ]) assert expected == bh.parse_event(status) Add test for bspwm widget from collections import OrderedDict import pytest from barython.hooks.bspwm import BspwmHook def test_bspwm_hook_parse_event(): bh = BspwmHook() status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:" "mDVI-I-0:Od:LT") expected = OrderedDict([ ('HDMI-0', {'desktops': ['Ou'], 'focused': False, 'layout': 'T'}), ('DVI-D-0', { 'desktops': ['fo', 'f7', 'fDesktop2', 'os', 'Of', 'fp', 'oq', 'fi'], 'focused': True, 'layout': 'T' }), ('DVI-I-0', {'desktops': ['Od'], 'focused': False, 'layout': 'T'}) ]) assert expected == bh.parse_event(status)["monitors"]
<commit_before> from collections import OrderedDict import pytest from barython.hooks.bspwm import BspwmHook def test_bspwm_hook_parse_event(): bh = BspwmHook() status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:" "mDVI-I-0:Od:LT") expected = OrderedDict([ ('HDMI-0', {'desktops': ['Ou'], 'focused': False, 'layout': 'T'}), ('DVI-D-0', { 'desktops': ['fo', 'f7', 'fDesktop2', 'os', 'Of', 'fp', 'oq', 'fi'], 'focused': True, 'layout': 'T' }), ('DVI-I-0', {'desktops': ['Od'], 'focused': False, 'layout': 'T'}) ]) assert expected == bh.parse_event(status) <commit_msg>Add test for bspwm widget<commit_after> from collections import OrderedDict import pytest from barython.hooks.bspwm import BspwmHook def test_bspwm_hook_parse_event(): bh = BspwmHook() status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:" "mDVI-I-0:Od:LT") expected = OrderedDict([ ('HDMI-0', {'desktops': ['Ou'], 'focused': False, 'layout': 'T'}), ('DVI-D-0', { 'desktops': ['fo', 'f7', 'fDesktop2', 'os', 'Of', 'fp', 'oq', 'fi'], 'focused': True, 'layout': 'T' }), ('DVI-I-0', {'desktops': ['Od'], 'focused': False, 'layout': 'T'}) ]) assert expected == bh.parse_event(status)["monitors"]
ae583132ade7370595d6d9d14dba2b720c5415d6
cinemair/favorites/serializers.py
cinemair/favorites/serializers.py
from rest_framework import serializers as drf_serializers from cinemair.common.api import serializers from cinemair.shows.serializers import ShowRelatedSerializer from . import models class FavoriteSerializer(serializers.ModelSerializer): show_info = drf_serializers.SerializerMethodField() class Meta: model = models.Favorite def get_show_info(self, obj): data = ShowRelatedSerializer(obj.show).data del data["id"] return data
from rest_framework import serializers as drf_serializers from cinemair.common.api import serializers from cinemair.shows.serializers import ShowRelatedSerializer from . import models class FavoriteSerializer(serializers.ModelSerializer): show_info = drf_serializers.SerializerMethodField() class Meta: model = models.Favorite def get_show_info(self, obj): data = ShowRelatedSerializer(obj.show).data del data["id"] return data def validate_user(self, value): """ Check that the user is the same as request.user. """ if "request" in self.context: current_user = self.context["request"].user if current_user != value: raise drf_serializers.ValidationError("User must be you.") return value
Validate user when favorite a show
Validate user when favorite a show
Python
mit
Cinemair/cinemair-server,Cinemair/cinemair-server
from rest_framework import serializers as drf_serializers from cinemair.common.api import serializers from cinemair.shows.serializers import ShowRelatedSerializer from . import models class FavoriteSerializer(serializers.ModelSerializer): show_info = drf_serializers.SerializerMethodField() class Meta: model = models.Favorite def get_show_info(self, obj): data = ShowRelatedSerializer(obj.show).data del data["id"] return data Validate user when favorite a show
from rest_framework import serializers as drf_serializers from cinemair.common.api import serializers from cinemair.shows.serializers import ShowRelatedSerializer from . import models class FavoriteSerializer(serializers.ModelSerializer): show_info = drf_serializers.SerializerMethodField() class Meta: model = models.Favorite def get_show_info(self, obj): data = ShowRelatedSerializer(obj.show).data del data["id"] return data def validate_user(self, value): """ Check that the user is the same as request.user. """ if "request" in self.context: current_user = self.context["request"].user if current_user != value: raise drf_serializers.ValidationError("User must be you.") return value
<commit_before>from rest_framework import serializers as drf_serializers from cinemair.common.api import serializers from cinemair.shows.serializers import ShowRelatedSerializer from . import models class FavoriteSerializer(serializers.ModelSerializer): show_info = drf_serializers.SerializerMethodField() class Meta: model = models.Favorite def get_show_info(self, obj): data = ShowRelatedSerializer(obj.show).data del data["id"] return data <commit_msg>Validate user when favorite a show<commit_after>
from rest_framework import serializers as drf_serializers from cinemair.common.api import serializers from cinemair.shows.serializers import ShowRelatedSerializer from . import models class FavoriteSerializer(serializers.ModelSerializer): show_info = drf_serializers.SerializerMethodField() class Meta: model = models.Favorite def get_show_info(self, obj): data = ShowRelatedSerializer(obj.show).data del data["id"] return data def validate_user(self, value): """ Check that the user is the same as request.user. """ if "request" in self.context: current_user = self.context["request"].user if current_user != value: raise drf_serializers.ValidationError("User must be you.") return value
from rest_framework import serializers as drf_serializers from cinemair.common.api import serializers from cinemair.shows.serializers import ShowRelatedSerializer from . import models class FavoriteSerializer(serializers.ModelSerializer): show_info = drf_serializers.SerializerMethodField() class Meta: model = models.Favorite def get_show_info(self, obj): data = ShowRelatedSerializer(obj.show).data del data["id"] return data Validate user when favorite a showfrom rest_framework import serializers as drf_serializers from cinemair.common.api import serializers from cinemair.shows.serializers import ShowRelatedSerializer from . import models class FavoriteSerializer(serializers.ModelSerializer): show_info = drf_serializers.SerializerMethodField() class Meta: model = models.Favorite def get_show_info(self, obj): data = ShowRelatedSerializer(obj.show).data del data["id"] return data def validate_user(self, value): """ Check that the user is the same as request.user. """ if "request" in self.context: current_user = self.context["request"].user if current_user != value: raise drf_serializers.ValidationError("User must be you.") return value
<commit_before>from rest_framework import serializers as drf_serializers from cinemair.common.api import serializers from cinemair.shows.serializers import ShowRelatedSerializer from . import models class FavoriteSerializer(serializers.ModelSerializer): show_info = drf_serializers.SerializerMethodField() class Meta: model = models.Favorite def get_show_info(self, obj): data = ShowRelatedSerializer(obj.show).data del data["id"] return data <commit_msg>Validate user when favorite a show<commit_after>from rest_framework import serializers as drf_serializers from cinemair.common.api import serializers from cinemair.shows.serializers import ShowRelatedSerializer from . import models class FavoriteSerializer(serializers.ModelSerializer): show_info = drf_serializers.SerializerMethodField() class Meta: model = models.Favorite def get_show_info(self, obj): data = ShowRelatedSerializer(obj.show).data del data["id"] return data def validate_user(self, value): """ Check that the user is the same as request.user. """ if "request" in self.context: current_user = self.context["request"].user if current_user != value: raise drf_serializers.ValidationError("User must be you.") return value
82bb28f32c343e419e595aa2ca5ffb6fe6aa30ed
modules/pipeunion.py
modules/pipeunion.py
# pipeunion.py # from pipe2py import util def pipe_union(context, _INPUT, **kwargs): """This operator merges up to 5 source together. Keyword arguments: context -- pipeline context _INPUT -- source generator kwargs -- _OTHER1 - another source generator _OTHER2 etc. Yields (_OUTPUT): union of all source items """ #TODO the multiple sources should be pulled in parallel # check David Beazely for suggestions (co-routines with queues?) # or maybe use multiprocessing and Queues (perhaps over multiple servers too) #Single thread and sequential pulling will do for now... for item in _INPUT: if item == True: #i.e. this is being fed forever, i.e. not a real source so just use _OTHERs break yield item for other in kwargs: if other.startswith('_OTHER'): for item in kwargs[other]: yield item
# pipeunion.py # from pipe2py import util def pipe_union(context, _INPUT, **kwargs): """This operator merges up to 5 source together. Keyword arguments: context -- pipeline context _INPUT -- source generator kwargs -- _OTHER1 - another source generator _OTHER2 etc. Yields (_OUTPUT): union of all source items """ #TODO the multiple sources should be pulled in parallel # check David Beazely for suggestions (co-routines with queues?) # or maybe use multiprocessing and Queues (perhaps over multiple servers too) #Single thread and sequential pulling will do for now... for item in _INPUT: #this is being fed forever, i.e. not a real source so just use _OTHERs if item == True: break yield item for other in kwargs: if other.startswith('_OTHER'): for item in kwargs[other]: yield item
Fix whitespace errors and line lengths
Fix whitespace errors and line lengths
Python
mit
nerevu/riko,nerevu/riko
# pipeunion.py # from pipe2py import util def pipe_union(context, _INPUT, **kwargs): """This operator merges up to 5 source together. Keyword arguments: context -- pipeline context _INPUT -- source generator kwargs -- _OTHER1 - another source generator _OTHER2 etc. Yields (_OUTPUT): union of all source items """ #TODO the multiple sources should be pulled in parallel # check David Beazely for suggestions (co-routines with queues?) # or maybe use multiprocessing and Queues (perhaps over multiple servers too) #Single thread and sequential pulling will do for now... for item in _INPUT: if item == True: #i.e. this is being fed forever, i.e. not a real source so just use _OTHERs break yield item for other in kwargs: if other.startswith('_OTHER'): for item in kwargs[other]: yield item Fix whitespace errors and line lengths
# pipeunion.py # from pipe2py import util def pipe_union(context, _INPUT, **kwargs): """This operator merges up to 5 source together. Keyword arguments: context -- pipeline context _INPUT -- source generator kwargs -- _OTHER1 - another source generator _OTHER2 etc. Yields (_OUTPUT): union of all source items """ #TODO the multiple sources should be pulled in parallel # check David Beazely for suggestions (co-routines with queues?) # or maybe use multiprocessing and Queues (perhaps over multiple servers too) #Single thread and sequential pulling will do for now... for item in _INPUT: #this is being fed forever, i.e. not a real source so just use _OTHERs if item == True: break yield item for other in kwargs: if other.startswith('_OTHER'): for item in kwargs[other]: yield item
<commit_before># pipeunion.py # from pipe2py import util def pipe_union(context, _INPUT, **kwargs): """This operator merges up to 5 source together. Keyword arguments: context -- pipeline context _INPUT -- source generator kwargs -- _OTHER1 - another source generator _OTHER2 etc. Yields (_OUTPUT): union of all source items """ #TODO the multiple sources should be pulled in parallel # check David Beazely for suggestions (co-routines with queues?) # or maybe use multiprocessing and Queues (perhaps over multiple servers too) #Single thread and sequential pulling will do for now... for item in _INPUT: if item == True: #i.e. this is being fed forever, i.e. not a real source so just use _OTHERs break yield item for other in kwargs: if other.startswith('_OTHER'): for item in kwargs[other]: yield item <commit_msg>Fix whitespace errors and line lengths<commit_after>
# pipeunion.py # from pipe2py import util def pipe_union(context, _INPUT, **kwargs): """This operator merges up to 5 source together. Keyword arguments: context -- pipeline context _INPUT -- source generator kwargs -- _OTHER1 - another source generator _OTHER2 etc. Yields (_OUTPUT): union of all source items """ #TODO the multiple sources should be pulled in parallel # check David Beazely for suggestions (co-routines with queues?) # or maybe use multiprocessing and Queues (perhaps over multiple servers too) #Single thread and sequential pulling will do for now... for item in _INPUT: #this is being fed forever, i.e. not a real source so just use _OTHERs if item == True: break yield item for other in kwargs: if other.startswith('_OTHER'): for item in kwargs[other]: yield item
# pipeunion.py # from pipe2py import util def pipe_union(context, _INPUT, **kwargs): """This operator merges up to 5 source together. Keyword arguments: context -- pipeline context _INPUT -- source generator kwargs -- _OTHER1 - another source generator _OTHER2 etc. Yields (_OUTPUT): union of all source items """ #TODO the multiple sources should be pulled in parallel # check David Beazely for suggestions (co-routines with queues?) # or maybe use multiprocessing and Queues (perhaps over multiple servers too) #Single thread and sequential pulling will do for now... for item in _INPUT: if item == True: #i.e. this is being fed forever, i.e. not a real source so just use _OTHERs break yield item for other in kwargs: if other.startswith('_OTHER'): for item in kwargs[other]: yield item Fix whitespace errors and line lengths# pipeunion.py # from pipe2py import util def pipe_union(context, _INPUT, **kwargs): """This operator merges up to 5 source together. Keyword arguments: context -- pipeline context _INPUT -- source generator kwargs -- _OTHER1 - another source generator _OTHER2 etc. Yields (_OUTPUT): union of all source items """ #TODO the multiple sources should be pulled in parallel # check David Beazely for suggestions (co-routines with queues?) # or maybe use multiprocessing and Queues (perhaps over multiple servers too) #Single thread and sequential pulling will do for now... for item in _INPUT: #this is being fed forever, i.e. not a real source so just use _OTHERs if item == True: break yield item for other in kwargs: if other.startswith('_OTHER'): for item in kwargs[other]: yield item
<commit_before># pipeunion.py # from pipe2py import util def pipe_union(context, _INPUT, **kwargs): """This operator merges up to 5 source together. Keyword arguments: context -- pipeline context _INPUT -- source generator kwargs -- _OTHER1 - another source generator _OTHER2 etc. Yields (_OUTPUT): union of all source items """ #TODO the multiple sources should be pulled in parallel # check David Beazely for suggestions (co-routines with queues?) # or maybe use multiprocessing and Queues (perhaps over multiple servers too) #Single thread and sequential pulling will do for now... for item in _INPUT: if item == True: #i.e. this is being fed forever, i.e. not a real source so just use _OTHERs break yield item for other in kwargs: if other.startswith('_OTHER'): for item in kwargs[other]: yield item <commit_msg>Fix whitespace errors and line lengths<commit_after># pipeunion.py # from pipe2py import util def pipe_union(context, _INPUT, **kwargs): """This operator merges up to 5 source together. Keyword arguments: context -- pipeline context _INPUT -- source generator kwargs -- _OTHER1 - another source generator _OTHER2 etc. Yields (_OUTPUT): union of all source items """ #TODO the multiple sources should be pulled in parallel # check David Beazely for suggestions (co-routines with queues?) # or maybe use multiprocessing and Queues (perhaps over multiple servers too) #Single thread and sequential pulling will do for now... for item in _INPUT: #this is being fed forever, i.e. not a real source so just use _OTHERs if item == True: break yield item for other in kwargs: if other.startswith('_OTHER'): for item in kwargs[other]: yield item
48750d7fef9a6045251f72f1064b1cc825dfdb5f
mysite/testrunner.py
mysite/testrunner.py
from django.conf import settings import xmlrunner.extra.djangotestrunner from django.test.simple import run_tests import os def run(*args, **kwargs): settings.CELERY_ALWAYS_EAGER = True if os.environ.get('USER', 'unknown') == 'hudson': # Hudson should run with xmlrunner because he consumes JUnit-style xml # test reports. return xmlrunner.extra.djangotestrunner.run_tests(*args, **kwargs) else: # Those of us unfortunate enough not to have been born Hudson should # use the normal test runner, because xmlrunner swallows input, # preventing interaction with pdb.set_trace(), which makes debugging a # pain! return run_tests(*args, **kwargs)
from django.conf import settings import xmlrunner.extra.djangotestrunner from django.test.simple import run_tests import tempfile import os import datetime def override_settings_for_testing(): settings.CELERY_ALWAYS_EAGER = True settings.SVN_REPO_PATH = tempfile.mkdtemp( prefix='svn_repo_path_' + datetime.datetime.now().isoformat().replace(':', '.')) def run(*args, **kwargs): override_settings_for_testing() if os.environ.get('USER', 'unknown') == 'hudson': # Hudson should run with xmlrunner because he consumes # JUnit-style xml test reports. return xmlrunner.extra.djangotestrunner.run_tests(*args, **kwargs) else: # Those of us unfortunate enough not to have been born # Hudson should use the normal test runner, because # xmlrunner swallows input, preventing interaction with # pdb.set_trace(), which makes debugging a pain! return run_tests(*args, **kwargs)
Add a function called override_settings_for_testing
Add a function called override_settings_for_testing In it, set SVN_REPO_PATH to a tempfile.mkdtemp() path.
Python
agpl-3.0
willingc/oh-mainline,campbe13/openhatch,eeshangarg/oh-mainline,openhatch/oh-mainline,nirmeshk/oh-mainline,campbe13/openhatch,nirmeshk/oh-mainline,Changaco/oh-mainline,onceuponatimeforever/oh-mainline,ojengwa/oh-mainline,vipul-sharma20/oh-mainline,sudheesh001/oh-mainline,SnappleCap/oh-mainline,campbe13/openhatch,sudheesh001/oh-mainline,openhatch/oh-mainline,nirmeshk/oh-mainline,ehashman/oh-mainline,SnappleCap/oh-mainline,onceuponatimeforever/oh-mainline,heeraj123/oh-mainline,willingc/oh-mainline,onceuponatimeforever/oh-mainline,mzdaniel/oh-mainline,openhatch/oh-mainline,heeraj123/oh-mainline,ehashman/oh-mainline,heeraj123/oh-mainline,waseem18/oh-mainline,Changaco/oh-mainline,Changaco/oh-mainline,vipul-sharma20/oh-mainline,moijes12/oh-mainline,mzdaniel/oh-mainline,waseem18/oh-mainline,mzdaniel/oh-mainline,SnappleCap/oh-mainline,sudheesh001/oh-mainline,willingc/oh-mainline,heeraj123/oh-mainline,SnappleCap/oh-mainline,campbe13/openhatch,openhatch/oh-mainline,moijes12/oh-mainline,jledbetter/openhatch,Changaco/oh-mainline,jledbetter/openhatch,sudheesh001/oh-mainline,mzdaniel/oh-mainline,waseem18/oh-mainline,willingc/oh-mainline,vipul-sharma20/oh-mainline,eeshangarg/oh-mainline,ojengwa/oh-mainline,waseem18/oh-mainline,ojengwa/oh-mainline,moijes12/oh-mainline,waseem18/oh-mainline,moijes12/oh-mainline,jledbetter/openhatch,eeshangarg/oh-mainline,mzdaniel/oh-mainline,jledbetter/openhatch,ehashman/oh-mainline,jledbetter/openhatch,onceuponatimeforever/oh-mainline,campbe13/openhatch,sudheesh001/oh-mainline,ehashman/oh-mainline,willingc/oh-mainline,mzdaniel/oh-mainline,vipul-sharma20/oh-mainline,ojengwa/oh-mainline,ojengwa/oh-mainline,moijes12/oh-mainline,vipul-sharma20/oh-mainline,SnappleCap/oh-mainline,eeshangarg/oh-mainline,ehashman/oh-mainline,openhatch/oh-mainline,nirmeshk/oh-mainline,eeshangarg/oh-mainline,onceuponatimeforever/oh-mainline,heeraj123/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,nirmeshk/oh-mainline
from django.conf import settings import xmlrunner.extra.djangotestrunner from django.test.simple import run_tests import os def run(*args, **kwargs): settings.CELERY_ALWAYS_EAGER = True if os.environ.get('USER', 'unknown') == 'hudson': # Hudson should run with xmlrunner because he consumes JUnit-style xml # test reports. return xmlrunner.extra.djangotestrunner.run_tests(*args, **kwargs) else: # Those of us unfortunate enough not to have been born Hudson should # use the normal test runner, because xmlrunner swallows input, # preventing interaction with pdb.set_trace(), which makes debugging a # pain! return run_tests(*args, **kwargs) Add a function called override_settings_for_testing In it, set SVN_REPO_PATH to a tempfile.mkdtemp() path.
from django.conf import settings import xmlrunner.extra.djangotestrunner from django.test.simple import run_tests import tempfile import os import datetime def override_settings_for_testing(): settings.CELERY_ALWAYS_EAGER = True settings.SVN_REPO_PATH = tempfile.mkdtemp( prefix='svn_repo_path_' + datetime.datetime.now().isoformat().replace(':', '.')) def run(*args, **kwargs): override_settings_for_testing() if os.environ.get('USER', 'unknown') == 'hudson': # Hudson should run with xmlrunner because he consumes # JUnit-style xml test reports. return xmlrunner.extra.djangotestrunner.run_tests(*args, **kwargs) else: # Those of us unfortunate enough not to have been born # Hudson should use the normal test runner, because # xmlrunner swallows input, preventing interaction with # pdb.set_trace(), which makes debugging a pain! return run_tests(*args, **kwargs)
<commit_before>from django.conf import settings import xmlrunner.extra.djangotestrunner from django.test.simple import run_tests import os def run(*args, **kwargs): settings.CELERY_ALWAYS_EAGER = True if os.environ.get('USER', 'unknown') == 'hudson': # Hudson should run with xmlrunner because he consumes JUnit-style xml # test reports. return xmlrunner.extra.djangotestrunner.run_tests(*args, **kwargs) else: # Those of us unfortunate enough not to have been born Hudson should # use the normal test runner, because xmlrunner swallows input, # preventing interaction with pdb.set_trace(), which makes debugging a # pain! return run_tests(*args, **kwargs) <commit_msg>Add a function called override_settings_for_testing In it, set SVN_REPO_PATH to a tempfile.mkdtemp() path.<commit_after>
from django.conf import settings import xmlrunner.extra.djangotestrunner from django.test.simple import run_tests import tempfile import os import datetime def override_settings_for_testing(): settings.CELERY_ALWAYS_EAGER = True settings.SVN_REPO_PATH = tempfile.mkdtemp( prefix='svn_repo_path_' + datetime.datetime.now().isoformat().replace(':', '.')) def run(*args, **kwargs): override_settings_for_testing() if os.environ.get('USER', 'unknown') == 'hudson': # Hudson should run with xmlrunner because he consumes # JUnit-style xml test reports. return xmlrunner.extra.djangotestrunner.run_tests(*args, **kwargs) else: # Those of us unfortunate enough not to have been born # Hudson should use the normal test runner, because # xmlrunner swallows input, preventing interaction with # pdb.set_trace(), which makes debugging a pain! return run_tests(*args, **kwargs)
from django.conf import settings import xmlrunner.extra.djangotestrunner from django.test.simple import run_tests import os def run(*args, **kwargs): settings.CELERY_ALWAYS_EAGER = True if os.environ.get('USER', 'unknown') == 'hudson': # Hudson should run with xmlrunner because he consumes JUnit-style xml # test reports. return xmlrunner.extra.djangotestrunner.run_tests(*args, **kwargs) else: # Those of us unfortunate enough not to have been born Hudson should # use the normal test runner, because xmlrunner swallows input, # preventing interaction with pdb.set_trace(), which makes debugging a # pain! return run_tests(*args, **kwargs) Add a function called override_settings_for_testing In it, set SVN_REPO_PATH to a tempfile.mkdtemp() path.from django.conf import settings import xmlrunner.extra.djangotestrunner from django.test.simple import run_tests import tempfile import os import datetime def override_settings_for_testing(): settings.CELERY_ALWAYS_EAGER = True settings.SVN_REPO_PATH = tempfile.mkdtemp( prefix='svn_repo_path_' + datetime.datetime.now().isoformat().replace(':', '.')) def run(*args, **kwargs): override_settings_for_testing() if os.environ.get('USER', 'unknown') == 'hudson': # Hudson should run with xmlrunner because he consumes # JUnit-style xml test reports. return xmlrunner.extra.djangotestrunner.run_tests(*args, **kwargs) else: # Those of us unfortunate enough not to have been born # Hudson should use the normal test runner, because # xmlrunner swallows input, preventing interaction with # pdb.set_trace(), which makes debugging a pain! return run_tests(*args, **kwargs)
<commit_before>from django.conf import settings import xmlrunner.extra.djangotestrunner from django.test.simple import run_tests import os def run(*args, **kwargs): settings.CELERY_ALWAYS_EAGER = True if os.environ.get('USER', 'unknown') == 'hudson': # Hudson should run with xmlrunner because he consumes JUnit-style xml # test reports. return xmlrunner.extra.djangotestrunner.run_tests(*args, **kwargs) else: # Those of us unfortunate enough not to have been born Hudson should # use the normal test runner, because xmlrunner swallows input, # preventing interaction with pdb.set_trace(), which makes debugging a # pain! return run_tests(*args, **kwargs) <commit_msg>Add a function called override_settings_for_testing In it, set SVN_REPO_PATH to a tempfile.mkdtemp() path.<commit_after>from django.conf import settings import xmlrunner.extra.djangotestrunner from django.test.simple import run_tests import tempfile import os import datetime def override_settings_for_testing(): settings.CELERY_ALWAYS_EAGER = True settings.SVN_REPO_PATH = tempfile.mkdtemp( prefix='svn_repo_path_' + datetime.datetime.now().isoformat().replace(':', '.')) def run(*args, **kwargs): override_settings_for_testing() if os.environ.get('USER', 'unknown') == 'hudson': # Hudson should run with xmlrunner because he consumes # JUnit-style xml test reports. return xmlrunner.extra.djangotestrunner.run_tests(*args, **kwargs) else: # Those of us unfortunate enough not to have been born # Hudson should use the normal test runner, because # xmlrunner swallows input, preventing interaction with # pdb.set_trace(), which makes debugging a pain! return run_tests(*args, **kwargs)
d4d73fe7d5e83c65d9abbf59ea14ed60eb23a83f
poem_reader.py
poem_reader.py
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Reader for the newspaper XML files """ import argparse from lxml import etree argparser = argparse.ArgumentParser(description="Newspaper XML parser", fromfile_prefix_chars='@') argparser.add_argument("dataroot", help="Path to DHH 17 newspapers directory") args = argparser.parse_args() data_root = args.dataroot with open(data_root + 'newspapers/fin/1854/1457-4616/1457-4616_1854-08-01_31/alto/1457-4616_1854-08-01_31_001.xml', 'r') as f: tree = etree.parse(f) root = tree.getroot() print(root.tag)
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Reader for the newspaper XML files """ import argparse import glob from lxml import etree argparser = argparse.ArgumentParser(description="Newspaper XML parser", fromfile_prefix_chars='@') argparser.add_argument("dataroot", help="Path to DHH 17 newspapers directory") args = argparser.parse_args() data_root = args.dataroot def read_xml_directory(path): """ Read XML files from path, parse them, and return them as list """ files = glob.glob(path + "*.xml") xmls = [] for xmlfile in files: with open(xmlfile, 'r') as f: xmls.append(etree.parse(f)) return xmls def find_by_block_id(xmls, block_id): """ Find an element by block_id from a list of lxml trees """ block_xpath = etree.XPath("//*[@ID='{id}']".format(id=block_id)) for xml in xmls: elements = block_xpath(xml) if elements: return elements[0] some_dir = data_root + 'newspapers/fin/1854/1457-4616/1457-4616_1854-08-01_31/alto/' xmls = read_xml_directory(some_dir) print(etree.tostring(find_by_block_id(xmls, 'P2_TB00001')))
Read XML files from a directory and find textblock by id
Read XML files from a directory and find textblock by id
Python
mit
dhh17/categories_norms_genres,dhh17/categories_norms_genres,dhh17/categories_norms_genres
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Reader for the newspaper XML files """ import argparse from lxml import etree argparser = argparse.ArgumentParser(description="Newspaper XML parser", fromfile_prefix_chars='@') argparser.add_argument("dataroot", help="Path to DHH 17 newspapers directory") args = argparser.parse_args() data_root = args.dataroot with open(data_root + 'newspapers/fin/1854/1457-4616/1457-4616_1854-08-01_31/alto/1457-4616_1854-08-01_31_001.xml', 'r') as f: tree = etree.parse(f) root = tree.getroot() print(root.tag) Read XML files from a directory and find textblock by id
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Reader for the newspaper XML files """ import argparse import glob from lxml import etree argparser = argparse.ArgumentParser(description="Newspaper XML parser", fromfile_prefix_chars='@') argparser.add_argument("dataroot", help="Path to DHH 17 newspapers directory") args = argparser.parse_args() data_root = args.dataroot def read_xml_directory(path): """ Read XML files from path, parse them, and return them as list """ files = glob.glob(path + "*.xml") xmls = [] for xmlfile in files: with open(xmlfile, 'r') as f: xmls.append(etree.parse(f)) return xmls def find_by_block_id(xmls, block_id): """ Find an element by block_id from a list of lxml trees """ block_xpath = etree.XPath("//*[@ID='{id}']".format(id=block_id)) for xml in xmls: elements = block_xpath(xml) if elements: return elements[0] some_dir = data_root + 'newspapers/fin/1854/1457-4616/1457-4616_1854-08-01_31/alto/' xmls = read_xml_directory(some_dir) print(etree.tostring(find_by_block_id(xmls, 'P2_TB00001')))
<commit_before>#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Reader for the newspaper XML files """ import argparse from lxml import etree argparser = argparse.ArgumentParser(description="Newspaper XML parser", fromfile_prefix_chars='@') argparser.add_argument("dataroot", help="Path to DHH 17 newspapers directory") args = argparser.parse_args() data_root = args.dataroot with open(data_root + 'newspapers/fin/1854/1457-4616/1457-4616_1854-08-01_31/alto/1457-4616_1854-08-01_31_001.xml', 'r') as f: tree = etree.parse(f) root = tree.getroot() print(root.tag) <commit_msg>Read XML files from a directory and find textblock by id<commit_after>
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Reader for the newspaper XML files """ import argparse import glob from lxml import etree argparser = argparse.ArgumentParser(description="Newspaper XML parser", fromfile_prefix_chars='@') argparser.add_argument("dataroot", help="Path to DHH 17 newspapers directory") args = argparser.parse_args() data_root = args.dataroot def read_xml_directory(path): """ Read XML files from path, parse them, and return them as list """ files = glob.glob(path + "*.xml") xmls = [] for xmlfile in files: with open(xmlfile, 'r') as f: xmls.append(etree.parse(f)) return xmls def find_by_block_id(xmls, block_id): """ Find an element by block_id from a list of lxml trees """ block_xpath = etree.XPath("//*[@ID='{id}']".format(id=block_id)) for xml in xmls: elements = block_xpath(xml) if elements: return elements[0] some_dir = data_root + 'newspapers/fin/1854/1457-4616/1457-4616_1854-08-01_31/alto/' xmls = read_xml_directory(some_dir) print(etree.tostring(find_by_block_id(xmls, 'P2_TB00001')))
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Reader for the newspaper XML files """ import argparse from lxml import etree argparser = argparse.ArgumentParser(description="Newspaper XML parser", fromfile_prefix_chars='@') argparser.add_argument("dataroot", help="Path to DHH 17 newspapers directory") args = argparser.parse_args() data_root = args.dataroot with open(data_root + 'newspapers/fin/1854/1457-4616/1457-4616_1854-08-01_31/alto/1457-4616_1854-08-01_31_001.xml', 'r') as f: tree = etree.parse(f) root = tree.getroot() print(root.tag) Read XML files from a directory and find textblock by id#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Reader for the newspaper XML files """ import argparse import glob from lxml import etree argparser = argparse.ArgumentParser(description="Newspaper XML parser", fromfile_prefix_chars='@') argparser.add_argument("dataroot", help="Path to DHH 17 newspapers directory") args = argparser.parse_args() data_root = args.dataroot def read_xml_directory(path): """ Read XML files from path, parse them, and return them as list """ files = glob.glob(path + "*.xml") xmls = [] for xmlfile in files: with open(xmlfile, 'r') as f: xmls.append(etree.parse(f)) return xmls def find_by_block_id(xmls, block_id): """ Find an element by block_id from a list of lxml trees """ block_xpath = etree.XPath("//*[@ID='{id}']".format(id=block_id)) for xml in xmls: elements = block_xpath(xml) if elements: return elements[0] some_dir = data_root + 'newspapers/fin/1854/1457-4616/1457-4616_1854-08-01_31/alto/' xmls = read_xml_directory(some_dir) print(etree.tostring(find_by_block_id(xmls, 'P2_TB00001')))
<commit_before>#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Reader for the newspaper XML files """ import argparse from lxml import etree argparser = argparse.ArgumentParser(description="Newspaper XML parser", fromfile_prefix_chars='@') argparser.add_argument("dataroot", help="Path to DHH 17 newspapers directory") args = argparser.parse_args() data_root = args.dataroot with open(data_root + 'newspapers/fin/1854/1457-4616/1457-4616_1854-08-01_31/alto/1457-4616_1854-08-01_31_001.xml', 'r') as f: tree = etree.parse(f) root = tree.getroot() print(root.tag) <commit_msg>Read XML files from a directory and find textblock by id<commit_after>#!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ Reader for the newspaper XML files """ import argparse import glob from lxml import etree argparser = argparse.ArgumentParser(description="Newspaper XML parser", fromfile_prefix_chars='@') argparser.add_argument("dataroot", help="Path to DHH 17 newspapers directory") args = argparser.parse_args() data_root = args.dataroot def read_xml_directory(path): """ Read XML files from path, parse them, and return them as list """ files = glob.glob(path + "*.xml") xmls = [] for xmlfile in files: with open(xmlfile, 'r') as f: xmls.append(etree.parse(f)) return xmls def find_by_block_id(xmls, block_id): """ Find an element by block_id from a list of lxml trees """ block_xpath = etree.XPath("//*[@ID='{id}']".format(id=block_id)) for xml in xmls: elements = block_xpath(xml) if elements: return elements[0] some_dir = data_root + 'newspapers/fin/1854/1457-4616/1457-4616_1854-08-01_31/alto/' xmls = read_xml_directory(some_dir) print(etree.tostring(find_by_block_id(xmls, 'P2_TB00001')))
51bbc760d0be6f21b1526752f1b4ab5a76c82917
diff_array/diff_array.py
diff_array/diff_array.py
def array_diff(a, b): return a if not b else [x for x in a if x != b[0]]
def array_diff(a, b): return [x for x in a if x not in set(b)]
Change code because failed the random test
Change code because failed the random test
Python
mit
lowks/codewars-katas-python
def array_diff(a, b): return a if not b else [x for x in a if x != b[0]] Change code because failed the random test
def array_diff(a, b): return [x for x in a if x not in set(b)]
<commit_before>def array_diff(a, b): return a if not b else [x for x in a if x != b[0]] <commit_msg>Change code because failed the random test<commit_after>
def array_diff(a, b): return [x for x in a if x not in set(b)]
def array_diff(a, b): return a if not b else [x for x in a if x != b[0]] Change code because failed the random testdef array_diff(a, b): return [x for x in a if x not in set(b)]
<commit_before>def array_diff(a, b): return a if not b else [x for x in a if x != b[0]] <commit_msg>Change code because failed the random test<commit_after>def array_diff(a, b): return [x for x in a if x not in set(b)]
65c712464813ba41b564aa3e0116e60805f6681e
storyboard/api/v1/system_info.py
storyboard/api/v1/system_info.py
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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 pbr.version import VersionInfo from pecan import rest from pecan.secure import secure from storyboard.api.auth import authorization_checks as checks from storyboard.api.v1 import wmodels import wsmeext.pecan as wsme_pecan CONF = cfg.CONF class SystemInfoController(rest.RestController): """REST controller for sysinfo endpoint. Provides Get methods for System information. """ @secure(checks.guest) @wsme_pecan.wsexpose(wmodels.SystemInfo) def get(self): """Retrieve the Storyboard system information. """ sb_ver = VersionInfo('storyboard') return wmodels.SystemInfo(version=sb_ver.version_string())
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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 pbr.version import VersionInfo from pecan import rest from pecan.secure import secure from storyboard.api.auth import authorization_checks as checks from storyboard.api.v1 import wmodels import wsmeext.pecan as wsme_pecan CONF = cfg.CONF class SystemInfoController(rest.RestController): """REST controller for sysinfo endpoint. Provides Get methods for System information. """ @secure(checks.guest) @wsme_pecan.wsexpose(wmodels.SystemInfo) def get(self): """Retrieve the Storyboard system information. Example:: curl https://my.example.org/api/v1/systeminfo """ sb_ver = VersionInfo('storyboard') return wmodels.SystemInfo(version=sb_ver.version_string())
Add example commands for the Systeminfo api
Add example commands for the Systeminfo api Currently the api documentation does not include example commands. It would be very friendly for our users to have some example commands to follow and use the api. This patch adds examples to the Systeminfo section of the api documentation. Change-Id: Ic3d56d207db696100754a5a1fd5764f2f3f0a7f3
Python
apache-2.0
ColdrickSotK/storyboard,ColdrickSotK/storyboard,ColdrickSotK/storyboard
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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 pbr.version import VersionInfo from pecan import rest from pecan.secure import secure from storyboard.api.auth import authorization_checks as checks from storyboard.api.v1 import wmodels import wsmeext.pecan as wsme_pecan CONF = cfg.CONF class SystemInfoController(rest.RestController): """REST controller for sysinfo endpoint. Provides Get methods for System information. """ @secure(checks.guest) @wsme_pecan.wsexpose(wmodels.SystemInfo) def get(self): """Retrieve the Storyboard system information. """ sb_ver = VersionInfo('storyboard') return wmodels.SystemInfo(version=sb_ver.version_string()) Add example commands for the Systeminfo api Currently the api documentation does not include example commands. It would be very friendly for our users to have some example commands to follow and use the api. This patch adds examples to the Systeminfo section of the api documentation. Change-Id: Ic3d56d207db696100754a5a1fd5764f2f3f0a7f3
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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 pbr.version import VersionInfo from pecan import rest from pecan.secure import secure from storyboard.api.auth import authorization_checks as checks from storyboard.api.v1 import wmodels import wsmeext.pecan as wsme_pecan CONF = cfg.CONF class SystemInfoController(rest.RestController): """REST controller for sysinfo endpoint. Provides Get methods for System information. """ @secure(checks.guest) @wsme_pecan.wsexpose(wmodels.SystemInfo) def get(self): """Retrieve the Storyboard system information. Example:: curl https://my.example.org/api/v1/systeminfo """ sb_ver = VersionInfo('storyboard') return wmodels.SystemInfo(version=sb_ver.version_string())
<commit_before># Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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 pbr.version import VersionInfo from pecan import rest from pecan.secure import secure from storyboard.api.auth import authorization_checks as checks from storyboard.api.v1 import wmodels import wsmeext.pecan as wsme_pecan CONF = cfg.CONF class SystemInfoController(rest.RestController): """REST controller for sysinfo endpoint. Provides Get methods for System information. """ @secure(checks.guest) @wsme_pecan.wsexpose(wmodels.SystemInfo) def get(self): """Retrieve the Storyboard system information. """ sb_ver = VersionInfo('storyboard') return wmodels.SystemInfo(version=sb_ver.version_string()) <commit_msg>Add example commands for the Systeminfo api Currently the api documentation does not include example commands. It would be very friendly for our users to have some example commands to follow and use the api. This patch adds examples to the Systeminfo section of the api documentation. Change-Id: Ic3d56d207db696100754a5a1fd5764f2f3f0a7f3<commit_after>
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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 pbr.version import VersionInfo from pecan import rest from pecan.secure import secure from storyboard.api.auth import authorization_checks as checks from storyboard.api.v1 import wmodels import wsmeext.pecan as wsme_pecan CONF = cfg.CONF class SystemInfoController(rest.RestController): """REST controller for sysinfo endpoint. Provides Get methods for System information. """ @secure(checks.guest) @wsme_pecan.wsexpose(wmodels.SystemInfo) def get(self): """Retrieve the Storyboard system information. Example:: curl https://my.example.org/api/v1/systeminfo """ sb_ver = VersionInfo('storyboard') return wmodels.SystemInfo(version=sb_ver.version_string())
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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 pbr.version import VersionInfo from pecan import rest from pecan.secure import secure from storyboard.api.auth import authorization_checks as checks from storyboard.api.v1 import wmodels import wsmeext.pecan as wsme_pecan CONF = cfg.CONF class SystemInfoController(rest.RestController): """REST controller for sysinfo endpoint. Provides Get methods for System information. """ @secure(checks.guest) @wsme_pecan.wsexpose(wmodels.SystemInfo) def get(self): """Retrieve the Storyboard system information. """ sb_ver = VersionInfo('storyboard') return wmodels.SystemInfo(version=sb_ver.version_string()) Add example commands for the Systeminfo api Currently the api documentation does not include example commands. It would be very friendly for our users to have some example commands to follow and use the api. This patch adds examples to the Systeminfo section of the api documentation. Change-Id: Ic3d56d207db696100754a5a1fd5764f2f3f0a7f3# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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 pbr.version import VersionInfo from pecan import rest from pecan.secure import secure from storyboard.api.auth import authorization_checks as checks from storyboard.api.v1 import wmodels import wsmeext.pecan as wsme_pecan CONF = cfg.CONF class SystemInfoController(rest.RestController): """REST controller for sysinfo endpoint. Provides Get methods for System information. """ @secure(checks.guest) @wsme_pecan.wsexpose(wmodels.SystemInfo) def get(self): """Retrieve the Storyboard system information. Example:: curl https://my.example.org/api/v1/systeminfo """ sb_ver = VersionInfo('storyboard') return wmodels.SystemInfo(version=sb_ver.version_string())
<commit_before># Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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 pbr.version import VersionInfo from pecan import rest from pecan.secure import secure from storyboard.api.auth import authorization_checks as checks from storyboard.api.v1 import wmodels import wsmeext.pecan as wsme_pecan CONF = cfg.CONF class SystemInfoController(rest.RestController): """REST controller for sysinfo endpoint. Provides Get methods for System information. """ @secure(checks.guest) @wsme_pecan.wsexpose(wmodels.SystemInfo) def get(self): """Retrieve the Storyboard system information. """ sb_ver = VersionInfo('storyboard') return wmodels.SystemInfo(version=sb_ver.version_string()) <commit_msg>Add example commands for the Systeminfo api Currently the api documentation does not include example commands. It would be very friendly for our users to have some example commands to follow and use the api. This patch adds examples to the Systeminfo section of the api documentation. Change-Id: Ic3d56d207db696100754a5a1fd5764f2f3f0a7f3<commit_after># Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # 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 pbr.version import VersionInfo from pecan import rest from pecan.secure import secure from storyboard.api.auth import authorization_checks as checks from storyboard.api.v1 import wmodels import wsmeext.pecan as wsme_pecan CONF = cfg.CONF class SystemInfoController(rest.RestController): """REST controller for sysinfo endpoint. Provides Get methods for System information. """ @secure(checks.guest) @wsme_pecan.wsexpose(wmodels.SystemInfo) def get(self): """Retrieve the Storyboard system information. Example:: curl https://my.example.org/api/v1/systeminfo """ sb_ver = VersionInfo('storyboard') return wmodels.SystemInfo(version=sb_ver.version_string())
81cc39ca4c9348732a18d2f1ee7edcdbc4c61479
tests/tags/test_div.py
tests/tags/test_div.py
# -*- coding: utf-8 -*- from riot.layout import render_layout, patch_layout def test_render_div(): assert render_layout([ 'div', {}, [] ]) == [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] def test_render_div_with_div_char(): el = render_layout([ 'div', { 'char': u'-', 'top': 1, 'bottom': 1 }, [] ]) == [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] def test_patch_div(): # call div._invalidate() el1 = [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] el2 = [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] assert patch_layout(el1, el2) == [ ('.div_char', u'-'), ('.top', 1), ('.bottom', 1), ]
# -*- coding: utf-8 -*- from riot.layout import render_layout, patch_layout def test_render_div(): assert render_layout([ 'div', {}, [] ]) == [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] def test_render_div_with_opts(): assert render_layout([ 'div', { 'char': '{ opts.custom_char }', 'top': '{ opts.custom_top }', 'bottom': '{ opts.custom_bottom }', }, [] ], { 'custom_char': u'x', 'custom_top': '1', 'custom_bottom': '1', }) == [ 'div', { 'div_char': u'x', 'top': 1, 'bottom': 1, } ] def test_render_div_with_div_char(): el = render_layout([ 'div', { 'char': u'-', 'top': 1, 'bottom': 1 }, [] ]) == [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] def test_patch_div(): # call div._invalidate() el1 = [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] el2 = [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] assert patch_layout(el1, el2) == [ ('.div_char', u'-'), ('.top', 1), ('.bottom', 1), ]
Allow render opts to div.
Allow render opts to div.
Python
mit
soasme/riotpy
# -*- coding: utf-8 -*- from riot.layout import render_layout, patch_layout def test_render_div(): assert render_layout([ 'div', {}, [] ]) == [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] def test_render_div_with_div_char(): el = render_layout([ 'div', { 'char': u'-', 'top': 1, 'bottom': 1 }, [] ]) == [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] def test_patch_div(): # call div._invalidate() el1 = [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] el2 = [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] assert patch_layout(el1, el2) == [ ('.div_char', u'-'), ('.top', 1), ('.bottom', 1), ] Allow render opts to div.
# -*- coding: utf-8 -*- from riot.layout import render_layout, patch_layout def test_render_div(): assert render_layout([ 'div', {}, [] ]) == [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] def test_render_div_with_opts(): assert render_layout([ 'div', { 'char': '{ opts.custom_char }', 'top': '{ opts.custom_top }', 'bottom': '{ opts.custom_bottom }', }, [] ], { 'custom_char': u'x', 'custom_top': '1', 'custom_bottom': '1', }) == [ 'div', { 'div_char': u'x', 'top': 1, 'bottom': 1, } ] def test_render_div_with_div_char(): el = render_layout([ 'div', { 'char': u'-', 'top': 1, 'bottom': 1 }, [] ]) == [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] def test_patch_div(): # call div._invalidate() el1 = [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] el2 = [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] assert patch_layout(el1, el2) == [ ('.div_char', u'-'), ('.top', 1), ('.bottom', 1), ]
<commit_before># -*- coding: utf-8 -*- from riot.layout import render_layout, patch_layout def test_render_div(): assert render_layout([ 'div', {}, [] ]) == [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] def test_render_div_with_div_char(): el = render_layout([ 'div', { 'char': u'-', 'top': 1, 'bottom': 1 }, [] ]) == [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] def test_patch_div(): # call div._invalidate() el1 = [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] el2 = [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] assert patch_layout(el1, el2) == [ ('.div_char', u'-'), ('.top', 1), ('.bottom', 1), ] <commit_msg>Allow render opts to div.<commit_after>
# -*- coding: utf-8 -*- from riot.layout import render_layout, patch_layout def test_render_div(): assert render_layout([ 'div', {}, [] ]) == [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] def test_render_div_with_opts(): assert render_layout([ 'div', { 'char': '{ opts.custom_char }', 'top': '{ opts.custom_top }', 'bottom': '{ opts.custom_bottom }', }, [] ], { 'custom_char': u'x', 'custom_top': '1', 'custom_bottom': '1', }) == [ 'div', { 'div_char': u'x', 'top': 1, 'bottom': 1, } ] def test_render_div_with_div_char(): el = render_layout([ 'div', { 'char': u'-', 'top': 1, 'bottom': 1 }, [] ]) == [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] def test_patch_div(): # call div._invalidate() el1 = [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] el2 = [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] assert patch_layout(el1, el2) == [ ('.div_char', u'-'), ('.top', 1), ('.bottom', 1), ]
# -*- coding: utf-8 -*- from riot.layout import render_layout, patch_layout def test_render_div(): assert render_layout([ 'div', {}, [] ]) == [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] def test_render_div_with_div_char(): el = render_layout([ 'div', { 'char': u'-', 'top': 1, 'bottom': 1 }, [] ]) == [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] def test_patch_div(): # call div._invalidate() el1 = [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] el2 = [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] assert patch_layout(el1, el2) == [ ('.div_char', u'-'), ('.top', 1), ('.bottom', 1), ] Allow render opts to div.# -*- coding: utf-8 -*- from riot.layout import render_layout, patch_layout def test_render_div(): assert render_layout([ 'div', {}, [] ]) == [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] def test_render_div_with_opts(): assert render_layout([ 'div', { 'char': '{ opts.custom_char }', 'top': '{ opts.custom_top }', 'bottom': '{ opts.custom_bottom }', }, [] ], { 'custom_char': u'x', 'custom_top': '1', 'custom_bottom': '1', }) == [ 'div', { 'div_char': u'x', 'top': 1, 'bottom': 1, } ] def test_render_div_with_div_char(): el = render_layout([ 'div', { 'char': u'-', 'top': 1, 'bottom': 1 }, [] ]) == [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] def test_patch_div(): # call div._invalidate() el1 = [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] el2 = [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] assert patch_layout(el1, el2) == [ ('.div_char', u'-'), ('.top', 1), ('.bottom', 1), ]
<commit_before># -*- coding: utf-8 -*- from riot.layout import render_layout, patch_layout def test_render_div(): assert render_layout([ 'div', {}, [] ]) == [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] def test_render_div_with_div_char(): el = render_layout([ 'div', { 'char': u'-', 'top': 1, 'bottom': 1 }, [] ]) == [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] def test_patch_div(): # call div._invalidate() el1 = [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] el2 = [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] assert patch_layout(el1, el2) == [ ('.div_char', u'-'), ('.top', 1), ('.bottom', 1), ] <commit_msg>Allow render opts to div.<commit_after># -*- coding: utf-8 -*- from riot.layout import render_layout, patch_layout def test_render_div(): assert render_layout([ 'div', {}, [] ]) == [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] def test_render_div_with_opts(): assert render_layout([ 'div', { 'char': '{ opts.custom_char }', 'top': '{ opts.custom_top }', 'bottom': '{ opts.custom_bottom }', }, [] ], { 'custom_char': u'x', 'custom_top': '1', 'custom_bottom': '1', }) == [ 'div', { 'div_char': u'x', 'top': 1, 'bottom': 1, } ] def test_render_div_with_div_char(): el = render_layout([ 'div', { 'char': u'-', 'top': 1, 'bottom': 1 }, [] ]) == [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] def test_patch_div(): # call div._invalidate() el1 = [ 'div', { 'div_char': u' ', 'top': 0, 'bottom': 0, } ] el2 = [ 'div', { 'div_char': u'-', 'top': 1, 'bottom': 1, } ] assert patch_layout(el1, el2) == [ ('.div_char', u'-'), ('.top', 1), ('.bottom', 1), ]
c3d094074a6c4224efb39489110fe99b491d1108
utils/swift_build_support/swift_build_support/compiler_stage.py
utils/swift_build_support/swift_build_support/compiler_stage.py
# ===--- compiler_stage.py -----------------------------------------------===# # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https:#swift.org/LICENSE.txt for license information # See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ===---------------------------------------------------------------------===# class StageArgs(object): def __init__(self, stage, args): self.stage = stage self.args = args def __getattr__(self, key): real_key = '{}{}'.format(key, self.stage.postfix) if not hasattr(self.args, real_key): return None return getattr(self.args, real_key) class Stage(object): def __init__(self, identifier, postfix=""): self.identifier = identifier self.postfix = postfix STAGE_1 = Stage(1, "") STAGE_2 = Stage(2, "_stage2")
# ===--- compiler_stage.py -----------------------------------------------===# # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https:#swift.org/LICENSE.txt for license information # See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ===---------------------------------------------------------------------===# class StageArgs(object): def __init__(self, stage, args): self.stage = stage self.args = args assert(not isinstance(self.args, StageArgs)) def __getattr__(self, key): real_key = '{}{}'.format(key, self.stage.postfix) if not hasattr(self.args, real_key): return None return getattr(self.args, real_key) class Stage(object): def __init__(self, identifier, postfix=""): self.identifier = identifier self.postfix = postfix STAGE_1 = Stage(1, "") STAGE_2 = Stage(2, "_stage2")
Make sure that StageArgs are never passed a StageArgs as their args.
[build-script] Make sure that StageArgs are never passed a StageArgs as their args. No good reason to do this and simplifies the state space.
Python
apache-2.0
hooman/swift,ahoppen/swift,gregomni/swift,benlangmuir/swift,gregomni/swift,glessard/swift,ahoppen/swift,glessard/swift,hooman/swift,roambotics/swift,apple/swift,rudkx/swift,hooman/swift,ahoppen/swift,xwu/swift,xwu/swift,xwu/swift,JGiola/swift,rudkx/swift,apple/swift,hooman/swift,roambotics/swift,atrick/swift,benlangmuir/swift,hooman/swift,atrick/swift,benlangmuir/swift,rudkx/swift,JGiola/swift,gregomni/swift,gregomni/swift,apple/swift,atrick/swift,roambotics/swift,rudkx/swift,apple/swift,apple/swift,ahoppen/swift,xwu/swift,JGiola/swift,hooman/swift,atrick/swift,roambotics/swift,glessard/swift,benlangmuir/swift,xwu/swift,atrick/swift,JGiola/swift,xwu/swift,JGiola/swift,hooman/swift,gregomni/swift,ahoppen/swift,rudkx/swift,atrick/swift,roambotics/swift,benlangmuir/swift,roambotics/swift,JGiola/swift,apple/swift,rudkx/swift,glessard/swift,glessard/swift,glessard/swift,gregomni/swift,benlangmuir/swift,ahoppen/swift,xwu/swift
# ===--- compiler_stage.py -----------------------------------------------===# # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https:#swift.org/LICENSE.txt for license information # See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ===---------------------------------------------------------------------===# class StageArgs(object): def __init__(self, stage, args): self.stage = stage self.args = args def __getattr__(self, key): real_key = '{}{}'.format(key, self.stage.postfix) if not hasattr(self.args, real_key): return None return getattr(self.args, real_key) class Stage(object): def __init__(self, identifier, postfix=""): self.identifier = identifier self.postfix = postfix STAGE_1 = Stage(1, "") STAGE_2 = Stage(2, "_stage2") [build-script] Make sure that StageArgs are never passed a StageArgs as their args. No good reason to do this and simplifies the state space.
# ===--- compiler_stage.py -----------------------------------------------===# # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https:#swift.org/LICENSE.txt for license information # See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ===---------------------------------------------------------------------===# class StageArgs(object): def __init__(self, stage, args): self.stage = stage self.args = args assert(not isinstance(self.args, StageArgs)) def __getattr__(self, key): real_key = '{}{}'.format(key, self.stage.postfix) if not hasattr(self.args, real_key): return None return getattr(self.args, real_key) class Stage(object): def __init__(self, identifier, postfix=""): self.identifier = identifier self.postfix = postfix STAGE_1 = Stage(1, "") STAGE_2 = Stage(2, "_stage2")
<commit_before># ===--- compiler_stage.py -----------------------------------------------===# # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https:#swift.org/LICENSE.txt for license information # See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ===---------------------------------------------------------------------===# class StageArgs(object): def __init__(self, stage, args): self.stage = stage self.args = args def __getattr__(self, key): real_key = '{}{}'.format(key, self.stage.postfix) if not hasattr(self.args, real_key): return None return getattr(self.args, real_key) class Stage(object): def __init__(self, identifier, postfix=""): self.identifier = identifier self.postfix = postfix STAGE_1 = Stage(1, "") STAGE_2 = Stage(2, "_stage2") <commit_msg>[build-script] Make sure that StageArgs are never passed a StageArgs as their args. No good reason to do this and simplifies the state space.<commit_after>
# ===--- compiler_stage.py -----------------------------------------------===# # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https:#swift.org/LICENSE.txt for license information # See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ===---------------------------------------------------------------------===# class StageArgs(object): def __init__(self, stage, args): self.stage = stage self.args = args assert(not isinstance(self.args, StageArgs)) def __getattr__(self, key): real_key = '{}{}'.format(key, self.stage.postfix) if not hasattr(self.args, real_key): return None return getattr(self.args, real_key) class Stage(object): def __init__(self, identifier, postfix=""): self.identifier = identifier self.postfix = postfix STAGE_1 = Stage(1, "") STAGE_2 = Stage(2, "_stage2")
# ===--- compiler_stage.py -----------------------------------------------===# # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https:#swift.org/LICENSE.txt for license information # See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ===---------------------------------------------------------------------===# class StageArgs(object): def __init__(self, stage, args): self.stage = stage self.args = args def __getattr__(self, key): real_key = '{}{}'.format(key, self.stage.postfix) if not hasattr(self.args, real_key): return None return getattr(self.args, real_key) class Stage(object): def __init__(self, identifier, postfix=""): self.identifier = identifier self.postfix = postfix STAGE_1 = Stage(1, "") STAGE_2 = Stage(2, "_stage2") [build-script] Make sure that StageArgs are never passed a StageArgs as their args. No good reason to do this and simplifies the state space.# ===--- compiler_stage.py -----------------------------------------------===# # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https:#swift.org/LICENSE.txt for license information # See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ===---------------------------------------------------------------------===# class StageArgs(object): def __init__(self, stage, args): self.stage = stage self.args = args assert(not isinstance(self.args, StageArgs)) def __getattr__(self, key): real_key = '{}{}'.format(key, self.stage.postfix) if not hasattr(self.args, real_key): return None return getattr(self.args, real_key) class Stage(object): def __init__(self, identifier, postfix=""): self.identifier = identifier self.postfix = postfix STAGE_1 = Stage(1, "") STAGE_2 = Stage(2, "_stage2")
<commit_before># ===--- compiler_stage.py -----------------------------------------------===# # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https:#swift.org/LICENSE.txt for license information # See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ===---------------------------------------------------------------------===# class StageArgs(object): def __init__(self, stage, args): self.stage = stage self.args = args def __getattr__(self, key): real_key = '{}{}'.format(key, self.stage.postfix) if not hasattr(self.args, real_key): return None return getattr(self.args, real_key) class Stage(object): def __init__(self, identifier, postfix=""): self.identifier = identifier self.postfix = postfix STAGE_1 = Stage(1, "") STAGE_2 = Stage(2, "_stage2") <commit_msg>[build-script] Make sure that StageArgs are never passed a StageArgs as their args. No good reason to do this and simplifies the state space.<commit_after># ===--- compiler_stage.py -----------------------------------------------===# # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https:#swift.org/LICENSE.txt for license information # See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ===---------------------------------------------------------------------===# class StageArgs(object): def __init__(self, stage, args): self.stage = stage self.args = args assert(not isinstance(self.args, StageArgs)) def __getattr__(self, key): real_key = '{}{}'.format(key, self.stage.postfix) if not hasattr(self.args, real_key): return None return getattr(self.args, real_key) class Stage(object): def __init__(self, identifier, postfix=""): self.identifier = identifier self.postfix = postfix STAGE_1 = Stage(1, "") STAGE_2 = Stage(2, "_stage2")
f86ca97dc1ba22b5fab0c7a4605ab2a51367b365
openassessment/assessment/migrations/0002_staffworkflow.py
openassessment/assessment/migrations/0002_staffworkflow.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('assessment', '0001_initial'), ] operations = [ migrations.CreateModel( name='StaffWorkflow', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('scorer_id', models.CharField(max_length=40, db_index=True)), ('course_id', models.CharField(max_length=40, db_index=True)), ('item_id', models.CharField(max_length=128, db_index=True)), ('submission_uuid', models.CharField(unique=True, max_length=128, db_index=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, db_index=True)), ('grading_completed_at', models.DateTimeField(null=True, db_index=True)), ('grading_started_at', models.DateTimeField(null=True, db_index=True)), ('cancelled_at', models.DateTimeField(null=True, db_index=True)), ('assessment', models.CharField(max_length=128, null=True, db_index=True)), ], options={ 'ordering': ['created_at', 'id'], }, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('assessment', '0004_edited_content_migration'), ] operations = [ migrations.CreateModel( name='StaffWorkflow', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('scorer_id', models.CharField(max_length=40, db_index=True)), ('course_id', models.CharField(max_length=40, db_index=True)), ('item_id', models.CharField(max_length=128, db_index=True)), ('submission_uuid', models.CharField(unique=True, max_length=128, db_index=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, db_index=True)), ('grading_completed_at', models.DateTimeField(null=True, db_index=True)), ('grading_started_at', models.DateTimeField(null=True, db_index=True)), ('cancelled_at', models.DateTimeField(null=True, db_index=True)), ('assessment', models.CharField(max_length=128, null=True, db_index=True)), ], options={ 'ordering': ['created_at', 'id'], }, ), ]
Update migration history to include trackchanges migrations
Update migration history to include trackchanges migrations
Python
agpl-3.0
Stanford-Online/edx-ora2,Stanford-Online/edx-ora2,Stanford-Online/edx-ora2,Stanford-Online/edx-ora2
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('assessment', '0001_initial'), ] operations = [ migrations.CreateModel( name='StaffWorkflow', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('scorer_id', models.CharField(max_length=40, db_index=True)), ('course_id', models.CharField(max_length=40, db_index=True)), ('item_id', models.CharField(max_length=128, db_index=True)), ('submission_uuid', models.CharField(unique=True, max_length=128, db_index=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, db_index=True)), ('grading_completed_at', models.DateTimeField(null=True, db_index=True)), ('grading_started_at', models.DateTimeField(null=True, db_index=True)), ('cancelled_at', models.DateTimeField(null=True, db_index=True)), ('assessment', models.CharField(max_length=128, null=True, db_index=True)), ], options={ 'ordering': ['created_at', 'id'], }, ), ] Update migration history to include trackchanges migrations
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('assessment', '0004_edited_content_migration'), ] operations = [ migrations.CreateModel( name='StaffWorkflow', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('scorer_id', models.CharField(max_length=40, db_index=True)), ('course_id', models.CharField(max_length=40, db_index=True)), ('item_id', models.CharField(max_length=128, db_index=True)), ('submission_uuid', models.CharField(unique=True, max_length=128, db_index=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, db_index=True)), ('grading_completed_at', models.DateTimeField(null=True, db_index=True)), ('grading_started_at', models.DateTimeField(null=True, db_index=True)), ('cancelled_at', models.DateTimeField(null=True, db_index=True)), ('assessment', models.CharField(max_length=128, null=True, db_index=True)), ], options={ 'ordering': ['created_at', 'id'], }, ), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('assessment', '0001_initial'), ] operations = [ migrations.CreateModel( name='StaffWorkflow', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('scorer_id', models.CharField(max_length=40, db_index=True)), ('course_id', models.CharField(max_length=40, db_index=True)), ('item_id', models.CharField(max_length=128, db_index=True)), ('submission_uuid', models.CharField(unique=True, max_length=128, db_index=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, db_index=True)), ('grading_completed_at', models.DateTimeField(null=True, db_index=True)), ('grading_started_at', models.DateTimeField(null=True, db_index=True)), ('cancelled_at', models.DateTimeField(null=True, db_index=True)), ('assessment', models.CharField(max_length=128, null=True, db_index=True)), ], options={ 'ordering': ['created_at', 'id'], }, ), ] <commit_msg>Update migration history to include trackchanges migrations<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('assessment', '0004_edited_content_migration'), ] operations = [ migrations.CreateModel( name='StaffWorkflow', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('scorer_id', models.CharField(max_length=40, db_index=True)), ('course_id', models.CharField(max_length=40, db_index=True)), ('item_id', models.CharField(max_length=128, db_index=True)), ('submission_uuid', models.CharField(unique=True, max_length=128, db_index=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, db_index=True)), ('grading_completed_at', models.DateTimeField(null=True, db_index=True)), ('grading_started_at', models.DateTimeField(null=True, db_index=True)), ('cancelled_at', models.DateTimeField(null=True, db_index=True)), ('assessment', models.CharField(max_length=128, null=True, db_index=True)), ], options={ 'ordering': ['created_at', 'id'], }, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('assessment', '0001_initial'), ] operations = [ migrations.CreateModel( name='StaffWorkflow', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('scorer_id', models.CharField(max_length=40, db_index=True)), ('course_id', models.CharField(max_length=40, db_index=True)), ('item_id', models.CharField(max_length=128, db_index=True)), ('submission_uuid', models.CharField(unique=True, max_length=128, db_index=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, db_index=True)), ('grading_completed_at', models.DateTimeField(null=True, db_index=True)), ('grading_started_at', models.DateTimeField(null=True, db_index=True)), ('cancelled_at', models.DateTimeField(null=True, db_index=True)), ('assessment', models.CharField(max_length=128, null=True, db_index=True)), ], options={ 'ordering': ['created_at', 'id'], }, ), ] Update migration history to include trackchanges migrations# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('assessment', '0004_edited_content_migration'), ] operations = [ migrations.CreateModel( name='StaffWorkflow', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('scorer_id', models.CharField(max_length=40, db_index=True)), ('course_id', models.CharField(max_length=40, db_index=True)), ('item_id', models.CharField(max_length=128, db_index=True)), ('submission_uuid', models.CharField(unique=True, max_length=128, db_index=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, db_index=True)), ('grading_completed_at', models.DateTimeField(null=True, db_index=True)), ('grading_started_at', models.DateTimeField(null=True, db_index=True)), ('cancelled_at', models.DateTimeField(null=True, db_index=True)), ('assessment', models.CharField(max_length=128, null=True, db_index=True)), ], options={ 'ordering': ['created_at', 'id'], }, ), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('assessment', '0001_initial'), ] operations = [ migrations.CreateModel( name='StaffWorkflow', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('scorer_id', models.CharField(max_length=40, db_index=True)), ('course_id', models.CharField(max_length=40, db_index=True)), ('item_id', models.CharField(max_length=128, db_index=True)), ('submission_uuid', models.CharField(unique=True, max_length=128, db_index=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, db_index=True)), ('grading_completed_at', models.DateTimeField(null=True, db_index=True)), ('grading_started_at', models.DateTimeField(null=True, db_index=True)), ('cancelled_at', models.DateTimeField(null=True, db_index=True)), ('assessment', models.CharField(max_length=128, null=True, db_index=True)), ], options={ 'ordering': ['created_at', 'id'], }, ), ] <commit_msg>Update migration history to include trackchanges migrations<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('assessment', '0004_edited_content_migration'), ] operations = [ migrations.CreateModel( name='StaffWorkflow', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('scorer_id', models.CharField(max_length=40, db_index=True)), ('course_id', models.CharField(max_length=40, db_index=True)), ('item_id', models.CharField(max_length=128, db_index=True)), ('submission_uuid', models.CharField(unique=True, max_length=128, db_index=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, db_index=True)), ('grading_completed_at', models.DateTimeField(null=True, db_index=True)), ('grading_started_at', models.DateTimeField(null=True, db_index=True)), ('cancelled_at', models.DateTimeField(null=True, db_index=True)), ('assessment', models.CharField(max_length=128, null=True, db_index=True)), ], options={ 'ordering': ['created_at', 'id'], }, ), ]
77e9d92e040b60cc5e894a59ecfde0a91a8f1f8c
coop_cms/apps/email_auth/forms.py
coop_cms/apps/email_auth/forms.py
# -*- coding: utf-8 -*- from django import forms from django.contrib.auth import authenticate from django.utils.translation import ugettext as _ class EmailAuthForm(forms.Form): email = forms.EmailField(required=True, label=_(u"Email")) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput) def __init__(self, request=None, *args, **kwargs): super(EmailAuthForm, self).__init__(*args, **kwargs) def _authenticate(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') error_messages = { 'invalid_login': _("Please enter a correct %(email)s and password. " "Note that both fields may be case-sensitive."), } if email and password: self.user_cache = authenticate(email=email, password=password) if self.user_cache is None: raise forms.ValidationError( error_messages['invalid_login'], code='invalid_login', params={'email': _(u"email")}, ) def get_user(self): return self.user_cache def clean(self): self._authenticate() return self.cleaned_data
# -*- coding: utf-8 -*- from django import forms from django.contrib.auth import authenticate from django.utils.translation import ugettext as _, ugettext_lazy as __ class EmailAuthForm(forms.Form): email = forms.EmailField(required=True, label=__(u"Email")) password = forms.CharField(label=__("Password"), widget=forms.PasswordInput) def __init__(self, request=None, *args, **kwargs): super(EmailAuthForm, self).__init__(*args, **kwargs) def _authenticate(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') error_messages = { 'invalid_login': _("Please enter a correct %(email)s and password. " "Note that both fields may be case-sensitive."), } if email and password: self.user_cache = authenticate(email=email, password=password) if self.user_cache is None: raise forms.ValidationError( error_messages['invalid_login'], code='invalid_login', params={'email': _(u"email")}, ) def get_user(self): return self.user_cache def clean(self): self._authenticate() return self.cleaned_data
Fix translation issue on EmailAuthForm
Fix translation issue on EmailAuthForm
Python
bsd-3-clause
ljean/coop_cms,ljean/coop_cms,ljean/coop_cms
# -*- coding: utf-8 -*- from django import forms from django.contrib.auth import authenticate from django.utils.translation import ugettext as _ class EmailAuthForm(forms.Form): email = forms.EmailField(required=True, label=_(u"Email")) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput) def __init__(self, request=None, *args, **kwargs): super(EmailAuthForm, self).__init__(*args, **kwargs) def _authenticate(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') error_messages = { 'invalid_login': _("Please enter a correct %(email)s and password. " "Note that both fields may be case-sensitive."), } if email and password: self.user_cache = authenticate(email=email, password=password) if self.user_cache is None: raise forms.ValidationError( error_messages['invalid_login'], code='invalid_login', params={'email': _(u"email")}, ) def get_user(self): return self.user_cache def clean(self): self._authenticate() return self.cleaned_dataFix translation issue on EmailAuthForm
# -*- coding: utf-8 -*- from django import forms from django.contrib.auth import authenticate from django.utils.translation import ugettext as _, ugettext_lazy as __ class EmailAuthForm(forms.Form): email = forms.EmailField(required=True, label=__(u"Email")) password = forms.CharField(label=__("Password"), widget=forms.PasswordInput) def __init__(self, request=None, *args, **kwargs): super(EmailAuthForm, self).__init__(*args, **kwargs) def _authenticate(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') error_messages = { 'invalid_login': _("Please enter a correct %(email)s and password. " "Note that both fields may be case-sensitive."), } if email and password: self.user_cache = authenticate(email=email, password=password) if self.user_cache is None: raise forms.ValidationError( error_messages['invalid_login'], code='invalid_login', params={'email': _(u"email")}, ) def get_user(self): return self.user_cache def clean(self): self._authenticate() return self.cleaned_data
<commit_before># -*- coding: utf-8 -*- from django import forms from django.contrib.auth import authenticate from django.utils.translation import ugettext as _ class EmailAuthForm(forms.Form): email = forms.EmailField(required=True, label=_(u"Email")) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput) def __init__(self, request=None, *args, **kwargs): super(EmailAuthForm, self).__init__(*args, **kwargs) def _authenticate(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') error_messages = { 'invalid_login': _("Please enter a correct %(email)s and password. " "Note that both fields may be case-sensitive."), } if email and password: self.user_cache = authenticate(email=email, password=password) if self.user_cache is None: raise forms.ValidationError( error_messages['invalid_login'], code='invalid_login', params={'email': _(u"email")}, ) def get_user(self): return self.user_cache def clean(self): self._authenticate() return self.cleaned_data<commit_msg>Fix translation issue on EmailAuthForm<commit_after>
# -*- coding: utf-8 -*- from django import forms from django.contrib.auth import authenticate from django.utils.translation import ugettext as _, ugettext_lazy as __ class EmailAuthForm(forms.Form): email = forms.EmailField(required=True, label=__(u"Email")) password = forms.CharField(label=__("Password"), widget=forms.PasswordInput) def __init__(self, request=None, *args, **kwargs): super(EmailAuthForm, self).__init__(*args, **kwargs) def _authenticate(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') error_messages = { 'invalid_login': _("Please enter a correct %(email)s and password. " "Note that both fields may be case-sensitive."), } if email and password: self.user_cache = authenticate(email=email, password=password) if self.user_cache is None: raise forms.ValidationError( error_messages['invalid_login'], code='invalid_login', params={'email': _(u"email")}, ) def get_user(self): return self.user_cache def clean(self): self._authenticate() return self.cleaned_data
# -*- coding: utf-8 -*- from django import forms from django.contrib.auth import authenticate from django.utils.translation import ugettext as _ class EmailAuthForm(forms.Form): email = forms.EmailField(required=True, label=_(u"Email")) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput) def __init__(self, request=None, *args, **kwargs): super(EmailAuthForm, self).__init__(*args, **kwargs) def _authenticate(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') error_messages = { 'invalid_login': _("Please enter a correct %(email)s and password. " "Note that both fields may be case-sensitive."), } if email and password: self.user_cache = authenticate(email=email, password=password) if self.user_cache is None: raise forms.ValidationError( error_messages['invalid_login'], code='invalid_login', params={'email': _(u"email")}, ) def get_user(self): return self.user_cache def clean(self): self._authenticate() return self.cleaned_dataFix translation issue on EmailAuthForm# -*- coding: utf-8 -*- from django import forms from django.contrib.auth import authenticate from django.utils.translation import ugettext as _, ugettext_lazy as __ class EmailAuthForm(forms.Form): email = forms.EmailField(required=True, label=__(u"Email")) password = forms.CharField(label=__("Password"), widget=forms.PasswordInput) def __init__(self, request=None, *args, **kwargs): super(EmailAuthForm, self).__init__(*args, **kwargs) def _authenticate(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') error_messages = { 'invalid_login': _("Please enter a correct %(email)s and password. " "Note that both fields may be case-sensitive."), } if email and password: self.user_cache = authenticate(email=email, password=password) if self.user_cache is None: raise forms.ValidationError( error_messages['invalid_login'], code='invalid_login', params={'email': _(u"email")}, ) def get_user(self): return self.user_cache def clean(self): self._authenticate() return self.cleaned_data
<commit_before># -*- coding: utf-8 -*- from django import forms from django.contrib.auth import authenticate from django.utils.translation import ugettext as _ class EmailAuthForm(forms.Form): email = forms.EmailField(required=True, label=_(u"Email")) password = forms.CharField(label=_("Password"), widget=forms.PasswordInput) def __init__(self, request=None, *args, **kwargs): super(EmailAuthForm, self).__init__(*args, **kwargs) def _authenticate(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') error_messages = { 'invalid_login': _("Please enter a correct %(email)s and password. " "Note that both fields may be case-sensitive."), } if email and password: self.user_cache = authenticate(email=email, password=password) if self.user_cache is None: raise forms.ValidationError( error_messages['invalid_login'], code='invalid_login', params={'email': _(u"email")}, ) def get_user(self): return self.user_cache def clean(self): self._authenticate() return self.cleaned_data<commit_msg>Fix translation issue on EmailAuthForm<commit_after># -*- coding: utf-8 -*- from django import forms from django.contrib.auth import authenticate from django.utils.translation import ugettext as _, ugettext_lazy as __ class EmailAuthForm(forms.Form): email = forms.EmailField(required=True, label=__(u"Email")) password = forms.CharField(label=__("Password"), widget=forms.PasswordInput) def __init__(self, request=None, *args, **kwargs): super(EmailAuthForm, self).__init__(*args, **kwargs) def _authenticate(self): email = self.cleaned_data.get('email') password = self.cleaned_data.get('password') error_messages = { 'invalid_login': _("Please enter a correct %(email)s and password. " "Note that both fields may be case-sensitive."), } if email and password: self.user_cache = authenticate(email=email, password=password) if self.user_cache is None: raise forms.ValidationError( error_messages['invalid_login'], code='invalid_login', params={'email': _(u"email")}, ) def get_user(self): return self.user_cache def clean(self): self._authenticate() return self.cleaned_data
82db68b8474ccd38ddd9edf564a522add0658e0b
corehq/apps/export/esaccessors.py
corehq/apps/export/esaccessors.py
from corehq.apps.es import CaseES, GroupES from corehq.apps.es import FormES def get_form_export_base_query(domain, app_id, xmlns, include_errors): query = (FormES() .domain(domain) .app(app_id) .xmlns(xmlns) .sort("received_on")) if include_errors: query = query.remove_default_filter("is_xform_instance") query = query.doc_type(["xforminstance", "xformarchived", "xformdeprecated", "xformduplicate"]) return query def get_case_export_base_query(domain, case_type): return (CaseES() .domain(domain) .case_type(case_type) .sort("opened_on")) def get_group_user_ids(group_id): q = (GroupES() .doc_id(group_id) .fields("users")) return q.run().hits[0]['users']
from corehq.apps.es import CaseES, GroupES from corehq.apps.es import FormES def get_form_export_base_query(domain, app_id, xmlns, include_errors): query = (FormES() .domain(domain) .app(app_id) .xmlns(xmlns) .sort("received_on") .remove_default_filter('has_user')) # TODO: Remove has_xmlns default filter too? if include_errors: query = query.remove_default_filter("is_xform_instance") query = query.doc_type(["xforminstance", "xformarchived", "xformdeprecated", "xformduplicate"]) return query def get_case_export_base_query(domain, case_type): return (CaseES() .domain(domain) .case_type(case_type) .sort("opened_on")) def get_group_user_ids(group_id): q = (GroupES() .doc_id(group_id) .fields("users")) return q.run().hits[0]['users']
Remove default filter that breaks unknown users export filter
Remove default filter that breaks unknown users export filter
Python
bsd-3-clause
qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq
from corehq.apps.es import CaseES, GroupES from corehq.apps.es import FormES def get_form_export_base_query(domain, app_id, xmlns, include_errors): query = (FormES() .domain(domain) .app(app_id) .xmlns(xmlns) .sort("received_on")) if include_errors: query = query.remove_default_filter("is_xform_instance") query = query.doc_type(["xforminstance", "xformarchived", "xformdeprecated", "xformduplicate"]) return query def get_case_export_base_query(domain, case_type): return (CaseES() .domain(domain) .case_type(case_type) .sort("opened_on")) def get_group_user_ids(group_id): q = (GroupES() .doc_id(group_id) .fields("users")) return q.run().hits[0]['users'] Remove default filter that breaks unknown users export filter
from corehq.apps.es import CaseES, GroupES from corehq.apps.es import FormES def get_form_export_base_query(domain, app_id, xmlns, include_errors): query = (FormES() .domain(domain) .app(app_id) .xmlns(xmlns) .sort("received_on") .remove_default_filter('has_user')) # TODO: Remove has_xmlns default filter too? if include_errors: query = query.remove_default_filter("is_xform_instance") query = query.doc_type(["xforminstance", "xformarchived", "xformdeprecated", "xformduplicate"]) return query def get_case_export_base_query(domain, case_type): return (CaseES() .domain(domain) .case_type(case_type) .sort("opened_on")) def get_group_user_ids(group_id): q = (GroupES() .doc_id(group_id) .fields("users")) return q.run().hits[0]['users']
<commit_before>from corehq.apps.es import CaseES, GroupES from corehq.apps.es import FormES def get_form_export_base_query(domain, app_id, xmlns, include_errors): query = (FormES() .domain(domain) .app(app_id) .xmlns(xmlns) .sort("received_on")) if include_errors: query = query.remove_default_filter("is_xform_instance") query = query.doc_type(["xforminstance", "xformarchived", "xformdeprecated", "xformduplicate"]) return query def get_case_export_base_query(domain, case_type): return (CaseES() .domain(domain) .case_type(case_type) .sort("opened_on")) def get_group_user_ids(group_id): q = (GroupES() .doc_id(group_id) .fields("users")) return q.run().hits[0]['users'] <commit_msg>Remove default filter that breaks unknown users export filter<commit_after>
from corehq.apps.es import CaseES, GroupES from corehq.apps.es import FormES def get_form_export_base_query(domain, app_id, xmlns, include_errors): query = (FormES() .domain(domain) .app(app_id) .xmlns(xmlns) .sort("received_on") .remove_default_filter('has_user')) # TODO: Remove has_xmlns default filter too? if include_errors: query = query.remove_default_filter("is_xform_instance") query = query.doc_type(["xforminstance", "xformarchived", "xformdeprecated", "xformduplicate"]) return query def get_case_export_base_query(domain, case_type): return (CaseES() .domain(domain) .case_type(case_type) .sort("opened_on")) def get_group_user_ids(group_id): q = (GroupES() .doc_id(group_id) .fields("users")) return q.run().hits[0]['users']
from corehq.apps.es import CaseES, GroupES from corehq.apps.es import FormES def get_form_export_base_query(domain, app_id, xmlns, include_errors): query = (FormES() .domain(domain) .app(app_id) .xmlns(xmlns) .sort("received_on")) if include_errors: query = query.remove_default_filter("is_xform_instance") query = query.doc_type(["xforminstance", "xformarchived", "xformdeprecated", "xformduplicate"]) return query def get_case_export_base_query(domain, case_type): return (CaseES() .domain(domain) .case_type(case_type) .sort("opened_on")) def get_group_user_ids(group_id): q = (GroupES() .doc_id(group_id) .fields("users")) return q.run().hits[0]['users'] Remove default filter that breaks unknown users export filterfrom corehq.apps.es import CaseES, GroupES from corehq.apps.es import FormES def get_form_export_base_query(domain, app_id, xmlns, include_errors): query = (FormES() .domain(domain) .app(app_id) .xmlns(xmlns) .sort("received_on") .remove_default_filter('has_user')) # TODO: Remove has_xmlns default filter too? if include_errors: query = query.remove_default_filter("is_xform_instance") query = query.doc_type(["xforminstance", "xformarchived", "xformdeprecated", "xformduplicate"]) return query def get_case_export_base_query(domain, case_type): return (CaseES() .domain(domain) .case_type(case_type) .sort("opened_on")) def get_group_user_ids(group_id): q = (GroupES() .doc_id(group_id) .fields("users")) return q.run().hits[0]['users']
<commit_before>from corehq.apps.es import CaseES, GroupES from corehq.apps.es import FormES def get_form_export_base_query(domain, app_id, xmlns, include_errors): query = (FormES() .domain(domain) .app(app_id) .xmlns(xmlns) .sort("received_on")) if include_errors: query = query.remove_default_filter("is_xform_instance") query = query.doc_type(["xforminstance", "xformarchived", "xformdeprecated", "xformduplicate"]) return query def get_case_export_base_query(domain, case_type): return (CaseES() .domain(domain) .case_type(case_type) .sort("opened_on")) def get_group_user_ids(group_id): q = (GroupES() .doc_id(group_id) .fields("users")) return q.run().hits[0]['users'] <commit_msg>Remove default filter that breaks unknown users export filter<commit_after>from corehq.apps.es import CaseES, GroupES from corehq.apps.es import FormES def get_form_export_base_query(domain, app_id, xmlns, include_errors): query = (FormES() .domain(domain) .app(app_id) .xmlns(xmlns) .sort("received_on") .remove_default_filter('has_user')) # TODO: Remove has_xmlns default filter too? if include_errors: query = query.remove_default_filter("is_xform_instance") query = query.doc_type(["xforminstance", "xformarchived", "xformdeprecated", "xformduplicate"]) return query def get_case_export_base_query(domain, case_type): return (CaseES() .domain(domain) .case_type(case_type) .sort("opened_on")) def get_group_user_ids(group_id): q = (GroupES() .doc_id(group_id) .fields("users")) return q.run().hits[0]['users']
027e9dabb3270a3b9e3135f8a399ae4eb114a217
package_name/module.py
package_name/module.py
""" Module provides a simple cubic_rectification function. """ import numpy as np def cubic_rectification(x): """ Rectified cube of an array. Parameters ---------- x : numpy.ndarray Input array. Returns ------- numpy.ndarray Elementwise, the cube of `x` where it is positive and ``0`` otherwise. Note ---- This is a sample function, using a numpy docstring format. Note ---- The use of intersphinx will cause :class:`numpy.ndarray` to link to the numpy documentation page. """ return np.maximum(0, x ** 3)
""" Module provides a simple cubic_rectification function. """ import numpy as np def cubic_rectification(x, verbose=False): """ Rectified cube of an array. Parameters ---------- x : numpy.ndarray Input array. verbose : bool, optional Whether to print out details. Default is ``False``. Returns ------- numpy.ndarray Elementwise, the cube of `x` where it is positive and ``0`` otherwise. Note ---- This is a sample function, using a numpy docstring format. Note ---- The use of intersphinx will cause :class:`numpy.ndarray` to link to the numpy documentation page. """ if verbose: print("Cubing and then rectifying {}".format(x)) return np.maximum(0, x ** 3)
Add verbose argument to cubic_rectification
ENH: Add verbose argument to cubic_rectification
Python
mit
scottclowe/python-ci,scottclowe/python-ci,scottclowe/python-continuous-integration,scottclowe/python-continuous-integration
""" Module provides a simple cubic_rectification function. """ import numpy as np def cubic_rectification(x): """ Rectified cube of an array. Parameters ---------- x : numpy.ndarray Input array. Returns ------- numpy.ndarray Elementwise, the cube of `x` where it is positive and ``0`` otherwise. Note ---- This is a sample function, using a numpy docstring format. Note ---- The use of intersphinx will cause :class:`numpy.ndarray` to link to the numpy documentation page. """ return np.maximum(0, x ** 3) ENH: Add verbose argument to cubic_rectification
""" Module provides a simple cubic_rectification function. """ import numpy as np def cubic_rectification(x, verbose=False): """ Rectified cube of an array. Parameters ---------- x : numpy.ndarray Input array. verbose : bool, optional Whether to print out details. Default is ``False``. Returns ------- numpy.ndarray Elementwise, the cube of `x` where it is positive and ``0`` otherwise. Note ---- This is a sample function, using a numpy docstring format. Note ---- The use of intersphinx will cause :class:`numpy.ndarray` to link to the numpy documentation page. """ if verbose: print("Cubing and then rectifying {}".format(x)) return np.maximum(0, x ** 3)
<commit_before>""" Module provides a simple cubic_rectification function. """ import numpy as np def cubic_rectification(x): """ Rectified cube of an array. Parameters ---------- x : numpy.ndarray Input array. Returns ------- numpy.ndarray Elementwise, the cube of `x` where it is positive and ``0`` otherwise. Note ---- This is a sample function, using a numpy docstring format. Note ---- The use of intersphinx will cause :class:`numpy.ndarray` to link to the numpy documentation page. """ return np.maximum(0, x ** 3) <commit_msg>ENH: Add verbose argument to cubic_rectification<commit_after>
""" Module provides a simple cubic_rectification function. """ import numpy as np def cubic_rectification(x, verbose=False): """ Rectified cube of an array. Parameters ---------- x : numpy.ndarray Input array. verbose : bool, optional Whether to print out details. Default is ``False``. Returns ------- numpy.ndarray Elementwise, the cube of `x` where it is positive and ``0`` otherwise. Note ---- This is a sample function, using a numpy docstring format. Note ---- The use of intersphinx will cause :class:`numpy.ndarray` to link to the numpy documentation page. """ if verbose: print("Cubing and then rectifying {}".format(x)) return np.maximum(0, x ** 3)
""" Module provides a simple cubic_rectification function. """ import numpy as np def cubic_rectification(x): """ Rectified cube of an array. Parameters ---------- x : numpy.ndarray Input array. Returns ------- numpy.ndarray Elementwise, the cube of `x` where it is positive and ``0`` otherwise. Note ---- This is a sample function, using a numpy docstring format. Note ---- The use of intersphinx will cause :class:`numpy.ndarray` to link to the numpy documentation page. """ return np.maximum(0, x ** 3) ENH: Add verbose argument to cubic_rectification""" Module provides a simple cubic_rectification function. """ import numpy as np def cubic_rectification(x, verbose=False): """ Rectified cube of an array. Parameters ---------- x : numpy.ndarray Input array. verbose : bool, optional Whether to print out details. Default is ``False``. Returns ------- numpy.ndarray Elementwise, the cube of `x` where it is positive and ``0`` otherwise. Note ---- This is a sample function, using a numpy docstring format. Note ---- The use of intersphinx will cause :class:`numpy.ndarray` to link to the numpy documentation page. """ if verbose: print("Cubing and then rectifying {}".format(x)) return np.maximum(0, x ** 3)
<commit_before>""" Module provides a simple cubic_rectification function. """ import numpy as np def cubic_rectification(x): """ Rectified cube of an array. Parameters ---------- x : numpy.ndarray Input array. Returns ------- numpy.ndarray Elementwise, the cube of `x` where it is positive and ``0`` otherwise. Note ---- This is a sample function, using a numpy docstring format. Note ---- The use of intersphinx will cause :class:`numpy.ndarray` to link to the numpy documentation page. """ return np.maximum(0, x ** 3) <commit_msg>ENH: Add verbose argument to cubic_rectification<commit_after>""" Module provides a simple cubic_rectification function. """ import numpy as np def cubic_rectification(x, verbose=False): """ Rectified cube of an array. Parameters ---------- x : numpy.ndarray Input array. verbose : bool, optional Whether to print out details. Default is ``False``. Returns ------- numpy.ndarray Elementwise, the cube of `x` where it is positive and ``0`` otherwise. Note ---- This is a sample function, using a numpy docstring format. Note ---- The use of intersphinx will cause :class:`numpy.ndarray` to link to the numpy documentation page. """ if verbose: print("Cubing and then rectifying {}".format(x)) return np.maximum(0, x ** 3)
db6755fae84afee6466fb7119e44532392ea6e4a
lms/djangoapps/teams/api_urls.py
lms/djangoapps/teams/api_urls.py
"""Defines the URL routes for the Team API.""" from django.conf import settings from django.conf.urls import patterns, url from .views import ( TeamsListView, TeamsDetailView, TopicDetailView, TopicListView, MembershipListView, MembershipDetailView ) TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+)' USERNAME_PATTERN = r'(?P<username>[\w.+-]+)' TOPIC_ID_PATTERN = TEAM_ID_PATTERN.replace('team_id', 'topic_id') urlpatterns = patterns( '', url( r'^v0/teams$', TeamsListView.as_view(), name="teams_list" ), url( r'^v0/teams/' + TEAM_ID_PATTERN + '$', TeamsDetailView.as_view(), name="teams_detail" ), url( r'^v0/topics/$', TopicListView.as_view(), name="topics_list" ), url( r'^v0/topics/' + TOPIC_ID_PATTERN + ',' + settings.COURSE_ID_PATTERN + '$', TopicDetailView.as_view(), name="topics_detail" ), url( r'^v0/team_membership$', MembershipListView.as_view(), name="team_membership_list" ), url( r'^v0/team_membership/' + TEAM_ID_PATTERN + ',' + USERNAME_PATTERN + '$', MembershipDetailView.as_view(), name="team_membership_detail" ) )
"""Defines the URL routes for the Team API.""" from django.conf import settings from django.conf.urls import patterns, url from .views import ( TeamsListView, TeamsDetailView, TopicDetailView, TopicListView, MembershipListView, MembershipDetailView ) TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+)' USERNAME_PATTERN = r'(?P<username>[\w.+-]+)' TOPIC_ID_PATTERN = TEAM_ID_PATTERN.replace('team_id', 'topic_id') urlpatterns = patterns( '', url( r'^v0/teams/$', TeamsListView.as_view(), name="teams_list" ), url( r'^v0/teams/' + TEAM_ID_PATTERN + '$', TeamsDetailView.as_view(), name="teams_detail" ), url( r'^v0/topics/$', TopicListView.as_view(), name="topics_list" ), url( r'^v0/topics/' + TOPIC_ID_PATTERN + ',' + settings.COURSE_ID_PATTERN + '$', TopicDetailView.as_view(), name="topics_detail" ), url( r'^v0/team_membership$', MembershipListView.as_view(), name="team_membership_list" ), url( r'^v0/team_membership/' + TEAM_ID_PATTERN + ',' + USERNAME_PATTERN + '$', MembershipDetailView.as_view(), name="team_membership_detail" ) )
Fix URL trailing slash bug in teams endpoint
Fix URL trailing slash bug in teams endpoint
Python
agpl-3.0
ESOedX/edx-platform,motion2015/edx-platform,fintech-circle/edx-platform,stvstnfrd/edx-platform,louyihua/edx-platform,tiagochiavericosta/edx-platform,analyseuc3m/ANALYSE-v1,gymnasium/edx-platform,vasyarv/edx-platform,ampax/edx-platform,raccoongang/edx-platform,simbs/edx-platform,bitifirefly/edx-platform,wwj718/edx-platform,arifsetiawan/edx-platform,zofuthan/edx-platform,ahmedaljazzar/edx-platform,jazkarta/edx-platform,don-github/edx-platform,Ayub-Khan/edx-platform,chauhanhardik/populo,appliedx/edx-platform,nikolas/edx-platform,10clouds/edx-platform,zhenzhai/edx-platform,devs1991/test_edx_docmode,adoosii/edx-platform,simbs/edx-platform,cpennington/edx-platform,a-parhom/edx-platform,mjirayu/sit_academy,solashirai/edx-platform,pepeportela/edx-platform,CourseTalk/edx-platform,prarthitm/edxplatform,zhenzhai/edx-platform,mjirayu/sit_academy,mcgachey/edx-platform,msegado/edx-platform,xinjiguaike/edx-platform,Semi-global/edx-platform,Endika/edx-platform,appsembler/edx-platform,fintech-circle/edx-platform,gymnasium/edx-platform,solashirai/edx-platform,kxliugang/edx-platform,antoviaque/edx-platform,Livit/Livit.Learn.EdX,J861449197/edx-platform,philanthropy-u/edx-platform,iivic/BoiseStateX,alexthered/kienhoc-platform,waheedahmed/edx-platform,edry/edx-platform,cognitiveclass/edx-platform,Livit/Livit.Learn.EdX,stvstnfrd/edx-platform,ESOedX/edx-platform,franosincic/edx-platform,pepeportela/edx-platform,itsjeyd/edx-platform,jamesblunt/edx-platform,appsembler/edx-platform,nikolas/edx-platform,ampax/edx-platform,benpatterson/edx-platform,mitocw/edx-platform,tiagochiavericosta/edx-platform,appliedx/edx-platform,adoosii/edx-platform,nanolearningllc/edx-platform-cypress,inares/edx-platform,romain-li/edx-platform,atsolakid/edx-platform,zerobatu/edx-platform,rismalrv/edx-platform,EDUlib/edx-platform,franosincic/edx-platform,MakeHer/edx-platform,jzoldak/edx-platform,utecuy/edx-platform,eduNEXT/edunext-platform,prarthitm/edxplatform,lduarte1991/edx-platform,marcore/edx-platform,cecep-edu/edx-platform,tanmaykm/edx-platform,louyihua/edx-platform,doganov/edx-platform,devs1991/test_edx_docmode,inares/edx-platform,ahmadiga/min_edx,Semi-global/edx-platform,wwj718/edx-platform,cognitiveclass/edx-platform,proversity-org/edx-platform,edry/edx-platform,Edraak/circleci-edx-platform,fly19890211/edx-platform,mcgachey/edx-platform,utecuy/edx-platform,pepeportela/edx-platform,RPI-OPENEDX/edx-platform,solashirai/edx-platform,romain-li/edx-platform,adoosii/edx-platform,antoviaque/edx-platform,etzhou/edx-platform,doganov/edx-platform,Lektorium-LLC/edx-platform,ferabra/edx-platform,vikas1885/test1,SravanthiSinha/edx-platform,pomegranited/edx-platform,tanmaykm/edx-platform,tiagochiavericosta/edx-platform,don-github/edx-platform,RPI-OPENEDX/edx-platform,etzhou/edx-platform,ESOedX/edx-platform,SivilTaram/edx-platform,alu042/edx-platform,ak2703/edx-platform,nanolearningllc/edx-platform-cypress,waheedahmed/edx-platform,jazkarta/edx-platform,shabab12/edx-platform,J861449197/edx-platform,ovnicraft/edx-platform,ubc/edx-platform,waheedahmed/edx-platform,alu042/edx-platform,nanolearningllc/edx-platform-cypress-2,playm2mboy/edx-platform,ferabra/edx-platform,iivic/BoiseStateX,Edraak/edx-platform,Kalyzee/edx-platform,JioEducation/edx-platform,mitocw/edx-platform,Edraak/circleci-edx-platform,eduNEXT/edx-platform,chauhanhardik/populo_2,chauhanhardik/populo_2,msegado/edx-platform,halvertoluke/edx-platform,ahmadio/edx-platform,leansoft/edx-platform,JCBarahona/edX,chudaol/edx-platform,angelapper/edx-platform,ferabra/edx-platform,tiagochiavericosta/edx-platform,JCBarahona/edX,JCBarahona/edX,AkA84/edx-platform,4eek/edx-platform,Softmotions/edx-platform,JioEducation/edx-platform,shurihell/testasia,mcgachey/edx-platform,shabab12/edx-platform,bitifirefly/edx-platform,jjmiranda/edx-platform,nagyistoce/edx-platform,a-parhom/edx-platform,Edraak/circleci-edx-platform,jolyonb/edx-platform,tiagochiavericosta/edx-platform,gsehub/edx-platform,gsehub/edx-platform,etzhou/edx-platform,teltek/edx-platform,zubair-arbi/edx-platform,doismellburning/edx-platform,Softmotions/edx-platform,jbassen/edx-platform,pabloborrego93/edx-platform,cecep-edu/edx-platform,appsembler/edx-platform,eduNEXT/edx-platform,jbassen/edx-platform,IndonesiaX/edx-platform,10clouds/edx-platform,proversity-org/edx-platform,TeachAtTUM/edx-platform,mahendra-r/edx-platform,itsjeyd/edx-platform,adoosii/edx-platform,hastexo/edx-platform,miptliot/edx-platform,utecuy/edx-platform,Livit/Livit.Learn.EdX,IndonesiaX/edx-platform,deepsrijit1105/edx-platform,synergeticsedx/deployment-wipro,msegado/edx-platform,4eek/edx-platform,deepsrijit1105/edx-platform,kmoocdev2/edx-platform,shabab12/edx-platform,raccoongang/edx-platform,itsjeyd/edx-platform,alexthered/kienhoc-platform,bigdatauniversity/edx-platform,jazztpt/edx-platform,chauhanhardik/populo,zofuthan/edx-platform,fly19890211/edx-platform,jazkarta/edx-platform,ubc/edx-platform,mjirayu/sit_academy,caesar2164/edx-platform,edx-solutions/edx-platform,nanolearningllc/edx-platform-cypress,jbassen/edx-platform,motion2015/edx-platform,pomegranited/edx-platform,antoviaque/edx-platform,Kalyzee/edx-platform,tanmaykm/edx-platform,pabloborrego93/edx-platform,nttks/edx-platform,jamesblunt/edx-platform,xuxiao19910803/edx,utecuy/edx-platform,franosincic/edx-platform,mitocw/edx-platform,leansoft/edx-platform,angelapper/edx-platform,vikas1885/test1,pomegranited/edx-platform,chauhanhardik/populo_2,bitifirefly/edx-platform,TeachAtTUM/edx-platform,cognitiveclass/edx-platform,nanolearningllc/edx-platform-cypress-2,adoosii/edx-platform,deepsrijit1105/edx-platform,caesar2164/edx-platform,gymnasium/edx-platform,MakeHer/edx-platform,waheedahmed/edx-platform,jazztpt/edx-platform,Edraak/edx-platform,Semi-global/edx-platform,kursitet/edx-platform,doismellburning/edx-platform,Stanford-Online/edx-platform,romain-li/edx-platform,jazztpt/edx-platform,xuxiao19910803/edx,4eek/edx-platform,chauhanhardik/populo,kxliugang/edx-platform,devs1991/test_edx_docmode,nanolearningllc/edx-platform-cypress-2,marcore/edx-platform,deepsrijit1105/edx-platform,BehavioralInsightsTeam/edx-platform,philanthropy-u/edx-platform,kursitet/edx-platform,miptliot/edx-platform,BehavioralInsightsTeam/edx-platform,CredoReference/edx-platform,jamesblunt/edx-platform,shabab12/edx-platform,kxliugang/edx-platform,jzoldak/edx-platform,eduNEXT/edunext-platform,mcgachey/edx-platform,benpatterson/edx-platform,ak2703/edx-platform,zhenzhai/edx-platform,zerobatu/edx-platform,Lektorium-LLC/edx-platform,BehavioralInsightsTeam/edx-platform,edx/edx-platform,chauhanhardik/populo,ovnicraft/edx-platform,ahmadiga/min_edx,doismellburning/edx-platform,simbs/edx-platform,miptliot/edx-platform,hastexo/edx-platform,xingyepei/edx-platform,raccoongang/edx-platform,IONISx/edx-platform,IndonesiaX/edx-platform,motion2015/edx-platform,mbareta/edx-platform-ft,UOMx/edx-platform,BehavioralInsightsTeam/edx-platform,a-parhom/edx-platform,Edraak/circleci-edx-platform,zubair-arbi/edx-platform,10clouds/edx-platform,arifsetiawan/edx-platform,ovnicraft/edx-platform,edry/edx-platform,jamesblunt/edx-platform,a-parhom/edx-platform,ahmadio/edx-platform,romain-li/edx-platform,cecep-edu/edx-platform,msegado/edx-platform,Semi-global/edx-platform,kmoocdev2/edx-platform,bigdatauniversity/edx-platform,amir-qayyum-khan/edx-platform,Edraak/circleci-edx-platform,ZLLab-Mooc/edx-platform,waheedahmed/edx-platform,defance/edx-platform,ovnicraft/edx-platform,philanthropy-u/edx-platform,kmoocdev2/edx-platform,doismellburning/edx-platform,chrisndodge/edx-platform,vasyarv/edx-platform,teltek/edx-platform,devs1991/test_edx_docmode,jolyonb/edx-platform,AkA84/edx-platform,jamiefolsom/edx-platform,itsjeyd/edx-platform,arbrandes/edx-platform,hastexo/edx-platform,stvstnfrd/edx-platform,ahmedaljazzar/edx-platform,appliedx/edx-platform,ferabra/edx-platform,jonathan-beard/edx-platform,xinjiguaike/edx-platform,IONISx/edx-platform,synergeticsedx/deployment-wipro,appliedx/edx-platform,synergeticsedx/deployment-wipro,xuxiao19910803/edx,defance/edx-platform,nanolearningllc/edx-platform-cypress,teltek/edx-platform,Softmotions/edx-platform,zerobatu/edx-platform,xingyepei/edx-platform,arbrandes/edx-platform,romain-li/edx-platform,JioEducation/edx-platform,caesar2164/edx-platform,vasyarv/edx-platform,MakeHer/edx-platform,ahmadio/edx-platform,inares/edx-platform,playm2mboy/edx-platform,4eek/edx-platform,CredoReference/edx-platform,ubc/edx-platform,J861449197/edx-platform,RPI-OPENEDX/edx-platform,Kalyzee/edx-platform,mbareta/edx-platform-ft,iivic/BoiseStateX,chrisndodge/edx-platform,CourseTalk/edx-platform,eduNEXT/edx-platform,Edraak/edraak-platform,longmen21/edx-platform,shurihell/testasia,analyseuc3m/ANALYSE-v1,shashank971/edx-platform,pomegranited/edx-platform,procangroup/edx-platform,jbassen/edx-platform,bitifirefly/edx-platform,atsolakid/edx-platform,edx/edx-platform,devs1991/test_edx_docmode,benpatterson/edx-platform,pabloborrego93/edx-platform,JioEducation/edx-platform,jjmiranda/edx-platform,xingyepei/edx-platform,nikolas/edx-platform,devs1991/test_edx_docmode,franosincic/edx-platform,zofuthan/edx-platform,devs1991/test_edx_docmode,analyseuc3m/ANALYSE-v1,eduNEXT/edx-platform,jolyonb/edx-platform,louyihua/edx-platform,J861449197/edx-platform,Endika/edx-platform,appsembler/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform,Ayub-Khan/edx-platform,motion2015/edx-platform,AkA84/edx-platform,alexthered/kienhoc-platform,miptliot/edx-platform,rismalrv/edx-platform,Lektorium-LLC/edx-platform,iivic/BoiseStateX,jbzdak/edx-platform,cognitiveclass/edx-platform,ahmadiga/min_edx,simbs/edx-platform,jonathan-beard/edx-platform,rismalrv/edx-platform,Livit/Livit.Learn.EdX,longmen21/edx-platform,jjmiranda/edx-platform,nttks/edx-platform,chauhanhardik/populo_2,ahmadiga/min_edx,mahendra-r/edx-platform,Edraak/edraak-platform,Lektorium-LLC/edx-platform,ampax/edx-platform,benpatterson/edx-platform,etzhou/edx-platform,nikolas/edx-platform,kursitet/edx-platform,louyihua/edx-platform,edx/edx-platform,ahmadiga/min_edx,CourseTalk/edx-platform,EDUlib/edx-platform,longmen21/edx-platform,edry/edx-platform,chudaol/edx-platform,TeachAtTUM/edx-platform,SravanthiSinha/edx-platform,Stanford-Online/edx-platform,benpatterson/edx-platform,halvertoluke/edx-platform,fly19890211/edx-platform,pabloborrego93/edx-platform,kursitet/edx-platform,Endika/edx-platform,jamesblunt/edx-platform,SravanthiSinha/edx-platform,chauhanhardik/populo_2,jbzdak/edx-platform,franosincic/edx-platform,playm2mboy/edx-platform,jzoldak/edx-platform,SravanthiSinha/edx-platform,procangroup/edx-platform,ZLLab-Mooc/edx-platform,ferabra/edx-platform,arifsetiawan/edx-platform,Edraak/edx-platform,zubair-arbi/edx-platform,Ayub-Khan/edx-platform,Stanford-Online/edx-platform,CourseTalk/edx-platform,zerobatu/edx-platform,jazkarta/edx-platform,zofuthan/edx-platform,halvertoluke/edx-platform,bigdatauniversity/edx-platform,amir-qayyum-khan/edx-platform,CredoReference/edx-platform,bitifirefly/edx-platform,longmen21/edx-platform,nttks/edx-platform,marcore/edx-platform,ahmadio/edx-platform,mahendra-r/edx-platform,ahmedaljazzar/edx-platform,IONISx/edx-platform,vikas1885/test1,nttks/edx-platform,msegado/edx-platform,ZLLab-Mooc/edx-platform,zubair-arbi/edx-platform,Edraak/edraak-platform,teltek/edx-platform,nagyistoce/edx-platform,J861449197/edx-platform,mahendra-r/edx-platform,cecep-edu/edx-platform,Kalyzee/edx-platform,ubc/edx-platform,marcore/edx-platform,nagyistoce/edx-platform,nanolearningllc/edx-platform-cypress-2,kxliugang/edx-platform,ak2703/edx-platform,eduNEXT/edunext-platform,cecep-edu/edx-platform,ovnicraft/edx-platform,xuxiao19910803/edx,naresh21/synergetics-edx-platform,Ayub-Khan/edx-platform,4eek/edx-platform,don-github/edx-platform,Edraak/edx-platform,shashank971/edx-platform,ak2703/edx-platform,doganov/edx-platform,mahendra-r/edx-platform,xinjiguaike/edx-platform,mjirayu/sit_academy,RPI-OPENEDX/edx-platform,pomegranited/edx-platform,inares/edx-platform,kmoocdev2/edx-platform,halvertoluke/edx-platform,philanthropy-u/edx-platform,shurihell/testasia,chudaol/edx-platform,alexthered/kienhoc-platform,UOMx/edx-platform,alu042/edx-platform,UOMx/edx-platform,kmoocdev2/edx-platform,utecuy/edx-platform,IONISx/edx-platform,caesar2164/edx-platform,MakeHer/edx-platform,mbareta/edx-platform-ft,cpennington/edx-platform,analyseuc3m/ANALYSE-v1,jolyonb/edx-platform,etzhou/edx-platform,hamzehd/edx-platform,zubair-arbi/edx-platform,kxliugang/edx-platform,nttks/edx-platform,rismalrv/edx-platform,ubc/edx-platform,Kalyzee/edx-platform,halvertoluke/edx-platform,xingyepei/edx-platform,Semi-global/edx-platform,fintech-circle/edx-platform,mjirayu/sit_academy,vasyarv/edx-platform,chrisndodge/edx-platform,eduNEXT/edunext-platform,jjmiranda/edx-platform,fintech-circle/edx-platform,jazztpt/edx-platform,jonathan-beard/edx-platform,10clouds/edx-platform,hamzehd/edx-platform,solashirai/edx-platform,defance/edx-platform,ZLLab-Mooc/edx-platform,nagyistoce/edx-platform,Endika/edx-platform,jamiefolsom/edx-platform,doganov/edx-platform,leansoft/edx-platform,wwj718/edx-platform,chrisndodge/edx-platform,naresh21/synergetics-edx-platform,zhenzhai/edx-platform,angelapper/edx-platform,xinjiguaike/edx-platform,IndonesiaX/edx-platform,AkA84/edx-platform,SivilTaram/edx-platform,jbzdak/edx-platform,hastexo/edx-platform,Ayub-Khan/edx-platform,atsolakid/edx-platform,chudaol/edx-platform,simbs/edx-platform,kursitet/edx-platform,jamiefolsom/edx-platform,inares/edx-platform,xingyepei/edx-platform,fly19890211/edx-platform,edry/edx-platform,ZLLab-Mooc/edx-platform,shashank971/edx-platform,pepeportela/edx-platform,procangroup/edx-platform,cpennington/edx-platform,zhenzhai/edx-platform,JCBarahona/edX,longmen21/edx-platform,iivic/BoiseStateX,Stanford-Online/edx-platform,naresh21/synergetics-edx-platform,zerobatu/edx-platform,edx-solutions/edx-platform,Softmotions/edx-platform,doganov/edx-platform,jonathan-beard/edx-platform,lduarte1991/edx-platform,proversity-org/edx-platform,hamzehd/edx-platform,fly19890211/edx-platform,atsolakid/edx-platform,jbzdak/edx-platform,devs1991/test_edx_docmode,amir-qayyum-khan/edx-platform,appliedx/edx-platform,jonathan-beard/edx-platform,stvstnfrd/edx-platform,xinjiguaike/edx-platform,antoviaque/edx-platform,xuxiao19910803/edx,edx/edx-platform,don-github/edx-platform,jamiefolsom/edx-platform,alexthered/kienhoc-platform,ampax/edx-platform,tanmaykm/edx-platform,mcgachey/edx-platform,jbassen/edx-platform,alu042/edx-platform,atsolakid/edx-platform,ahmedaljazzar/edx-platform,EDUlib/edx-platform,JCBarahona/edX,shashank971/edx-platform,cognitiveclass/edx-platform,jamiefolsom/edx-platform,EDUlib/edx-platform,shurihell/testasia,angelapper/edx-platform,cpennington/edx-platform,wwj718/edx-platform,prarthitm/edxplatform,mbareta/edx-platform-ft,ESOedX/edx-platform,arifsetiawan/edx-platform,IndonesiaX/edx-platform,Softmotions/edx-platform,lduarte1991/edx-platform,leansoft/edx-platform,playm2mboy/edx-platform,procangroup/edx-platform,Edraak/edraak-platform,proversity-org/edx-platform,UOMx/edx-platform,chauhanhardik/populo,IONISx/edx-platform,nikolas/edx-platform,SravanthiSinha/edx-platform,leansoft/edx-platform,hamzehd/edx-platform,raccoongang/edx-platform,SivilTaram/edx-platform,nanolearningllc/edx-platform-cypress,jazkarta/edx-platform,bigdatauniversity/edx-platform,gsehub/edx-platform,wwj718/edx-platform,vikas1885/test1,MakeHer/edx-platform,naresh21/synergetics-edx-platform,vasyarv/edx-platform,bigdatauniversity/edx-platform,ahmadio/edx-platform,arbrandes/edx-platform,gymnasium/edx-platform,CredoReference/edx-platform,nagyistoce/edx-platform,prarthitm/edxplatform,vikas1885/test1,arbrandes/edx-platform,jazztpt/edx-platform,ak2703/edx-platform,defance/edx-platform,SivilTaram/edx-platform,amir-qayyum-khan/edx-platform,shashank971/edx-platform,lduarte1991/edx-platform,AkA84/edx-platform,playm2mboy/edx-platform,gsehub/edx-platform,shurihell/testasia,jbzdak/edx-platform,nanolearningllc/edx-platform-cypress-2,arifsetiawan/edx-platform,solashirai/edx-platform,TeachAtTUM/edx-platform,doismellburning/edx-platform,rismalrv/edx-platform,motion2015/edx-platform,hamzehd/edx-platform,zofuthan/edx-platform,don-github/edx-platform,chudaol/edx-platform,Edraak/edx-platform,mitocw/edx-platform,SivilTaram/edx-platform,synergeticsedx/deployment-wipro,jzoldak/edx-platform,RPI-OPENEDX/edx-platform
"""Defines the URL routes for the Team API.""" from django.conf import settings from django.conf.urls import patterns, url from .views import ( TeamsListView, TeamsDetailView, TopicDetailView, TopicListView, MembershipListView, MembershipDetailView ) TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+)' USERNAME_PATTERN = r'(?P<username>[\w.+-]+)' TOPIC_ID_PATTERN = TEAM_ID_PATTERN.replace('team_id', 'topic_id') urlpatterns = patterns( '', url( r'^v0/teams$', TeamsListView.as_view(), name="teams_list" ), url( r'^v0/teams/' + TEAM_ID_PATTERN + '$', TeamsDetailView.as_view(), name="teams_detail" ), url( r'^v0/topics/$', TopicListView.as_view(), name="topics_list" ), url( r'^v0/topics/' + TOPIC_ID_PATTERN + ',' + settings.COURSE_ID_PATTERN + '$', TopicDetailView.as_view(), name="topics_detail" ), url( r'^v0/team_membership$', MembershipListView.as_view(), name="team_membership_list" ), url( r'^v0/team_membership/' + TEAM_ID_PATTERN + ',' + USERNAME_PATTERN + '$', MembershipDetailView.as_view(), name="team_membership_detail" ) ) Fix URL trailing slash bug in teams endpoint
"""Defines the URL routes for the Team API.""" from django.conf import settings from django.conf.urls import patterns, url from .views import ( TeamsListView, TeamsDetailView, TopicDetailView, TopicListView, MembershipListView, MembershipDetailView ) TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+)' USERNAME_PATTERN = r'(?P<username>[\w.+-]+)' TOPIC_ID_PATTERN = TEAM_ID_PATTERN.replace('team_id', 'topic_id') urlpatterns = patterns( '', url( r'^v0/teams/$', TeamsListView.as_view(), name="teams_list" ), url( r'^v0/teams/' + TEAM_ID_PATTERN + '$', TeamsDetailView.as_view(), name="teams_detail" ), url( r'^v0/topics/$', TopicListView.as_view(), name="topics_list" ), url( r'^v0/topics/' + TOPIC_ID_PATTERN + ',' + settings.COURSE_ID_PATTERN + '$', TopicDetailView.as_view(), name="topics_detail" ), url( r'^v0/team_membership$', MembershipListView.as_view(), name="team_membership_list" ), url( r'^v0/team_membership/' + TEAM_ID_PATTERN + ',' + USERNAME_PATTERN + '$', MembershipDetailView.as_view(), name="team_membership_detail" ) )
<commit_before>"""Defines the URL routes for the Team API.""" from django.conf import settings from django.conf.urls import patterns, url from .views import ( TeamsListView, TeamsDetailView, TopicDetailView, TopicListView, MembershipListView, MembershipDetailView ) TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+)' USERNAME_PATTERN = r'(?P<username>[\w.+-]+)' TOPIC_ID_PATTERN = TEAM_ID_PATTERN.replace('team_id', 'topic_id') urlpatterns = patterns( '', url( r'^v0/teams$', TeamsListView.as_view(), name="teams_list" ), url( r'^v0/teams/' + TEAM_ID_PATTERN + '$', TeamsDetailView.as_view(), name="teams_detail" ), url( r'^v0/topics/$', TopicListView.as_view(), name="topics_list" ), url( r'^v0/topics/' + TOPIC_ID_PATTERN + ',' + settings.COURSE_ID_PATTERN + '$', TopicDetailView.as_view(), name="topics_detail" ), url( r'^v0/team_membership$', MembershipListView.as_view(), name="team_membership_list" ), url( r'^v0/team_membership/' + TEAM_ID_PATTERN + ',' + USERNAME_PATTERN + '$', MembershipDetailView.as_view(), name="team_membership_detail" ) ) <commit_msg>Fix URL trailing slash bug in teams endpoint<commit_after>
"""Defines the URL routes for the Team API.""" from django.conf import settings from django.conf.urls import patterns, url from .views import ( TeamsListView, TeamsDetailView, TopicDetailView, TopicListView, MembershipListView, MembershipDetailView ) TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+)' USERNAME_PATTERN = r'(?P<username>[\w.+-]+)' TOPIC_ID_PATTERN = TEAM_ID_PATTERN.replace('team_id', 'topic_id') urlpatterns = patterns( '', url( r'^v0/teams/$', TeamsListView.as_view(), name="teams_list" ), url( r'^v0/teams/' + TEAM_ID_PATTERN + '$', TeamsDetailView.as_view(), name="teams_detail" ), url( r'^v0/topics/$', TopicListView.as_view(), name="topics_list" ), url( r'^v0/topics/' + TOPIC_ID_PATTERN + ',' + settings.COURSE_ID_PATTERN + '$', TopicDetailView.as_view(), name="topics_detail" ), url( r'^v0/team_membership$', MembershipListView.as_view(), name="team_membership_list" ), url( r'^v0/team_membership/' + TEAM_ID_PATTERN + ',' + USERNAME_PATTERN + '$', MembershipDetailView.as_view(), name="team_membership_detail" ) )
"""Defines the URL routes for the Team API.""" from django.conf import settings from django.conf.urls import patterns, url from .views import ( TeamsListView, TeamsDetailView, TopicDetailView, TopicListView, MembershipListView, MembershipDetailView ) TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+)' USERNAME_PATTERN = r'(?P<username>[\w.+-]+)' TOPIC_ID_PATTERN = TEAM_ID_PATTERN.replace('team_id', 'topic_id') urlpatterns = patterns( '', url( r'^v0/teams$', TeamsListView.as_view(), name="teams_list" ), url( r'^v0/teams/' + TEAM_ID_PATTERN + '$', TeamsDetailView.as_view(), name="teams_detail" ), url( r'^v0/topics/$', TopicListView.as_view(), name="topics_list" ), url( r'^v0/topics/' + TOPIC_ID_PATTERN + ',' + settings.COURSE_ID_PATTERN + '$', TopicDetailView.as_view(), name="topics_detail" ), url( r'^v0/team_membership$', MembershipListView.as_view(), name="team_membership_list" ), url( r'^v0/team_membership/' + TEAM_ID_PATTERN + ',' + USERNAME_PATTERN + '$', MembershipDetailView.as_view(), name="team_membership_detail" ) ) Fix URL trailing slash bug in teams endpoint"""Defines the URL routes for the Team API.""" from django.conf import settings from django.conf.urls import patterns, url from .views import ( TeamsListView, TeamsDetailView, TopicDetailView, TopicListView, MembershipListView, MembershipDetailView ) TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+)' USERNAME_PATTERN = r'(?P<username>[\w.+-]+)' TOPIC_ID_PATTERN = TEAM_ID_PATTERN.replace('team_id', 'topic_id') urlpatterns = patterns( '', url( r'^v0/teams/$', TeamsListView.as_view(), name="teams_list" ), url( r'^v0/teams/' + TEAM_ID_PATTERN + '$', TeamsDetailView.as_view(), name="teams_detail" ), url( r'^v0/topics/$', TopicListView.as_view(), name="topics_list" ), url( r'^v0/topics/' + TOPIC_ID_PATTERN + ',' + settings.COURSE_ID_PATTERN + '$', TopicDetailView.as_view(), name="topics_detail" ), url( r'^v0/team_membership$', MembershipListView.as_view(), name="team_membership_list" ), url( r'^v0/team_membership/' + TEAM_ID_PATTERN + ',' + USERNAME_PATTERN + '$', MembershipDetailView.as_view(), name="team_membership_detail" ) )
<commit_before>"""Defines the URL routes for the Team API.""" from django.conf import settings from django.conf.urls import patterns, url from .views import ( TeamsListView, TeamsDetailView, TopicDetailView, TopicListView, MembershipListView, MembershipDetailView ) TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+)' USERNAME_PATTERN = r'(?P<username>[\w.+-]+)' TOPIC_ID_PATTERN = TEAM_ID_PATTERN.replace('team_id', 'topic_id') urlpatterns = patterns( '', url( r'^v0/teams$', TeamsListView.as_view(), name="teams_list" ), url( r'^v0/teams/' + TEAM_ID_PATTERN + '$', TeamsDetailView.as_view(), name="teams_detail" ), url( r'^v0/topics/$', TopicListView.as_view(), name="topics_list" ), url( r'^v0/topics/' + TOPIC_ID_PATTERN + ',' + settings.COURSE_ID_PATTERN + '$', TopicDetailView.as_view(), name="topics_detail" ), url( r'^v0/team_membership$', MembershipListView.as_view(), name="team_membership_list" ), url( r'^v0/team_membership/' + TEAM_ID_PATTERN + ',' + USERNAME_PATTERN + '$', MembershipDetailView.as_view(), name="team_membership_detail" ) ) <commit_msg>Fix URL trailing slash bug in teams endpoint<commit_after>"""Defines the URL routes for the Team API.""" from django.conf import settings from django.conf.urls import patterns, url from .views import ( TeamsListView, TeamsDetailView, TopicDetailView, TopicListView, MembershipListView, MembershipDetailView ) TEAM_ID_PATTERN = r'(?P<team_id>[a-z\d_-]+)' USERNAME_PATTERN = r'(?P<username>[\w.+-]+)' TOPIC_ID_PATTERN = TEAM_ID_PATTERN.replace('team_id', 'topic_id') urlpatterns = patterns( '', url( r'^v0/teams/$', TeamsListView.as_view(), name="teams_list" ), url( r'^v0/teams/' + TEAM_ID_PATTERN + '$', TeamsDetailView.as_view(), name="teams_detail" ), url( r'^v0/topics/$', TopicListView.as_view(), name="topics_list" ), url( r'^v0/topics/' + TOPIC_ID_PATTERN + ',' + settings.COURSE_ID_PATTERN + '$', TopicDetailView.as_view(), name="topics_detail" ), url( r'^v0/team_membership$', MembershipListView.as_view(), name="team_membership_list" ), url( r'^v0/team_membership/' + TEAM_ID_PATTERN + ',' + USERNAME_PATTERN + '$', MembershipDetailView.as_view(), name="team_membership_detail" ) )
402f7d3b89efd98da23633542c17a0ff51edee0a
tcelery/__init__.py
tcelery/__init__.py
from __future__ import absolute_import import celery from tornado import ioloop from .connection import ConnectionPool from .producer import NonBlockingTaskProducer from .result import AsyncResult VERSION = (0, 3, 0) __version__ = '.'.join(map(str, VERSION)) + '-dev' def setup_nonblocking_producer(celery_app=None, io_loop=None, on_ready=None, result_cls=AsyncResult, limit=1): celery_app = celery_app or celery.current_app io_loop = io_loop or ioloop.IOLoop.instance() NonBlockingTaskProducer.app = celery_app NonBlockingTaskProducer.conn_pool = ConnectionPool(limit=limit) NonBlockingTaskProducer.result_cls = result_cls if celery_app.conf['BROKER_URL'] and celery_app.conf['BROKER_URL'].startswith('amqp'): celery.app.amqp.AMQP.producer_cls = NonBlockingTaskProducer def connect(): broker_url = celery_app.connection().as_uri(include_password=True) options = celery_app.conf.get('CELERYT_PIKA_OPTIONS', {}) NonBlockingTaskProducer.conn_pool.connect(broker_url, options=options, callback=on_ready) io_loop.add_callback(connect)
from __future__ import absolute_import import celery from tornado import ioloop from .connection import ConnectionPool from .producer import NonBlockingTaskProducer from .result import AsyncResult VERSION = (0, 3, 0) __version__ = '.'.join(map(str, VERSION)) + '-dev' def setup_nonblocking_producer(celery_app=None, io_loop=None, on_ready=None, result_cls=AsyncResult, limit=1): celery_app = celery_app or celery.current_app io_loop = io_loop or ioloop.IOLoop.instance() NonBlockingTaskProducer.app = celery_app NonBlockingTaskProducer.conn_pool = ConnectionPool(limit, io_loop) NonBlockingTaskProducer.result_cls = result_cls if celery_app.conf['BROKER_URL'] and celery_app.conf['BROKER_URL'].startswith('amqp'): celery.app.amqp.AMQP.producer_cls = NonBlockingTaskProducer def connect(): broker_url = celery_app.connection().as_uri(include_password=True) options = celery_app.conf.get('CELERYT_PIKA_OPTIONS', {}) NonBlockingTaskProducer.conn_pool.connect(broker_url, options=options, callback=on_ready) io_loop.add_callback(connect)
Allow custon io loops for ConnectionPools
Allow custon io loops for ConnectionPools
Python
bsd-3-clause
mher/tornado-celery,sangwonl/tornado-celery,shnjp/tornado-celery,qudos-com/tornado-celery
from __future__ import absolute_import import celery from tornado import ioloop from .connection import ConnectionPool from .producer import NonBlockingTaskProducer from .result import AsyncResult VERSION = (0, 3, 0) __version__ = '.'.join(map(str, VERSION)) + '-dev' def setup_nonblocking_producer(celery_app=None, io_loop=None, on_ready=None, result_cls=AsyncResult, limit=1): celery_app = celery_app or celery.current_app io_loop = io_loop or ioloop.IOLoop.instance() NonBlockingTaskProducer.app = celery_app NonBlockingTaskProducer.conn_pool = ConnectionPool(limit=limit) NonBlockingTaskProducer.result_cls = result_cls if celery_app.conf['BROKER_URL'] and celery_app.conf['BROKER_URL'].startswith('amqp'): celery.app.amqp.AMQP.producer_cls = NonBlockingTaskProducer def connect(): broker_url = celery_app.connection().as_uri(include_password=True) options = celery_app.conf.get('CELERYT_PIKA_OPTIONS', {}) NonBlockingTaskProducer.conn_pool.connect(broker_url, options=options, callback=on_ready) io_loop.add_callback(connect) Allow custon io loops for ConnectionPools
from __future__ import absolute_import import celery from tornado import ioloop from .connection import ConnectionPool from .producer import NonBlockingTaskProducer from .result import AsyncResult VERSION = (0, 3, 0) __version__ = '.'.join(map(str, VERSION)) + '-dev' def setup_nonblocking_producer(celery_app=None, io_loop=None, on_ready=None, result_cls=AsyncResult, limit=1): celery_app = celery_app or celery.current_app io_loop = io_loop or ioloop.IOLoop.instance() NonBlockingTaskProducer.app = celery_app NonBlockingTaskProducer.conn_pool = ConnectionPool(limit, io_loop) NonBlockingTaskProducer.result_cls = result_cls if celery_app.conf['BROKER_URL'] and celery_app.conf['BROKER_URL'].startswith('amqp'): celery.app.amqp.AMQP.producer_cls = NonBlockingTaskProducer def connect(): broker_url = celery_app.connection().as_uri(include_password=True) options = celery_app.conf.get('CELERYT_PIKA_OPTIONS', {}) NonBlockingTaskProducer.conn_pool.connect(broker_url, options=options, callback=on_ready) io_loop.add_callback(connect)
<commit_before>from __future__ import absolute_import import celery from tornado import ioloop from .connection import ConnectionPool from .producer import NonBlockingTaskProducer from .result import AsyncResult VERSION = (0, 3, 0) __version__ = '.'.join(map(str, VERSION)) + '-dev' def setup_nonblocking_producer(celery_app=None, io_loop=None, on_ready=None, result_cls=AsyncResult, limit=1): celery_app = celery_app or celery.current_app io_loop = io_loop or ioloop.IOLoop.instance() NonBlockingTaskProducer.app = celery_app NonBlockingTaskProducer.conn_pool = ConnectionPool(limit=limit) NonBlockingTaskProducer.result_cls = result_cls if celery_app.conf['BROKER_URL'] and celery_app.conf['BROKER_URL'].startswith('amqp'): celery.app.amqp.AMQP.producer_cls = NonBlockingTaskProducer def connect(): broker_url = celery_app.connection().as_uri(include_password=True) options = celery_app.conf.get('CELERYT_PIKA_OPTIONS', {}) NonBlockingTaskProducer.conn_pool.connect(broker_url, options=options, callback=on_ready) io_loop.add_callback(connect) <commit_msg>Allow custon io loops for ConnectionPools<commit_after>
from __future__ import absolute_import import celery from tornado import ioloop from .connection import ConnectionPool from .producer import NonBlockingTaskProducer from .result import AsyncResult VERSION = (0, 3, 0) __version__ = '.'.join(map(str, VERSION)) + '-dev' def setup_nonblocking_producer(celery_app=None, io_loop=None, on_ready=None, result_cls=AsyncResult, limit=1): celery_app = celery_app or celery.current_app io_loop = io_loop or ioloop.IOLoop.instance() NonBlockingTaskProducer.app = celery_app NonBlockingTaskProducer.conn_pool = ConnectionPool(limit, io_loop) NonBlockingTaskProducer.result_cls = result_cls if celery_app.conf['BROKER_URL'] and celery_app.conf['BROKER_URL'].startswith('amqp'): celery.app.amqp.AMQP.producer_cls = NonBlockingTaskProducer def connect(): broker_url = celery_app.connection().as_uri(include_password=True) options = celery_app.conf.get('CELERYT_PIKA_OPTIONS', {}) NonBlockingTaskProducer.conn_pool.connect(broker_url, options=options, callback=on_ready) io_loop.add_callback(connect)
from __future__ import absolute_import import celery from tornado import ioloop from .connection import ConnectionPool from .producer import NonBlockingTaskProducer from .result import AsyncResult VERSION = (0, 3, 0) __version__ = '.'.join(map(str, VERSION)) + '-dev' def setup_nonblocking_producer(celery_app=None, io_loop=None, on_ready=None, result_cls=AsyncResult, limit=1): celery_app = celery_app or celery.current_app io_loop = io_loop or ioloop.IOLoop.instance() NonBlockingTaskProducer.app = celery_app NonBlockingTaskProducer.conn_pool = ConnectionPool(limit=limit) NonBlockingTaskProducer.result_cls = result_cls if celery_app.conf['BROKER_URL'] and celery_app.conf['BROKER_URL'].startswith('amqp'): celery.app.amqp.AMQP.producer_cls = NonBlockingTaskProducer def connect(): broker_url = celery_app.connection().as_uri(include_password=True) options = celery_app.conf.get('CELERYT_PIKA_OPTIONS', {}) NonBlockingTaskProducer.conn_pool.connect(broker_url, options=options, callback=on_ready) io_loop.add_callback(connect) Allow custon io loops for ConnectionPoolsfrom __future__ import absolute_import import celery from tornado import ioloop from .connection import ConnectionPool from .producer import NonBlockingTaskProducer from .result import AsyncResult VERSION = (0, 3, 0) __version__ = '.'.join(map(str, VERSION)) + '-dev' def setup_nonblocking_producer(celery_app=None, io_loop=None, on_ready=None, result_cls=AsyncResult, limit=1): celery_app = celery_app or celery.current_app io_loop = io_loop or ioloop.IOLoop.instance() NonBlockingTaskProducer.app = celery_app NonBlockingTaskProducer.conn_pool = ConnectionPool(limit, io_loop) NonBlockingTaskProducer.result_cls = result_cls if celery_app.conf['BROKER_URL'] and celery_app.conf['BROKER_URL'].startswith('amqp'): celery.app.amqp.AMQP.producer_cls = NonBlockingTaskProducer def connect(): broker_url = celery_app.connection().as_uri(include_password=True) options = celery_app.conf.get('CELERYT_PIKA_OPTIONS', {}) NonBlockingTaskProducer.conn_pool.connect(broker_url, options=options, callback=on_ready) io_loop.add_callback(connect)
<commit_before>from __future__ import absolute_import import celery from tornado import ioloop from .connection import ConnectionPool from .producer import NonBlockingTaskProducer from .result import AsyncResult VERSION = (0, 3, 0) __version__ = '.'.join(map(str, VERSION)) + '-dev' def setup_nonblocking_producer(celery_app=None, io_loop=None, on_ready=None, result_cls=AsyncResult, limit=1): celery_app = celery_app or celery.current_app io_loop = io_loop or ioloop.IOLoop.instance() NonBlockingTaskProducer.app = celery_app NonBlockingTaskProducer.conn_pool = ConnectionPool(limit=limit) NonBlockingTaskProducer.result_cls = result_cls if celery_app.conf['BROKER_URL'] and celery_app.conf['BROKER_URL'].startswith('amqp'): celery.app.amqp.AMQP.producer_cls = NonBlockingTaskProducer def connect(): broker_url = celery_app.connection().as_uri(include_password=True) options = celery_app.conf.get('CELERYT_PIKA_OPTIONS', {}) NonBlockingTaskProducer.conn_pool.connect(broker_url, options=options, callback=on_ready) io_loop.add_callback(connect) <commit_msg>Allow custon io loops for ConnectionPools<commit_after>from __future__ import absolute_import import celery from tornado import ioloop from .connection import ConnectionPool from .producer import NonBlockingTaskProducer from .result import AsyncResult VERSION = (0, 3, 0) __version__ = '.'.join(map(str, VERSION)) + '-dev' def setup_nonblocking_producer(celery_app=None, io_loop=None, on_ready=None, result_cls=AsyncResult, limit=1): celery_app = celery_app or celery.current_app io_loop = io_loop or ioloop.IOLoop.instance() NonBlockingTaskProducer.app = celery_app NonBlockingTaskProducer.conn_pool = ConnectionPool(limit, io_loop) NonBlockingTaskProducer.result_cls = result_cls if celery_app.conf['BROKER_URL'] and celery_app.conf['BROKER_URL'].startswith('amqp'): celery.app.amqp.AMQP.producer_cls = NonBlockingTaskProducer def connect(): broker_url = celery_app.connection().as_uri(include_password=True) options = celery_app.conf.get('CELERYT_PIKA_OPTIONS', {}) NonBlockingTaskProducer.conn_pool.connect(broker_url, options=options, callback=on_ready) io_loop.add_callback(connect)
87545718c9178d1d25e51128ca8cdb9c4bb466fb
version.py
version.py
major = 0 minor=0 patch=14 branch="master" timestamp=1376507766.02
major = 0 minor=0 patch=15 branch="master" timestamp=1376507862.77
Tag commit for v0.0.15-master generated by gitmake.py
Tag commit for v0.0.15-master generated by gitmake.py
Python
mit
ryansturmer/gitmake
major = 0 minor=0 patch=14 branch="master" timestamp=1376507766.02Tag commit for v0.0.15-master generated by gitmake.py
major = 0 minor=0 patch=15 branch="master" timestamp=1376507862.77
<commit_before>major = 0 minor=0 patch=14 branch="master" timestamp=1376507766.02<commit_msg>Tag commit for v0.0.15-master generated by gitmake.py<commit_after>
major = 0 minor=0 patch=15 branch="master" timestamp=1376507862.77
major = 0 minor=0 patch=14 branch="master" timestamp=1376507766.02Tag commit for v0.0.15-master generated by gitmake.pymajor = 0 minor=0 patch=15 branch="master" timestamp=1376507862.77
<commit_before>major = 0 minor=0 patch=14 branch="master" timestamp=1376507766.02<commit_msg>Tag commit for v0.0.15-master generated by gitmake.py<commit_after>major = 0 minor=0 patch=15 branch="master" timestamp=1376507862.77
aa8c94bfa63aab1779e280d6695c3a259e290c8b
test/test_flvlib.py
test/test_flvlib.py
import unittest import test_primitives, test_astypes def get_suite(): primitives = unittest.TestLoader().loadTestsFromModule(test_primitives) astypes = unittest.TestLoader().loadTestsFromModule(test_astypes) return unittest.TestSuite([primitives, astypes]) def main(): unittest.TextTestRunner(verbosity=2).run(get_suite()) if __name__ == "__main__": main()
import unittest import test_primitives, test_astypes, test_helpers def get_suite(): modules = (test_primitives, test_astypes, test_helpers) suites = [unittest.TestLoader().loadTestsFromModule(module) for module in modules] return unittest.TestSuite(suites) def main(): unittest.TextTestRunner(verbosity=2).run(get_suite()) if __name__ == "__main__": main()
Include the helpers module tests in the full library testsuite.
Include the helpers module tests in the full library testsuite.
Python
mit
wulczer/flvlib
import unittest import test_primitives, test_astypes def get_suite(): primitives = unittest.TestLoader().loadTestsFromModule(test_primitives) astypes = unittest.TestLoader().loadTestsFromModule(test_astypes) return unittest.TestSuite([primitives, astypes]) def main(): unittest.TextTestRunner(verbosity=2).run(get_suite()) if __name__ == "__main__": main() Include the helpers module tests in the full library testsuite.
import unittest import test_primitives, test_astypes, test_helpers def get_suite(): modules = (test_primitives, test_astypes, test_helpers) suites = [unittest.TestLoader().loadTestsFromModule(module) for module in modules] return unittest.TestSuite(suites) def main(): unittest.TextTestRunner(verbosity=2).run(get_suite()) if __name__ == "__main__": main()
<commit_before>import unittest import test_primitives, test_astypes def get_suite(): primitives = unittest.TestLoader().loadTestsFromModule(test_primitives) astypes = unittest.TestLoader().loadTestsFromModule(test_astypes) return unittest.TestSuite([primitives, astypes]) def main(): unittest.TextTestRunner(verbosity=2).run(get_suite()) if __name__ == "__main__": main() <commit_msg>Include the helpers module tests in the full library testsuite.<commit_after>
import unittest import test_primitives, test_astypes, test_helpers def get_suite(): modules = (test_primitives, test_astypes, test_helpers) suites = [unittest.TestLoader().loadTestsFromModule(module) for module in modules] return unittest.TestSuite(suites) def main(): unittest.TextTestRunner(verbosity=2).run(get_suite()) if __name__ == "__main__": main()
import unittest import test_primitives, test_astypes def get_suite(): primitives = unittest.TestLoader().loadTestsFromModule(test_primitives) astypes = unittest.TestLoader().loadTestsFromModule(test_astypes) return unittest.TestSuite([primitives, astypes]) def main(): unittest.TextTestRunner(verbosity=2).run(get_suite()) if __name__ == "__main__": main() Include the helpers module tests in the full library testsuite.import unittest import test_primitives, test_astypes, test_helpers def get_suite(): modules = (test_primitives, test_astypes, test_helpers) suites = [unittest.TestLoader().loadTestsFromModule(module) for module in modules] return unittest.TestSuite(suites) def main(): unittest.TextTestRunner(verbosity=2).run(get_suite()) if __name__ == "__main__": main()
<commit_before>import unittest import test_primitives, test_astypes def get_suite(): primitives = unittest.TestLoader().loadTestsFromModule(test_primitives) astypes = unittest.TestLoader().loadTestsFromModule(test_astypes) return unittest.TestSuite([primitives, astypes]) def main(): unittest.TextTestRunner(verbosity=2).run(get_suite()) if __name__ == "__main__": main() <commit_msg>Include the helpers module tests in the full library testsuite.<commit_after>import unittest import test_primitives, test_astypes, test_helpers def get_suite(): modules = (test_primitives, test_astypes, test_helpers) suites = [unittest.TestLoader().loadTestsFromModule(module) for module in modules] return unittest.TestSuite(suites) def main(): unittest.TextTestRunner(verbosity=2).run(get_suite()) if __name__ == "__main__": main()
aafff9f089b92137c8827addaff278da94edec45
base/components/people/constants.py
base/components/people/constants.py
from model_utils import Choices from ohashi.constants import OTHER BLOOD_TYPE = Choices('A', 'B', 'O', 'AB') CLASSIFICATIONS = Choices( (1, 'major', 'Major Unit'), (2, 'minor', 'Minor Unit'), (3, 'shuffle', 'Shuffle Unit'), (4, 'temporary', 'Temporary Unit'), (5, 'subunit', 'Sub-Unit'), (6, 'revival', 'Revival Unit'), (7, 'supergroup', 'Supergroup'), (OTHER, 'other', 'Other') ) # This is a hard-coded constant because of the Hello Pro Kenshuusei, the only # "group" classified as Hello! Project that is not a major group. HELLO_PROJECT_GROUPS = [1, 2, 3, 52, 54] PHOTO_SOURCES = Choices( (1, 'promotional', 'Promotional Photo'), (2, 'blog', 'Blog Photo'), (OTHER, 'other', 'Other') ) SCOPE = Choices( (1, 'hp', 'Hello! Project'), (2, 'ufa', 'Up Front Agency'), (OTHER, 'other', 'Other') ) STATUS = Choices( (1, 'active', 'Active'), (2, 'former', 'Former'), (OTHER, 'other', 'Other') )
from model_utils import Choices from ohashi.constants import OTHER BLOOD_TYPE = Choices('A', 'B', 'O', 'AB') CLASSIFICATIONS = Choices( (1, 'major', 'Major Unit'), (2, 'minor', 'Minor Unit'), (3, 'shuffle', 'Shuffle Unit'), (4, 'temporary', 'Temporary Unit'), (5, 'subunit', 'Sub-Unit'), (6, 'revival', 'Revival Unit'), (7, 'supergroup', 'Supergroup'), (OTHER, 'other', 'Other') ) # This is a hard-coded constant because of the Hello Pro Kenshuusei, the only # "group" classified as Hello! Project that is not a major group. HELLO_PROJECT_GROUPS = [1, 2, 3, 52, 54] PHOTO_SOURCES = Choices( (1, 'promotional', 'Promotional Photo'), (2, 'blog', 'Blog Photo'), (OTHER, 'other', 'Other') ) SCOPE = Choices( (1, 'hp', 'Hello! Project'), (2, 'ufa', 'Up Front Agency'), (3, 'satoyama', 'Satoyama Movement'), (OTHER, 'other', 'Other') ) STATUS = Choices( (1, 'active', 'Active'), (2, 'former', 'Former'), (OTHER, 'other', 'Other') )
Make the Satoyama Movement a scope.
Make the Satoyama Movement a scope.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
from model_utils import Choices from ohashi.constants import OTHER BLOOD_TYPE = Choices('A', 'B', 'O', 'AB') CLASSIFICATIONS = Choices( (1, 'major', 'Major Unit'), (2, 'minor', 'Minor Unit'), (3, 'shuffle', 'Shuffle Unit'), (4, 'temporary', 'Temporary Unit'), (5, 'subunit', 'Sub-Unit'), (6, 'revival', 'Revival Unit'), (7, 'supergroup', 'Supergroup'), (OTHER, 'other', 'Other') ) # This is a hard-coded constant because of the Hello Pro Kenshuusei, the only # "group" classified as Hello! Project that is not a major group. HELLO_PROJECT_GROUPS = [1, 2, 3, 52, 54] PHOTO_SOURCES = Choices( (1, 'promotional', 'Promotional Photo'), (2, 'blog', 'Blog Photo'), (OTHER, 'other', 'Other') ) SCOPE = Choices( (1, 'hp', 'Hello! Project'), (2, 'ufa', 'Up Front Agency'), (OTHER, 'other', 'Other') ) STATUS = Choices( (1, 'active', 'Active'), (2, 'former', 'Former'), (OTHER, 'other', 'Other') ) Make the Satoyama Movement a scope.
from model_utils import Choices from ohashi.constants import OTHER BLOOD_TYPE = Choices('A', 'B', 'O', 'AB') CLASSIFICATIONS = Choices( (1, 'major', 'Major Unit'), (2, 'minor', 'Minor Unit'), (3, 'shuffle', 'Shuffle Unit'), (4, 'temporary', 'Temporary Unit'), (5, 'subunit', 'Sub-Unit'), (6, 'revival', 'Revival Unit'), (7, 'supergroup', 'Supergroup'), (OTHER, 'other', 'Other') ) # This is a hard-coded constant because of the Hello Pro Kenshuusei, the only # "group" classified as Hello! Project that is not a major group. HELLO_PROJECT_GROUPS = [1, 2, 3, 52, 54] PHOTO_SOURCES = Choices( (1, 'promotional', 'Promotional Photo'), (2, 'blog', 'Blog Photo'), (OTHER, 'other', 'Other') ) SCOPE = Choices( (1, 'hp', 'Hello! Project'), (2, 'ufa', 'Up Front Agency'), (3, 'satoyama', 'Satoyama Movement'), (OTHER, 'other', 'Other') ) STATUS = Choices( (1, 'active', 'Active'), (2, 'former', 'Former'), (OTHER, 'other', 'Other') )
<commit_before>from model_utils import Choices from ohashi.constants import OTHER BLOOD_TYPE = Choices('A', 'B', 'O', 'AB') CLASSIFICATIONS = Choices( (1, 'major', 'Major Unit'), (2, 'minor', 'Minor Unit'), (3, 'shuffle', 'Shuffle Unit'), (4, 'temporary', 'Temporary Unit'), (5, 'subunit', 'Sub-Unit'), (6, 'revival', 'Revival Unit'), (7, 'supergroup', 'Supergroup'), (OTHER, 'other', 'Other') ) # This is a hard-coded constant because of the Hello Pro Kenshuusei, the only # "group" classified as Hello! Project that is not a major group. HELLO_PROJECT_GROUPS = [1, 2, 3, 52, 54] PHOTO_SOURCES = Choices( (1, 'promotional', 'Promotional Photo'), (2, 'blog', 'Blog Photo'), (OTHER, 'other', 'Other') ) SCOPE = Choices( (1, 'hp', 'Hello! Project'), (2, 'ufa', 'Up Front Agency'), (OTHER, 'other', 'Other') ) STATUS = Choices( (1, 'active', 'Active'), (2, 'former', 'Former'), (OTHER, 'other', 'Other') ) <commit_msg>Make the Satoyama Movement a scope.<commit_after>
from model_utils import Choices from ohashi.constants import OTHER BLOOD_TYPE = Choices('A', 'B', 'O', 'AB') CLASSIFICATIONS = Choices( (1, 'major', 'Major Unit'), (2, 'minor', 'Minor Unit'), (3, 'shuffle', 'Shuffle Unit'), (4, 'temporary', 'Temporary Unit'), (5, 'subunit', 'Sub-Unit'), (6, 'revival', 'Revival Unit'), (7, 'supergroup', 'Supergroup'), (OTHER, 'other', 'Other') ) # This is a hard-coded constant because of the Hello Pro Kenshuusei, the only # "group" classified as Hello! Project that is not a major group. HELLO_PROJECT_GROUPS = [1, 2, 3, 52, 54] PHOTO_SOURCES = Choices( (1, 'promotional', 'Promotional Photo'), (2, 'blog', 'Blog Photo'), (OTHER, 'other', 'Other') ) SCOPE = Choices( (1, 'hp', 'Hello! Project'), (2, 'ufa', 'Up Front Agency'), (3, 'satoyama', 'Satoyama Movement'), (OTHER, 'other', 'Other') ) STATUS = Choices( (1, 'active', 'Active'), (2, 'former', 'Former'), (OTHER, 'other', 'Other') )
from model_utils import Choices from ohashi.constants import OTHER BLOOD_TYPE = Choices('A', 'B', 'O', 'AB') CLASSIFICATIONS = Choices( (1, 'major', 'Major Unit'), (2, 'minor', 'Minor Unit'), (3, 'shuffle', 'Shuffle Unit'), (4, 'temporary', 'Temporary Unit'), (5, 'subunit', 'Sub-Unit'), (6, 'revival', 'Revival Unit'), (7, 'supergroup', 'Supergroup'), (OTHER, 'other', 'Other') ) # This is a hard-coded constant because of the Hello Pro Kenshuusei, the only # "group" classified as Hello! Project that is not a major group. HELLO_PROJECT_GROUPS = [1, 2, 3, 52, 54] PHOTO_SOURCES = Choices( (1, 'promotional', 'Promotional Photo'), (2, 'blog', 'Blog Photo'), (OTHER, 'other', 'Other') ) SCOPE = Choices( (1, 'hp', 'Hello! Project'), (2, 'ufa', 'Up Front Agency'), (OTHER, 'other', 'Other') ) STATUS = Choices( (1, 'active', 'Active'), (2, 'former', 'Former'), (OTHER, 'other', 'Other') ) Make the Satoyama Movement a scope.from model_utils import Choices from ohashi.constants import OTHER BLOOD_TYPE = Choices('A', 'B', 'O', 'AB') CLASSIFICATIONS = Choices( (1, 'major', 'Major Unit'), (2, 'minor', 'Minor Unit'), (3, 'shuffle', 'Shuffle Unit'), (4, 'temporary', 'Temporary Unit'), (5, 'subunit', 'Sub-Unit'), (6, 'revival', 'Revival Unit'), (7, 'supergroup', 'Supergroup'), (OTHER, 'other', 'Other') ) # This is a hard-coded constant because of the Hello Pro Kenshuusei, the only # "group" classified as Hello! Project that is not a major group. HELLO_PROJECT_GROUPS = [1, 2, 3, 52, 54] PHOTO_SOURCES = Choices( (1, 'promotional', 'Promotional Photo'), (2, 'blog', 'Blog Photo'), (OTHER, 'other', 'Other') ) SCOPE = Choices( (1, 'hp', 'Hello! Project'), (2, 'ufa', 'Up Front Agency'), (3, 'satoyama', 'Satoyama Movement'), (OTHER, 'other', 'Other') ) STATUS = Choices( (1, 'active', 'Active'), (2, 'former', 'Former'), (OTHER, 'other', 'Other') )
<commit_before>from model_utils import Choices from ohashi.constants import OTHER BLOOD_TYPE = Choices('A', 'B', 'O', 'AB') CLASSIFICATIONS = Choices( (1, 'major', 'Major Unit'), (2, 'minor', 'Minor Unit'), (3, 'shuffle', 'Shuffle Unit'), (4, 'temporary', 'Temporary Unit'), (5, 'subunit', 'Sub-Unit'), (6, 'revival', 'Revival Unit'), (7, 'supergroup', 'Supergroup'), (OTHER, 'other', 'Other') ) # This is a hard-coded constant because of the Hello Pro Kenshuusei, the only # "group" classified as Hello! Project that is not a major group. HELLO_PROJECT_GROUPS = [1, 2, 3, 52, 54] PHOTO_SOURCES = Choices( (1, 'promotional', 'Promotional Photo'), (2, 'blog', 'Blog Photo'), (OTHER, 'other', 'Other') ) SCOPE = Choices( (1, 'hp', 'Hello! Project'), (2, 'ufa', 'Up Front Agency'), (OTHER, 'other', 'Other') ) STATUS = Choices( (1, 'active', 'Active'), (2, 'former', 'Former'), (OTHER, 'other', 'Other') ) <commit_msg>Make the Satoyama Movement a scope.<commit_after>from model_utils import Choices from ohashi.constants import OTHER BLOOD_TYPE = Choices('A', 'B', 'O', 'AB') CLASSIFICATIONS = Choices( (1, 'major', 'Major Unit'), (2, 'minor', 'Minor Unit'), (3, 'shuffle', 'Shuffle Unit'), (4, 'temporary', 'Temporary Unit'), (5, 'subunit', 'Sub-Unit'), (6, 'revival', 'Revival Unit'), (7, 'supergroup', 'Supergroup'), (OTHER, 'other', 'Other') ) # This is a hard-coded constant because of the Hello Pro Kenshuusei, the only # "group" classified as Hello! Project that is not a major group. HELLO_PROJECT_GROUPS = [1, 2, 3, 52, 54] PHOTO_SOURCES = Choices( (1, 'promotional', 'Promotional Photo'), (2, 'blog', 'Blog Photo'), (OTHER, 'other', 'Other') ) SCOPE = Choices( (1, 'hp', 'Hello! Project'), (2, 'ufa', 'Up Front Agency'), (3, 'satoyama', 'Satoyama Movement'), (OTHER, 'other', 'Other') ) STATUS = Choices( (1, 'active', 'Active'), (2, 'former', 'Former'), (OTHER, 'other', 'Other') )
fb335ed74d9d924816fe6bf712844023abf62e30
address_book/person.py
address_book/person.py
__all__ = ['Person'] class Person(object): pass
__all__ = ['Person'] class Person(object): def __init__(self, first_name, last_name, addresses, phone_numbers): self.first_name = first_name self.last_name = last_name self.addresses = addresses self.phone_numbers = phone_numbers
Add constructor with required arguments to the `Person` class
Add constructor with required arguments to the `Person` class
Python
mit
dizpers/python-address-book-assignment
__all__ = ['Person'] class Person(object): passAdd constructor with required arguments to the `Person` class
__all__ = ['Person'] class Person(object): def __init__(self, first_name, last_name, addresses, phone_numbers): self.first_name = first_name self.last_name = last_name self.addresses = addresses self.phone_numbers = phone_numbers
<commit_before>__all__ = ['Person'] class Person(object): pass<commit_msg>Add constructor with required arguments to the `Person` class<commit_after>
__all__ = ['Person'] class Person(object): def __init__(self, first_name, last_name, addresses, phone_numbers): self.first_name = first_name self.last_name = last_name self.addresses = addresses self.phone_numbers = phone_numbers
__all__ = ['Person'] class Person(object): passAdd constructor with required arguments to the `Person` class__all__ = ['Person'] class Person(object): def __init__(self, first_name, last_name, addresses, phone_numbers): self.first_name = first_name self.last_name = last_name self.addresses = addresses self.phone_numbers = phone_numbers
<commit_before>__all__ = ['Person'] class Person(object): pass<commit_msg>Add constructor with required arguments to the `Person` class<commit_after>__all__ = ['Person'] class Person(object): def __init__(self, first_name, last_name, addresses, phone_numbers): self.first_name = first_name self.last_name = last_name self.addresses = addresses self.phone_numbers = phone_numbers
e26109802eab5777602bab836c8c88cb8ee0fe89
openedx/stanford/cms/envs/aws.py
openedx/stanford/cms/envs/aws.py
from cms.envs.aws import * from lms.envs.common import COURSE_MODE_DEFAULTS CMS_BASE = ENV_TOKENS.get( 'CMS_BASE', ) COPYRIGHT_EMAIL = ENV_TOKENS.get( 'COPYRIGHT_EMAIL', COPYRIGHT_EMAIL ) DEFAULT_COURSE_ABOUT_IMAGE_URL = ENV_TOKENS.get( 'DEFAULT_COURSE_ABOUT_IMAGE_URL', DEFAULT_COURSE_ABOUT_IMAGE_URL ) EXTRA_MIMETYPES = ENV_TOKENS.get('EXTRA_MIMETYPES', EXTRA_MIMETYPES) SHIB_ONLY_SITE = ENV_TOKENS.get( 'SHIB_ONLY_SITE', SHIB_ONLY_SITE ) SHIB_REDIRECT_DOMAIN_WHITELIST = ENV_TOKENS.get( 'SHIB_REDIRECT_DOMAIN_WHITELIST', SHIB_REDIRECT_DOMAIN_WHITELIST ) XBLOCKS_ALWAYS_IN_STUDIO = ENV_TOKENS.get( 'XBLOCKS_ALWAYS_IN_STUDIO', XBLOCKS_ALWAYS_IN_STUDIO ) INSTRUCTOR_QUERY_PROBLEM_TYPES = ENV_TOKENS.get( 'INSTRUCTOR_QUERY_PROBLEM_TYPES', INSTRUCTOR_QUERY_PROBLEM_TYPES )
from cms.envs.aws import * from lms.envs.aws import COURSE_MODE_DEFAULTS CMS_BASE = ENV_TOKENS.get( 'CMS_BASE', ) COPYRIGHT_EMAIL = ENV_TOKENS.get( 'COPYRIGHT_EMAIL', COPYRIGHT_EMAIL ) DEFAULT_COURSE_ABOUT_IMAGE_URL = ENV_TOKENS.get( 'DEFAULT_COURSE_ABOUT_IMAGE_URL', DEFAULT_COURSE_ABOUT_IMAGE_URL ) EXTRA_MIMETYPES = ENV_TOKENS.get('EXTRA_MIMETYPES', EXTRA_MIMETYPES) SHIB_ONLY_SITE = ENV_TOKENS.get( 'SHIB_ONLY_SITE', SHIB_ONLY_SITE ) SHIB_REDIRECT_DOMAIN_WHITELIST = ENV_TOKENS.get( 'SHIB_REDIRECT_DOMAIN_WHITELIST', SHIB_REDIRECT_DOMAIN_WHITELIST ) XBLOCKS_ALWAYS_IN_STUDIO = ENV_TOKENS.get( 'XBLOCKS_ALWAYS_IN_STUDIO', XBLOCKS_ALWAYS_IN_STUDIO ) INSTRUCTOR_QUERY_PROBLEM_TYPES = ENV_TOKENS.get( 'INSTRUCTOR_QUERY_PROBLEM_TYPES', INSTRUCTOR_QUERY_PROBLEM_TYPES )
Fix course mode settings import
Fix course mode settings import Without this, we were pulling edx's default (audit) from common, instead of pulling "ours" from aws/json (honor).
Python
agpl-3.0
Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform
from cms.envs.aws import * from lms.envs.common import COURSE_MODE_DEFAULTS CMS_BASE = ENV_TOKENS.get( 'CMS_BASE', ) COPYRIGHT_EMAIL = ENV_TOKENS.get( 'COPYRIGHT_EMAIL', COPYRIGHT_EMAIL ) DEFAULT_COURSE_ABOUT_IMAGE_URL = ENV_TOKENS.get( 'DEFAULT_COURSE_ABOUT_IMAGE_URL', DEFAULT_COURSE_ABOUT_IMAGE_URL ) EXTRA_MIMETYPES = ENV_TOKENS.get('EXTRA_MIMETYPES', EXTRA_MIMETYPES) SHIB_ONLY_SITE = ENV_TOKENS.get( 'SHIB_ONLY_SITE', SHIB_ONLY_SITE ) SHIB_REDIRECT_DOMAIN_WHITELIST = ENV_TOKENS.get( 'SHIB_REDIRECT_DOMAIN_WHITELIST', SHIB_REDIRECT_DOMAIN_WHITELIST ) XBLOCKS_ALWAYS_IN_STUDIO = ENV_TOKENS.get( 'XBLOCKS_ALWAYS_IN_STUDIO', XBLOCKS_ALWAYS_IN_STUDIO ) INSTRUCTOR_QUERY_PROBLEM_TYPES = ENV_TOKENS.get( 'INSTRUCTOR_QUERY_PROBLEM_TYPES', INSTRUCTOR_QUERY_PROBLEM_TYPES ) Fix course mode settings import Without this, we were pulling edx's default (audit) from common, instead of pulling "ours" from aws/json (honor).
from cms.envs.aws import * from lms.envs.aws import COURSE_MODE_DEFAULTS CMS_BASE = ENV_TOKENS.get( 'CMS_BASE', ) COPYRIGHT_EMAIL = ENV_TOKENS.get( 'COPYRIGHT_EMAIL', COPYRIGHT_EMAIL ) DEFAULT_COURSE_ABOUT_IMAGE_URL = ENV_TOKENS.get( 'DEFAULT_COURSE_ABOUT_IMAGE_URL', DEFAULT_COURSE_ABOUT_IMAGE_URL ) EXTRA_MIMETYPES = ENV_TOKENS.get('EXTRA_MIMETYPES', EXTRA_MIMETYPES) SHIB_ONLY_SITE = ENV_TOKENS.get( 'SHIB_ONLY_SITE', SHIB_ONLY_SITE ) SHIB_REDIRECT_DOMAIN_WHITELIST = ENV_TOKENS.get( 'SHIB_REDIRECT_DOMAIN_WHITELIST', SHIB_REDIRECT_DOMAIN_WHITELIST ) XBLOCKS_ALWAYS_IN_STUDIO = ENV_TOKENS.get( 'XBLOCKS_ALWAYS_IN_STUDIO', XBLOCKS_ALWAYS_IN_STUDIO ) INSTRUCTOR_QUERY_PROBLEM_TYPES = ENV_TOKENS.get( 'INSTRUCTOR_QUERY_PROBLEM_TYPES', INSTRUCTOR_QUERY_PROBLEM_TYPES )
<commit_before>from cms.envs.aws import * from lms.envs.common import COURSE_MODE_DEFAULTS CMS_BASE = ENV_TOKENS.get( 'CMS_BASE', ) COPYRIGHT_EMAIL = ENV_TOKENS.get( 'COPYRIGHT_EMAIL', COPYRIGHT_EMAIL ) DEFAULT_COURSE_ABOUT_IMAGE_URL = ENV_TOKENS.get( 'DEFAULT_COURSE_ABOUT_IMAGE_URL', DEFAULT_COURSE_ABOUT_IMAGE_URL ) EXTRA_MIMETYPES = ENV_TOKENS.get('EXTRA_MIMETYPES', EXTRA_MIMETYPES) SHIB_ONLY_SITE = ENV_TOKENS.get( 'SHIB_ONLY_SITE', SHIB_ONLY_SITE ) SHIB_REDIRECT_DOMAIN_WHITELIST = ENV_TOKENS.get( 'SHIB_REDIRECT_DOMAIN_WHITELIST', SHIB_REDIRECT_DOMAIN_WHITELIST ) XBLOCKS_ALWAYS_IN_STUDIO = ENV_TOKENS.get( 'XBLOCKS_ALWAYS_IN_STUDIO', XBLOCKS_ALWAYS_IN_STUDIO ) INSTRUCTOR_QUERY_PROBLEM_TYPES = ENV_TOKENS.get( 'INSTRUCTOR_QUERY_PROBLEM_TYPES', INSTRUCTOR_QUERY_PROBLEM_TYPES ) <commit_msg>Fix course mode settings import Without this, we were pulling edx's default (audit) from common, instead of pulling "ours" from aws/json (honor).<commit_after>
from cms.envs.aws import * from lms.envs.aws import COURSE_MODE_DEFAULTS CMS_BASE = ENV_TOKENS.get( 'CMS_BASE', ) COPYRIGHT_EMAIL = ENV_TOKENS.get( 'COPYRIGHT_EMAIL', COPYRIGHT_EMAIL ) DEFAULT_COURSE_ABOUT_IMAGE_URL = ENV_TOKENS.get( 'DEFAULT_COURSE_ABOUT_IMAGE_URL', DEFAULT_COURSE_ABOUT_IMAGE_URL ) EXTRA_MIMETYPES = ENV_TOKENS.get('EXTRA_MIMETYPES', EXTRA_MIMETYPES) SHIB_ONLY_SITE = ENV_TOKENS.get( 'SHIB_ONLY_SITE', SHIB_ONLY_SITE ) SHIB_REDIRECT_DOMAIN_WHITELIST = ENV_TOKENS.get( 'SHIB_REDIRECT_DOMAIN_WHITELIST', SHIB_REDIRECT_DOMAIN_WHITELIST ) XBLOCKS_ALWAYS_IN_STUDIO = ENV_TOKENS.get( 'XBLOCKS_ALWAYS_IN_STUDIO', XBLOCKS_ALWAYS_IN_STUDIO ) INSTRUCTOR_QUERY_PROBLEM_TYPES = ENV_TOKENS.get( 'INSTRUCTOR_QUERY_PROBLEM_TYPES', INSTRUCTOR_QUERY_PROBLEM_TYPES )
from cms.envs.aws import * from lms.envs.common import COURSE_MODE_DEFAULTS CMS_BASE = ENV_TOKENS.get( 'CMS_BASE', ) COPYRIGHT_EMAIL = ENV_TOKENS.get( 'COPYRIGHT_EMAIL', COPYRIGHT_EMAIL ) DEFAULT_COURSE_ABOUT_IMAGE_URL = ENV_TOKENS.get( 'DEFAULT_COURSE_ABOUT_IMAGE_URL', DEFAULT_COURSE_ABOUT_IMAGE_URL ) EXTRA_MIMETYPES = ENV_TOKENS.get('EXTRA_MIMETYPES', EXTRA_MIMETYPES) SHIB_ONLY_SITE = ENV_TOKENS.get( 'SHIB_ONLY_SITE', SHIB_ONLY_SITE ) SHIB_REDIRECT_DOMAIN_WHITELIST = ENV_TOKENS.get( 'SHIB_REDIRECT_DOMAIN_WHITELIST', SHIB_REDIRECT_DOMAIN_WHITELIST ) XBLOCKS_ALWAYS_IN_STUDIO = ENV_TOKENS.get( 'XBLOCKS_ALWAYS_IN_STUDIO', XBLOCKS_ALWAYS_IN_STUDIO ) INSTRUCTOR_QUERY_PROBLEM_TYPES = ENV_TOKENS.get( 'INSTRUCTOR_QUERY_PROBLEM_TYPES', INSTRUCTOR_QUERY_PROBLEM_TYPES ) Fix course mode settings import Without this, we were pulling edx's default (audit) from common, instead of pulling "ours" from aws/json (honor).from cms.envs.aws import * from lms.envs.aws import COURSE_MODE_DEFAULTS CMS_BASE = ENV_TOKENS.get( 'CMS_BASE', ) COPYRIGHT_EMAIL = ENV_TOKENS.get( 'COPYRIGHT_EMAIL', COPYRIGHT_EMAIL ) DEFAULT_COURSE_ABOUT_IMAGE_URL = ENV_TOKENS.get( 'DEFAULT_COURSE_ABOUT_IMAGE_URL', DEFAULT_COURSE_ABOUT_IMAGE_URL ) EXTRA_MIMETYPES = ENV_TOKENS.get('EXTRA_MIMETYPES', EXTRA_MIMETYPES) SHIB_ONLY_SITE = ENV_TOKENS.get( 'SHIB_ONLY_SITE', SHIB_ONLY_SITE ) SHIB_REDIRECT_DOMAIN_WHITELIST = ENV_TOKENS.get( 'SHIB_REDIRECT_DOMAIN_WHITELIST', SHIB_REDIRECT_DOMAIN_WHITELIST ) XBLOCKS_ALWAYS_IN_STUDIO = ENV_TOKENS.get( 'XBLOCKS_ALWAYS_IN_STUDIO', XBLOCKS_ALWAYS_IN_STUDIO ) INSTRUCTOR_QUERY_PROBLEM_TYPES = ENV_TOKENS.get( 'INSTRUCTOR_QUERY_PROBLEM_TYPES', INSTRUCTOR_QUERY_PROBLEM_TYPES )
<commit_before>from cms.envs.aws import * from lms.envs.common import COURSE_MODE_DEFAULTS CMS_BASE = ENV_TOKENS.get( 'CMS_BASE', ) COPYRIGHT_EMAIL = ENV_TOKENS.get( 'COPYRIGHT_EMAIL', COPYRIGHT_EMAIL ) DEFAULT_COURSE_ABOUT_IMAGE_URL = ENV_TOKENS.get( 'DEFAULT_COURSE_ABOUT_IMAGE_URL', DEFAULT_COURSE_ABOUT_IMAGE_URL ) EXTRA_MIMETYPES = ENV_TOKENS.get('EXTRA_MIMETYPES', EXTRA_MIMETYPES) SHIB_ONLY_SITE = ENV_TOKENS.get( 'SHIB_ONLY_SITE', SHIB_ONLY_SITE ) SHIB_REDIRECT_DOMAIN_WHITELIST = ENV_TOKENS.get( 'SHIB_REDIRECT_DOMAIN_WHITELIST', SHIB_REDIRECT_DOMAIN_WHITELIST ) XBLOCKS_ALWAYS_IN_STUDIO = ENV_TOKENS.get( 'XBLOCKS_ALWAYS_IN_STUDIO', XBLOCKS_ALWAYS_IN_STUDIO ) INSTRUCTOR_QUERY_PROBLEM_TYPES = ENV_TOKENS.get( 'INSTRUCTOR_QUERY_PROBLEM_TYPES', INSTRUCTOR_QUERY_PROBLEM_TYPES ) <commit_msg>Fix course mode settings import Without this, we were pulling edx's default (audit) from common, instead of pulling "ours" from aws/json (honor).<commit_after>from cms.envs.aws import * from lms.envs.aws import COURSE_MODE_DEFAULTS CMS_BASE = ENV_TOKENS.get( 'CMS_BASE', ) COPYRIGHT_EMAIL = ENV_TOKENS.get( 'COPYRIGHT_EMAIL', COPYRIGHT_EMAIL ) DEFAULT_COURSE_ABOUT_IMAGE_URL = ENV_TOKENS.get( 'DEFAULT_COURSE_ABOUT_IMAGE_URL', DEFAULT_COURSE_ABOUT_IMAGE_URL ) EXTRA_MIMETYPES = ENV_TOKENS.get('EXTRA_MIMETYPES', EXTRA_MIMETYPES) SHIB_ONLY_SITE = ENV_TOKENS.get( 'SHIB_ONLY_SITE', SHIB_ONLY_SITE ) SHIB_REDIRECT_DOMAIN_WHITELIST = ENV_TOKENS.get( 'SHIB_REDIRECT_DOMAIN_WHITELIST', SHIB_REDIRECT_DOMAIN_WHITELIST ) XBLOCKS_ALWAYS_IN_STUDIO = ENV_TOKENS.get( 'XBLOCKS_ALWAYS_IN_STUDIO', XBLOCKS_ALWAYS_IN_STUDIO ) INSTRUCTOR_QUERY_PROBLEM_TYPES = ENV_TOKENS.get( 'INSTRUCTOR_QUERY_PROBLEM_TYPES', INSTRUCTOR_QUERY_PROBLEM_TYPES )
74ec59b48b8a0bd7bac9d0eada4caa463a897d08
playground/settings.py
playground/settings.py
""" Eve playground settings """ DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground"
""" Eve playground settings """ DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, # Example of a scoped resource "projects": { "url": "accounts/<regex('[a-f0-9]{24}'):owner>/projects", "schema": { "name": { "type": "string", }, "owner": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground"
Add example of a scoped resource
Add example of a scoped resource Add the Project resource and set the `url` setting in the domain to allow it to sit as a sub resource under accounts. See: http://python-eve.org/features.html#sub-resources
Python
mit
proxama/eve-playground
""" Eve playground settings """ DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground" Add example of a scoped resource Add the Project resource and set the `url` setting in the domain to allow it to sit as a sub resource under accounts. See: http://python-eve.org/features.html#sub-resources
""" Eve playground settings """ DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, # Example of a scoped resource "projects": { "url": "accounts/<regex('[a-f0-9]{24}'):owner>/projects", "schema": { "name": { "type": "string", }, "owner": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground"
<commit_before>""" Eve playground settings """ DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground" <commit_msg>Add example of a scoped resource Add the Project resource and set the `url` setting in the domain to allow it to sit as a sub resource under accounts. See: http://python-eve.org/features.html#sub-resources<commit_after>
""" Eve playground settings """ DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, # Example of a scoped resource "projects": { "url": "accounts/<regex('[a-f0-9]{24}'):owner>/projects", "schema": { "name": { "type": "string", }, "owner": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground"
""" Eve playground settings """ DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground" Add example of a scoped resource Add the Project resource and set the `url` setting in the domain to allow it to sit as a sub resource under accounts. See: http://python-eve.org/features.html#sub-resources""" Eve playground settings """ DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, # Example of a scoped resource "projects": { "url": "accounts/<regex('[a-f0-9]{24}'):owner>/projects", "schema": { "name": { "type": "string", }, "owner": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground"
<commit_before>""" Eve playground settings """ DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground" <commit_msg>Add example of a scoped resource Add the Project resource and set the `url` setting in the domain to allow it to sit as a sub resource under accounts. See: http://python-eve.org/features.html#sub-resources<commit_after>""" Eve playground settings """ DOMAIN = { "accounts": { "schema": { "name": { "type": "string", }, "can_manage": { "type": "list", "schema": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, }, # Example of a scoped resource "projects": { "url": "accounts/<regex('[a-f0-9]{24}'):owner>/projects", "schema": { "name": { "type": "string", }, "owner": { "type": "objectid", "data_relation": { "resource": "accounts", "field": "_id", "embeddable": True, }, }, }, }, } RESOURCE_METHODS = ["GET", "POST"] ITEM_METHODS = ["GET", "PATCH"] MONGO_HOST = "db" MONGO_PORT = 27017 MONGO_DBNAME = "playground"
1c2fc06fe61f4f512dc2e5bca412e123fa17fb9b
plenum/__metadata__.py
plenum/__metadata__.py
""" plenum package metadata """ __version_info__ = (0, 1, 157) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" }
""" plenum package metadata """ __version_info__ = (0, 1, 158) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" }
Increase plenum version to 0.1.158
Increase plenum version to 0.1.158
Python
apache-2.0
evernym/plenum,evernym/zeno
""" plenum package metadata """ __version_info__ = (0, 1, 157) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" } Increase plenum version to 0.1.158
""" plenum package metadata """ __version_info__ = (0, 1, 158) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" }
<commit_before>""" plenum package metadata """ __version_info__ = (0, 1, 157) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" } <commit_msg>Increase plenum version to 0.1.158<commit_after>
""" plenum package metadata """ __version_info__ = (0, 1, 158) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" }
""" plenum package metadata """ __version_info__ = (0, 1, 157) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" } Increase plenum version to 0.1.158""" plenum package metadata """ __version_info__ = (0, 1, 158) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" }
<commit_before>""" plenum package metadata """ __version_info__ = (0, 1, 157) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" } <commit_msg>Increase plenum version to 0.1.158<commit_after>""" plenum package metadata """ __version_info__ = (0, 1, 158) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" }
577a652852f0bb6305f071f34b69c318b01d9c97
poet/test/test_poet.py
poet/test/test_poet.py
# Integration tests for poet import subprocess import sys def poet(*args): return subprocess.check_output( ["poet"] + list(args), stderr=subprocess.STDOUT) def test_version(): assert b"homebrew-pypi-poet" in poet("-V") def test_single(): result = poet("-s", "nose", "six") assert b'resource "nose"' in result assert b'resource "six"' in result def test_formula(): result = poet("-f", "pytest") assert b'resource "py" do' in result if sys.version_info.major == 2: assert b'depends_on :python if' in result else: assert b'depends_on :python3' in result def test_case_sensitivity(): poet("-f", "FoBiS.py") def test_resources(): result = poet("pytest") assert b'resource "py" do' in result result = poet("py.test") assert b'PackageNotInstalledWarning' in result def test_audit(tmpdir): home = tmpdir.chdir() try: with open("pytest.rb", "wb") as f: subprocess.check_call(["poet", "-f", "pytest"], stdout=f) subprocess.check_call(["brew", "audit", "./pytest.rb"]) finally: tmpdir.join("pytest.rb").remove(ignore_errors=True) home.chdir()
# Integration tests for poet import subprocess import sys def poet(*args): return subprocess.check_output( ["poet"] + list(args), stderr=subprocess.STDOUT) def test_version(): assert b"homebrew-pypi-poet" in poet("-V") def test_single(): result = poet("-s", "nose", "six") assert b'resource "nose"' in result assert b'resource "six"' in result def test_formula(): result = poet("-f", "pytest") assert b'resource "py" do' in result if sys.version_info.major == 2: assert b'depends_on :python if' in result else: assert b'depends_on :python3' in result def test_case_sensitivity(): poet("-f", "FoBiS.py") def test_resources(): result = poet("pytest") assert b'resource "py" do' in result result = poet("py.test") assert b'PackageNotInstalledWarning' in result def test_uses_sha256_from_json(monkeypatch): monkeypatch.setenv("POET_DEBUG", 10) result = poet("pytest") assert b"Using provided checksum for py\n" in result def test_audit(tmpdir): home = tmpdir.chdir() try: with open("pytest.rb", "wb") as f: subprocess.check_call(["poet", "-f", "pytest"], stdout=f) subprocess.check_call(["brew", "audit", "./pytest.rb"]) finally: tmpdir.join("pytest.rb").remove(ignore_errors=True) home.chdir()
Test that poet uses sha256's from pypi
Test that poet uses sha256's from pypi Closes #25. Closes #23. Closes #6.
Python
mit
tdsmith/homebrew-pypi-poet
# Integration tests for poet import subprocess import sys def poet(*args): return subprocess.check_output( ["poet"] + list(args), stderr=subprocess.STDOUT) def test_version(): assert b"homebrew-pypi-poet" in poet("-V") def test_single(): result = poet("-s", "nose", "six") assert b'resource "nose"' in result assert b'resource "six"' in result def test_formula(): result = poet("-f", "pytest") assert b'resource "py" do' in result if sys.version_info.major == 2: assert b'depends_on :python if' in result else: assert b'depends_on :python3' in result def test_case_sensitivity(): poet("-f", "FoBiS.py") def test_resources(): result = poet("pytest") assert b'resource "py" do' in result result = poet("py.test") assert b'PackageNotInstalledWarning' in result def test_audit(tmpdir): home = tmpdir.chdir() try: with open("pytest.rb", "wb") as f: subprocess.check_call(["poet", "-f", "pytest"], stdout=f) subprocess.check_call(["brew", "audit", "./pytest.rb"]) finally: tmpdir.join("pytest.rb").remove(ignore_errors=True) home.chdir() Test that poet uses sha256's from pypi Closes #25. Closes #23. Closes #6.
# Integration tests for poet import subprocess import sys def poet(*args): return subprocess.check_output( ["poet"] + list(args), stderr=subprocess.STDOUT) def test_version(): assert b"homebrew-pypi-poet" in poet("-V") def test_single(): result = poet("-s", "nose", "six") assert b'resource "nose"' in result assert b'resource "six"' in result def test_formula(): result = poet("-f", "pytest") assert b'resource "py" do' in result if sys.version_info.major == 2: assert b'depends_on :python if' in result else: assert b'depends_on :python3' in result def test_case_sensitivity(): poet("-f", "FoBiS.py") def test_resources(): result = poet("pytest") assert b'resource "py" do' in result result = poet("py.test") assert b'PackageNotInstalledWarning' in result def test_uses_sha256_from_json(monkeypatch): monkeypatch.setenv("POET_DEBUG", 10) result = poet("pytest") assert b"Using provided checksum for py\n" in result def test_audit(tmpdir): home = tmpdir.chdir() try: with open("pytest.rb", "wb") as f: subprocess.check_call(["poet", "-f", "pytest"], stdout=f) subprocess.check_call(["brew", "audit", "./pytest.rb"]) finally: tmpdir.join("pytest.rb").remove(ignore_errors=True) home.chdir()
<commit_before># Integration tests for poet import subprocess import sys def poet(*args): return subprocess.check_output( ["poet"] + list(args), stderr=subprocess.STDOUT) def test_version(): assert b"homebrew-pypi-poet" in poet("-V") def test_single(): result = poet("-s", "nose", "six") assert b'resource "nose"' in result assert b'resource "six"' in result def test_formula(): result = poet("-f", "pytest") assert b'resource "py" do' in result if sys.version_info.major == 2: assert b'depends_on :python if' in result else: assert b'depends_on :python3' in result def test_case_sensitivity(): poet("-f", "FoBiS.py") def test_resources(): result = poet("pytest") assert b'resource "py" do' in result result = poet("py.test") assert b'PackageNotInstalledWarning' in result def test_audit(tmpdir): home = tmpdir.chdir() try: with open("pytest.rb", "wb") as f: subprocess.check_call(["poet", "-f", "pytest"], stdout=f) subprocess.check_call(["brew", "audit", "./pytest.rb"]) finally: tmpdir.join("pytest.rb").remove(ignore_errors=True) home.chdir() <commit_msg>Test that poet uses sha256's from pypi Closes #25. Closes #23. Closes #6.<commit_after>
# Integration tests for poet import subprocess import sys def poet(*args): return subprocess.check_output( ["poet"] + list(args), stderr=subprocess.STDOUT) def test_version(): assert b"homebrew-pypi-poet" in poet("-V") def test_single(): result = poet("-s", "nose", "six") assert b'resource "nose"' in result assert b'resource "six"' in result def test_formula(): result = poet("-f", "pytest") assert b'resource "py" do' in result if sys.version_info.major == 2: assert b'depends_on :python if' in result else: assert b'depends_on :python3' in result def test_case_sensitivity(): poet("-f", "FoBiS.py") def test_resources(): result = poet("pytest") assert b'resource "py" do' in result result = poet("py.test") assert b'PackageNotInstalledWarning' in result def test_uses_sha256_from_json(monkeypatch): monkeypatch.setenv("POET_DEBUG", 10) result = poet("pytest") assert b"Using provided checksum for py\n" in result def test_audit(tmpdir): home = tmpdir.chdir() try: with open("pytest.rb", "wb") as f: subprocess.check_call(["poet", "-f", "pytest"], stdout=f) subprocess.check_call(["brew", "audit", "./pytest.rb"]) finally: tmpdir.join("pytest.rb").remove(ignore_errors=True) home.chdir()
# Integration tests for poet import subprocess import sys def poet(*args): return subprocess.check_output( ["poet"] + list(args), stderr=subprocess.STDOUT) def test_version(): assert b"homebrew-pypi-poet" in poet("-V") def test_single(): result = poet("-s", "nose", "six") assert b'resource "nose"' in result assert b'resource "six"' in result def test_formula(): result = poet("-f", "pytest") assert b'resource "py" do' in result if sys.version_info.major == 2: assert b'depends_on :python if' in result else: assert b'depends_on :python3' in result def test_case_sensitivity(): poet("-f", "FoBiS.py") def test_resources(): result = poet("pytest") assert b'resource "py" do' in result result = poet("py.test") assert b'PackageNotInstalledWarning' in result def test_audit(tmpdir): home = tmpdir.chdir() try: with open("pytest.rb", "wb") as f: subprocess.check_call(["poet", "-f", "pytest"], stdout=f) subprocess.check_call(["brew", "audit", "./pytest.rb"]) finally: tmpdir.join("pytest.rb").remove(ignore_errors=True) home.chdir() Test that poet uses sha256's from pypi Closes #25. Closes #23. Closes #6.# Integration tests for poet import subprocess import sys def poet(*args): return subprocess.check_output( ["poet"] + list(args), stderr=subprocess.STDOUT) def test_version(): assert b"homebrew-pypi-poet" in poet("-V") def test_single(): result = poet("-s", "nose", "six") assert b'resource "nose"' in result assert b'resource "six"' in result def test_formula(): result = poet("-f", "pytest") assert b'resource "py" do' in result if sys.version_info.major == 2: assert b'depends_on :python if' in result else: assert b'depends_on :python3' in result def test_case_sensitivity(): poet("-f", "FoBiS.py") def test_resources(): result = poet("pytest") assert b'resource "py" do' in result result = poet("py.test") assert b'PackageNotInstalledWarning' in result def test_uses_sha256_from_json(monkeypatch): monkeypatch.setenv("POET_DEBUG", 10) result = poet("pytest") assert b"Using provided checksum for py\n" in result def test_audit(tmpdir): home = tmpdir.chdir() try: with open("pytest.rb", "wb") as f: subprocess.check_call(["poet", "-f", "pytest"], stdout=f) subprocess.check_call(["brew", "audit", "./pytest.rb"]) finally: tmpdir.join("pytest.rb").remove(ignore_errors=True) home.chdir()
<commit_before># Integration tests for poet import subprocess import sys def poet(*args): return subprocess.check_output( ["poet"] + list(args), stderr=subprocess.STDOUT) def test_version(): assert b"homebrew-pypi-poet" in poet("-V") def test_single(): result = poet("-s", "nose", "six") assert b'resource "nose"' in result assert b'resource "six"' in result def test_formula(): result = poet("-f", "pytest") assert b'resource "py" do' in result if sys.version_info.major == 2: assert b'depends_on :python if' in result else: assert b'depends_on :python3' in result def test_case_sensitivity(): poet("-f", "FoBiS.py") def test_resources(): result = poet("pytest") assert b'resource "py" do' in result result = poet("py.test") assert b'PackageNotInstalledWarning' in result def test_audit(tmpdir): home = tmpdir.chdir() try: with open("pytest.rb", "wb") as f: subprocess.check_call(["poet", "-f", "pytest"], stdout=f) subprocess.check_call(["brew", "audit", "./pytest.rb"]) finally: tmpdir.join("pytest.rb").remove(ignore_errors=True) home.chdir() <commit_msg>Test that poet uses sha256's from pypi Closes #25. Closes #23. Closes #6.<commit_after># Integration tests for poet import subprocess import sys def poet(*args): return subprocess.check_output( ["poet"] + list(args), stderr=subprocess.STDOUT) def test_version(): assert b"homebrew-pypi-poet" in poet("-V") def test_single(): result = poet("-s", "nose", "six") assert b'resource "nose"' in result assert b'resource "six"' in result def test_formula(): result = poet("-f", "pytest") assert b'resource "py" do' in result if sys.version_info.major == 2: assert b'depends_on :python if' in result else: assert b'depends_on :python3' in result def test_case_sensitivity(): poet("-f", "FoBiS.py") def test_resources(): result = poet("pytest") assert b'resource "py" do' in result result = poet("py.test") assert b'PackageNotInstalledWarning' in result def test_uses_sha256_from_json(monkeypatch): monkeypatch.setenv("POET_DEBUG", 10) result = poet("pytest") assert b"Using provided checksum for py\n" in result def test_audit(tmpdir): home = tmpdir.chdir() try: with open("pytest.rb", "wb") as f: subprocess.check_call(["poet", "-f", "pytest"], stdout=f) subprocess.check_call(["brew", "audit", "./pytest.rb"]) finally: tmpdir.join("pytest.rb").remove(ignore_errors=True) home.chdir()
4ff709f80999bfc512d23a25d4236108c067cc31
poppinsbag/__init__.py
poppinsbag/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = "0.1.0"
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Mary Poppins always has what you need in her bag. This is a set of tools and helpers to deals with common things. Give it a try ! """ __version__ = "0.1.0"
Add a docstring to the poppinsbag module
Add a docstring to the poppinsbag module
Python
mit
avcreation/pyPoppins
#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = "0.1.0" Add a docstring to the poppinsbag module
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Mary Poppins always has what you need in her bag. This is a set of tools and helpers to deals with common things. Give it a try ! """ __version__ = "0.1.0"
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = "0.1.0" <commit_msg>Add a docstring to the poppinsbag module<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Mary Poppins always has what you need in her bag. This is a set of tools and helpers to deals with common things. Give it a try ! """ __version__ = "0.1.0"
#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = "0.1.0" Add a docstring to the poppinsbag module#!/usr/bin/env python # -*- coding: utf-8 -*- """ Mary Poppins always has what you need in her bag. This is a set of tools and helpers to deals with common things. Give it a try ! """ __version__ = "0.1.0"
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = "0.1.0" <commit_msg>Add a docstring to the poppinsbag module<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Mary Poppins always has what you need in her bag. This is a set of tools and helpers to deals with common things. Give it a try ! """ __version__ = "0.1.0"
3873fe6b33665267a04f80faec63eaaa19ea00bd
portal/pages/models.py
portal/pages/models.py
from django.db import models from wagtail.wagtailcore.models import Page as WagtailPage from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel class Page(WagtailPage): parent_page_types = ['home.HomePage', 'Page'] body = RichTextField() indexed_fields = ('body', ) content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('body', classname="full"), ]
from django.db import models from wagtail.wagtailcore.models import Page as WagtailPage from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel class Page(WagtailPage): body = RichTextField() indexed_fields = ('body', ) content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('body', classname="full"), ]
Allow pages to appear anywhere they aren't excluded
Allow pages to appear anywhere they aren't excluded
Python
isc
Ecotrust/marineplanner-core,Ecotrust/marineplanner-core,Ecotrust/marineplanner-core,Ecotrust/marineplanner-core,MidAtlanticPortal/marco-portal2,MidAtlanticPortal/marco-portal2,MidAtlanticPortal/marco-portal2,MidAtlanticPortal/marco-portal2,Ecotrust/marineplanner-core
from django.db import models from wagtail.wagtailcore.models import Page as WagtailPage from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel class Page(WagtailPage): parent_page_types = ['home.HomePage', 'Page'] body = RichTextField() indexed_fields = ('body', ) content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('body', classname="full"), ] Allow pages to appear anywhere they aren't excluded
from django.db import models from wagtail.wagtailcore.models import Page as WagtailPage from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel class Page(WagtailPage): body = RichTextField() indexed_fields = ('body', ) content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('body', classname="full"), ]
<commit_before>from django.db import models from wagtail.wagtailcore.models import Page as WagtailPage from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel class Page(WagtailPage): parent_page_types = ['home.HomePage', 'Page'] body = RichTextField() indexed_fields = ('body', ) content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('body', classname="full"), ] <commit_msg>Allow pages to appear anywhere they aren't excluded<commit_after>
from django.db import models from wagtail.wagtailcore.models import Page as WagtailPage from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel class Page(WagtailPage): body = RichTextField() indexed_fields = ('body', ) content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('body', classname="full"), ]
from django.db import models from wagtail.wagtailcore.models import Page as WagtailPage from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel class Page(WagtailPage): parent_page_types = ['home.HomePage', 'Page'] body = RichTextField() indexed_fields = ('body', ) content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('body', classname="full"), ] Allow pages to appear anywhere they aren't excludedfrom django.db import models from wagtail.wagtailcore.models import Page as WagtailPage from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel class Page(WagtailPage): body = RichTextField() indexed_fields = ('body', ) content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('body', classname="full"), ]
<commit_before>from django.db import models from wagtail.wagtailcore.models import Page as WagtailPage from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel class Page(WagtailPage): parent_page_types = ['home.HomePage', 'Page'] body = RichTextField() indexed_fields = ('body', ) content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('body', classname="full"), ] <commit_msg>Allow pages to appear anywhere they aren't excluded<commit_after>from django.db import models from wagtail.wagtailcore.models import Page as WagtailPage from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel class Page(WagtailPage): body = RichTextField() indexed_fields = ('body', ) content_panels = [ FieldPanel('title', classname="full title"), FieldPanel('body', classname="full"), ]
c0c902cc356d1a3142a6d260e7b768114449013e
tutorials/models.py
tutorials/models.py
from django.db import models from markdownx.models import MarkdownxField # Create your models here. class Tutorial(models.Model): # ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ?? # Category = models.TextField() title = models.TextField() html = models.TextField() markdown = MarkdownxField() # Level = models.IntegerField()
from django.db import models from django.urls import reverse from markdownx.models import MarkdownxField # add options if needed CATEGORY_OPTIONS = [('io', 'I/O'), ('intro', 'Introduction')] LEVEL_OPTIONS = [(1, '1'), (2, '2'), (3, '3')] # Create your models here. class Tutorial(models.Model): # ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ?? category = models.CharField(max_length=15, choices=CATEGORY_OPTIONS, blank=True) title = models.TextField() html = models.TextField() markdown = MarkdownxField() level = models.IntegerField(choices=LEVEL_OPTIONS, null=True) def get_absolute_url (self): return reverse('detail_tutorial', args=[self.id])
Add options for choices fields, Add new fields to Tutorial model
Add options for choices fields, Add new fields to Tutorial model
Python
agpl-3.0
openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform
from django.db import models from markdownx.models import MarkdownxField # Create your models here. class Tutorial(models.Model): # ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ?? # Category = models.TextField() title = models.TextField() html = models.TextField() markdown = MarkdownxField() # Level = models.IntegerField() Add options for choices fields, Add new fields to Tutorial model
from django.db import models from django.urls import reverse from markdownx.models import MarkdownxField # add options if needed CATEGORY_OPTIONS = [('io', 'I/O'), ('intro', 'Introduction')] LEVEL_OPTIONS = [(1, '1'), (2, '2'), (3, '3')] # Create your models here. class Tutorial(models.Model): # ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ?? category = models.CharField(max_length=15, choices=CATEGORY_OPTIONS, blank=True) title = models.TextField() html = models.TextField() markdown = MarkdownxField() level = models.IntegerField(choices=LEVEL_OPTIONS, null=True) def get_absolute_url (self): return reverse('detail_tutorial', args=[self.id])
<commit_before>from django.db import models from markdownx.models import MarkdownxField # Create your models here. class Tutorial(models.Model): # ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ?? # Category = models.TextField() title = models.TextField() html = models.TextField() markdown = MarkdownxField() # Level = models.IntegerField() <commit_msg>Add options for choices fields, Add new fields to Tutorial model<commit_after>
from django.db import models from django.urls import reverse from markdownx.models import MarkdownxField # add options if needed CATEGORY_OPTIONS = [('io', 'I/O'), ('intro', 'Introduction')] LEVEL_OPTIONS = [(1, '1'), (2, '2'), (3, '3')] # Create your models here. class Tutorial(models.Model): # ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ?? category = models.CharField(max_length=15, choices=CATEGORY_OPTIONS, blank=True) title = models.TextField() html = models.TextField() markdown = MarkdownxField() level = models.IntegerField(choices=LEVEL_OPTIONS, null=True) def get_absolute_url (self): return reverse('detail_tutorial', args=[self.id])
from django.db import models from markdownx.models import MarkdownxField # Create your models here. class Tutorial(models.Model): # ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ?? # Category = models.TextField() title = models.TextField() html = models.TextField() markdown = MarkdownxField() # Level = models.IntegerField() Add options for choices fields, Add new fields to Tutorial modelfrom django.db import models from django.urls import reverse from markdownx.models import MarkdownxField # add options if needed CATEGORY_OPTIONS = [('io', 'I/O'), ('intro', 'Introduction')] LEVEL_OPTIONS = [(1, '1'), (2, '2'), (3, '3')] # Create your models here. class Tutorial(models.Model): # ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ?? category = models.CharField(max_length=15, choices=CATEGORY_OPTIONS, blank=True) title = models.TextField() html = models.TextField() markdown = MarkdownxField() level = models.IntegerField(choices=LEVEL_OPTIONS, null=True) def get_absolute_url (self): return reverse('detail_tutorial', args=[self.id])
<commit_before>from django.db import models from markdownx.models import MarkdownxField # Create your models here. class Tutorial(models.Model): # ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ?? # Category = models.TextField() title = models.TextField() html = models.TextField() markdown = MarkdownxField() # Level = models.IntegerField() <commit_msg>Add options for choices fields, Add new fields to Tutorial model<commit_after>from django.db import models from django.urls import reverse from markdownx.models import MarkdownxField # add options if needed CATEGORY_OPTIONS = [('io', 'I/O'), ('intro', 'Introduction')] LEVEL_OPTIONS = [(1, '1'), (2, '2'), (3, '3')] # Create your models here. class Tutorial(models.Model): # ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ?? category = models.CharField(max_length=15, choices=CATEGORY_OPTIONS, blank=True) title = models.TextField() html = models.TextField() markdown = MarkdownxField() level = models.IntegerField(choices=LEVEL_OPTIONS, null=True) def get_absolute_url (self): return reverse('detail_tutorial', args=[self.id])
6153f18bda4dcf3601df91b60787453af1517b78
falmer/auth/types.py
falmer/auth/types.py
import graphene from django.contrib.auth.models import Permission as DjangoPermission from graphene_django import DjangoObjectType from . import models class ClientUser(DjangoObjectType): name = graphene.String() has_cms_access = graphene.Boolean() user_id = graphene.Int() permissions = graphene.List(graphene.Int) class Meta: model = models.FalmerUser fields = ( 'id', 'name', ) def resolve_name(self, info): return self.get_full_name() def resolve_user_id(self, info): return self.pk # this is a quick hack until we work on permissions etc def resolve_has_cms_access(self, info): return self.has_perm('wagtailadmin.access_admin') def resolve_permissions(self, info): return self.get_permissions() class Permission(DjangoObjectType): content_type = graphene.String() class Meta: model = DjangoPermission fields = ( 'content_type', ) def resolve_content_type(self, info): return self.content_type.app_label
import graphene from django.contrib.auth.models import Permission as DjangoPermission from graphene_django import DjangoObjectType from . import models class ClientUser(DjangoObjectType): name = graphene.String() has_cms_access = graphene.Boolean() user_id = graphene.Int() permissions = graphene.List(graphene.Int) class Meta: model = models.FalmerUser fields = ( 'id', 'name', ) def resolve_name(self, info): return self.get_full_name() def resolve_user_id(self, info): return self.pk # this is a quick hack until we work on permissions etc def resolve_has_cms_access(self, info): return self.has_perm('wagtailadmin.access_admin') def resolve_permissions(self, info): return self.get_permissions() class Permission(DjangoObjectType): content_type = graphene.String() class Meta: model = DjangoPermission fields = ( 'id', 'name', 'codename', 'content_type', ) def resolve_content_type(self, info): return self.content_type.app_label
Add additional fields to permission type
Add additional fields to permission type
Python
mit
sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer
import graphene from django.contrib.auth.models import Permission as DjangoPermission from graphene_django import DjangoObjectType from . import models class ClientUser(DjangoObjectType): name = graphene.String() has_cms_access = graphene.Boolean() user_id = graphene.Int() permissions = graphene.List(graphene.Int) class Meta: model = models.FalmerUser fields = ( 'id', 'name', ) def resolve_name(self, info): return self.get_full_name() def resolve_user_id(self, info): return self.pk # this is a quick hack until we work on permissions etc def resolve_has_cms_access(self, info): return self.has_perm('wagtailadmin.access_admin') def resolve_permissions(self, info): return self.get_permissions() class Permission(DjangoObjectType): content_type = graphene.String() class Meta: model = DjangoPermission fields = ( 'content_type', ) def resolve_content_type(self, info): return self.content_type.app_label Add additional fields to permission type
import graphene from django.contrib.auth.models import Permission as DjangoPermission from graphene_django import DjangoObjectType from . import models class ClientUser(DjangoObjectType): name = graphene.String() has_cms_access = graphene.Boolean() user_id = graphene.Int() permissions = graphene.List(graphene.Int) class Meta: model = models.FalmerUser fields = ( 'id', 'name', ) def resolve_name(self, info): return self.get_full_name() def resolve_user_id(self, info): return self.pk # this is a quick hack until we work on permissions etc def resolve_has_cms_access(self, info): return self.has_perm('wagtailadmin.access_admin') def resolve_permissions(self, info): return self.get_permissions() class Permission(DjangoObjectType): content_type = graphene.String() class Meta: model = DjangoPermission fields = ( 'id', 'name', 'codename', 'content_type', ) def resolve_content_type(self, info): return self.content_type.app_label
<commit_before>import graphene from django.contrib.auth.models import Permission as DjangoPermission from graphene_django import DjangoObjectType from . import models class ClientUser(DjangoObjectType): name = graphene.String() has_cms_access = graphene.Boolean() user_id = graphene.Int() permissions = graphene.List(graphene.Int) class Meta: model = models.FalmerUser fields = ( 'id', 'name', ) def resolve_name(self, info): return self.get_full_name() def resolve_user_id(self, info): return self.pk # this is a quick hack until we work on permissions etc def resolve_has_cms_access(self, info): return self.has_perm('wagtailadmin.access_admin') def resolve_permissions(self, info): return self.get_permissions() class Permission(DjangoObjectType): content_type = graphene.String() class Meta: model = DjangoPermission fields = ( 'content_type', ) def resolve_content_type(self, info): return self.content_type.app_label <commit_msg>Add additional fields to permission type<commit_after>
import graphene from django.contrib.auth.models import Permission as DjangoPermission from graphene_django import DjangoObjectType from . import models class ClientUser(DjangoObjectType): name = graphene.String() has_cms_access = graphene.Boolean() user_id = graphene.Int() permissions = graphene.List(graphene.Int) class Meta: model = models.FalmerUser fields = ( 'id', 'name', ) def resolve_name(self, info): return self.get_full_name() def resolve_user_id(self, info): return self.pk # this is a quick hack until we work on permissions etc def resolve_has_cms_access(self, info): return self.has_perm('wagtailadmin.access_admin') def resolve_permissions(self, info): return self.get_permissions() class Permission(DjangoObjectType): content_type = graphene.String() class Meta: model = DjangoPermission fields = ( 'id', 'name', 'codename', 'content_type', ) def resolve_content_type(self, info): return self.content_type.app_label
import graphene from django.contrib.auth.models import Permission as DjangoPermission from graphene_django import DjangoObjectType from . import models class ClientUser(DjangoObjectType): name = graphene.String() has_cms_access = graphene.Boolean() user_id = graphene.Int() permissions = graphene.List(graphene.Int) class Meta: model = models.FalmerUser fields = ( 'id', 'name', ) def resolve_name(self, info): return self.get_full_name() def resolve_user_id(self, info): return self.pk # this is a quick hack until we work on permissions etc def resolve_has_cms_access(self, info): return self.has_perm('wagtailadmin.access_admin') def resolve_permissions(self, info): return self.get_permissions() class Permission(DjangoObjectType): content_type = graphene.String() class Meta: model = DjangoPermission fields = ( 'content_type', ) def resolve_content_type(self, info): return self.content_type.app_label Add additional fields to permission typeimport graphene from django.contrib.auth.models import Permission as DjangoPermission from graphene_django import DjangoObjectType from . import models class ClientUser(DjangoObjectType): name = graphene.String() has_cms_access = graphene.Boolean() user_id = graphene.Int() permissions = graphene.List(graphene.Int) class Meta: model = models.FalmerUser fields = ( 'id', 'name', ) def resolve_name(self, info): return self.get_full_name() def resolve_user_id(self, info): return self.pk # this is a quick hack until we work on permissions etc def resolve_has_cms_access(self, info): return self.has_perm('wagtailadmin.access_admin') def resolve_permissions(self, info): return self.get_permissions() class Permission(DjangoObjectType): content_type = graphene.String() class Meta: model = DjangoPermission fields = ( 'id', 'name', 'codename', 'content_type', ) def resolve_content_type(self, info): return self.content_type.app_label
<commit_before>import graphene from django.contrib.auth.models import Permission as DjangoPermission from graphene_django import DjangoObjectType from . import models class ClientUser(DjangoObjectType): name = graphene.String() has_cms_access = graphene.Boolean() user_id = graphene.Int() permissions = graphene.List(graphene.Int) class Meta: model = models.FalmerUser fields = ( 'id', 'name', ) def resolve_name(self, info): return self.get_full_name() def resolve_user_id(self, info): return self.pk # this is a quick hack until we work on permissions etc def resolve_has_cms_access(self, info): return self.has_perm('wagtailadmin.access_admin') def resolve_permissions(self, info): return self.get_permissions() class Permission(DjangoObjectType): content_type = graphene.String() class Meta: model = DjangoPermission fields = ( 'content_type', ) def resolve_content_type(self, info): return self.content_type.app_label <commit_msg>Add additional fields to permission type<commit_after>import graphene from django.contrib.auth.models import Permission as DjangoPermission from graphene_django import DjangoObjectType from . import models class ClientUser(DjangoObjectType): name = graphene.String() has_cms_access = graphene.Boolean() user_id = graphene.Int() permissions = graphene.List(graphene.Int) class Meta: model = models.FalmerUser fields = ( 'id', 'name', ) def resolve_name(self, info): return self.get_full_name() def resolve_user_id(self, info): return self.pk # this is a quick hack until we work on permissions etc def resolve_has_cms_access(self, info): return self.has_perm('wagtailadmin.access_admin') def resolve_permissions(self, info): return self.get_permissions() class Permission(DjangoObjectType): content_type = graphene.String() class Meta: model = DjangoPermission fields = ( 'id', 'name', 'codename', 'content_type', ) def resolve_content_type(self, info): return self.content_type.app_label
c5bcd270e8422ba23bcb29dd4a00ce4fa9e7d437
anki.py
anki.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import os import re import yaml import lib.genanki.genanki as genanki class Anki: def generate_id(): """Generate a 32-bit ID useful for Anki.""" return random.randrange(1 << 30, 1 << 31) # return datetime.now().timestamp() def import_card_definitions(self, yaml_filepath): """Import card definitions from YAML file.""" path = os.path.dirname(yaml_filepath) + '/' with open(yaml_filepath, 'r') as f: cards = f.read() cards = yaml.load(cards) for subject, model in cards.items(): for template in model['templates']: for fmt in ('qfmt', 'afmt'): with open(path + template[fmt], 'r') as f: lines = f.readlines() temp = '' for line in lines: match = re.match('\s*{{import:(.*)}}', line) if match: with open(path + match.group(1), 'r') as f: line = f.read() temp += line template[fmt] = temp return cards
# This Source Code Form is subject to the terms of the Mozilla Public # License, v2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import os import re import yaml import lib.genanki.genanki as genanki class Anki: def generate_id(): """Generate a 32-bit ID useful for Anki.""" return random.randrange(1 << 30, 1 << 31) # return datetime.now().timestamp() def import_card_definitions(self, yaml_filepath): """Import card definitions from YAML file. Adds a Anki-like {{import:file.txt}} file import command which works similar to the #include preprocessor command in C-like languages, directly replacing the command with text from the import file. """ path = os.path.dirname(yaml_filepath) + '/' with open(yaml_filepath, 'r') as f: cards = f.read() cards = yaml.load(cards) for subject, model in cards.items(): for template in model['templates']: for fmt in ('qfmt', 'afmt'): with open(path + template[fmt], 'r') as f: lines = f.readlines() temp = '' for line in lines: match = re.match('\s*{{import:(.*)}}', line) if match: with open(path + match.group(1), 'r') as f: line = f.read() temp += line template[fmt] = temp return cards
Document new {{import:file.txt}} command for Anki card definitions.
Document new {{import:file.txt}} command for Anki card definitions.
Python
mpl-2.0
holocronweaver/wanikani2anki,holocronweaver/wanikani2anki,holocronweaver/wanikani2anki
# This Source Code Form is subject to the terms of the Mozilla Public # License, v2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import os import re import yaml import lib.genanki.genanki as genanki class Anki: def generate_id(): """Generate a 32-bit ID useful for Anki.""" return random.randrange(1 << 30, 1 << 31) # return datetime.now().timestamp() def import_card_definitions(self, yaml_filepath): """Import card definitions from YAML file.""" path = os.path.dirname(yaml_filepath) + '/' with open(yaml_filepath, 'r') as f: cards = f.read() cards = yaml.load(cards) for subject, model in cards.items(): for template in model['templates']: for fmt in ('qfmt', 'afmt'): with open(path + template[fmt], 'r') as f: lines = f.readlines() temp = '' for line in lines: match = re.match('\s*{{import:(.*)}}', line) if match: with open(path + match.group(1), 'r') as f: line = f.read() temp += line template[fmt] = temp return cards Document new {{import:file.txt}} command for Anki card definitions.
# This Source Code Form is subject to the terms of the Mozilla Public # License, v2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import os import re import yaml import lib.genanki.genanki as genanki class Anki: def generate_id(): """Generate a 32-bit ID useful for Anki.""" return random.randrange(1 << 30, 1 << 31) # return datetime.now().timestamp() def import_card_definitions(self, yaml_filepath): """Import card definitions from YAML file. Adds a Anki-like {{import:file.txt}} file import command which works similar to the #include preprocessor command in C-like languages, directly replacing the command with text from the import file. """ path = os.path.dirname(yaml_filepath) + '/' with open(yaml_filepath, 'r') as f: cards = f.read() cards = yaml.load(cards) for subject, model in cards.items(): for template in model['templates']: for fmt in ('qfmt', 'afmt'): with open(path + template[fmt], 'r') as f: lines = f.readlines() temp = '' for line in lines: match = re.match('\s*{{import:(.*)}}', line) if match: with open(path + match.group(1), 'r') as f: line = f.read() temp += line template[fmt] = temp return cards
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public # License, v2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import os import re import yaml import lib.genanki.genanki as genanki class Anki: def generate_id(): """Generate a 32-bit ID useful for Anki.""" return random.randrange(1 << 30, 1 << 31) # return datetime.now().timestamp() def import_card_definitions(self, yaml_filepath): """Import card definitions from YAML file.""" path = os.path.dirname(yaml_filepath) + '/' with open(yaml_filepath, 'r') as f: cards = f.read() cards = yaml.load(cards) for subject, model in cards.items(): for template in model['templates']: for fmt in ('qfmt', 'afmt'): with open(path + template[fmt], 'r') as f: lines = f.readlines() temp = '' for line in lines: match = re.match('\s*{{import:(.*)}}', line) if match: with open(path + match.group(1), 'r') as f: line = f.read() temp += line template[fmt] = temp return cards <commit_msg>Document new {{import:file.txt}} command for Anki card definitions.<commit_after>
# This Source Code Form is subject to the terms of the Mozilla Public # License, v2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import os import re import yaml import lib.genanki.genanki as genanki class Anki: def generate_id(): """Generate a 32-bit ID useful for Anki.""" return random.randrange(1 << 30, 1 << 31) # return datetime.now().timestamp() def import_card_definitions(self, yaml_filepath): """Import card definitions from YAML file. Adds a Anki-like {{import:file.txt}} file import command which works similar to the #include preprocessor command in C-like languages, directly replacing the command with text from the import file. """ path = os.path.dirname(yaml_filepath) + '/' with open(yaml_filepath, 'r') as f: cards = f.read() cards = yaml.load(cards) for subject, model in cards.items(): for template in model['templates']: for fmt in ('qfmt', 'afmt'): with open(path + template[fmt], 'r') as f: lines = f.readlines() temp = '' for line in lines: match = re.match('\s*{{import:(.*)}}', line) if match: with open(path + match.group(1), 'r') as f: line = f.read() temp += line template[fmt] = temp return cards
# This Source Code Form is subject to the terms of the Mozilla Public # License, v2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import os import re import yaml import lib.genanki.genanki as genanki class Anki: def generate_id(): """Generate a 32-bit ID useful for Anki.""" return random.randrange(1 << 30, 1 << 31) # return datetime.now().timestamp() def import_card_definitions(self, yaml_filepath): """Import card definitions from YAML file.""" path = os.path.dirname(yaml_filepath) + '/' with open(yaml_filepath, 'r') as f: cards = f.read() cards = yaml.load(cards) for subject, model in cards.items(): for template in model['templates']: for fmt in ('qfmt', 'afmt'): with open(path + template[fmt], 'r') as f: lines = f.readlines() temp = '' for line in lines: match = re.match('\s*{{import:(.*)}}', line) if match: with open(path + match.group(1), 'r') as f: line = f.read() temp += line template[fmt] = temp return cards Document new {{import:file.txt}} command for Anki card definitions.# This Source Code Form is subject to the terms of the Mozilla Public # License, v2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import os import re import yaml import lib.genanki.genanki as genanki class Anki: def generate_id(): """Generate a 32-bit ID useful for Anki.""" return random.randrange(1 << 30, 1 << 31) # return datetime.now().timestamp() def import_card_definitions(self, yaml_filepath): """Import card definitions from YAML file. Adds a Anki-like {{import:file.txt}} file import command which works similar to the #include preprocessor command in C-like languages, directly replacing the command with text from the import file. """ path = os.path.dirname(yaml_filepath) + '/' with open(yaml_filepath, 'r') as f: cards = f.read() cards = yaml.load(cards) for subject, model in cards.items(): for template in model['templates']: for fmt in ('qfmt', 'afmt'): with open(path + template[fmt], 'r') as f: lines = f.readlines() temp = '' for line in lines: match = re.match('\s*{{import:(.*)}}', line) if match: with open(path + match.group(1), 'r') as f: line = f.read() temp += line template[fmt] = temp return cards
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public # License, v2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import os import re import yaml import lib.genanki.genanki as genanki class Anki: def generate_id(): """Generate a 32-bit ID useful for Anki.""" return random.randrange(1 << 30, 1 << 31) # return datetime.now().timestamp() def import_card_definitions(self, yaml_filepath): """Import card definitions from YAML file.""" path = os.path.dirname(yaml_filepath) + '/' with open(yaml_filepath, 'r') as f: cards = f.read() cards = yaml.load(cards) for subject, model in cards.items(): for template in model['templates']: for fmt in ('qfmt', 'afmt'): with open(path + template[fmt], 'r') as f: lines = f.readlines() temp = '' for line in lines: match = re.match('\s*{{import:(.*)}}', line) if match: with open(path + match.group(1), 'r') as f: line = f.read() temp += line template[fmt] = temp return cards <commit_msg>Document new {{import:file.txt}} command for Anki card definitions.<commit_after># This Source Code Form is subject to the terms of the Mozilla Public # License, v2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. import os import re import yaml import lib.genanki.genanki as genanki class Anki: def generate_id(): """Generate a 32-bit ID useful for Anki.""" return random.randrange(1 << 30, 1 << 31) # return datetime.now().timestamp() def import_card_definitions(self, yaml_filepath): """Import card definitions from YAML file. Adds a Anki-like {{import:file.txt}} file import command which works similar to the #include preprocessor command in C-like languages, directly replacing the command with text from the import file. """ path = os.path.dirname(yaml_filepath) + '/' with open(yaml_filepath, 'r') as f: cards = f.read() cards = yaml.load(cards) for subject, model in cards.items(): for template in model['templates']: for fmt in ('qfmt', 'afmt'): with open(path + template[fmt], 'r') as f: lines = f.readlines() temp = '' for line in lines: match = re.match('\s*{{import:(.*)}}', line) if match: with open(path + match.group(1), 'r') as f: line = f.read() temp += line template[fmt] = temp return cards
63d42df486c7276c4edc7d1b89e2e22215d81f61
picoCTF-web/api/apps/v1/groups.py
picoCTF-web/api/apps/v1/groups.py
"""Group manangement.""" from flask import jsonify from flask_restplus import Namespace, Resource import api.team import api.user ns = Namespace('groups', description='Group management') @ns.route('/') class GroupList(Resource): """Get the list of groups, or add a new group.""" # @TODO allow admins to see all groups with querystring parameter # @require_login @ns.response(200, 'Success') @ns.response(401, 'Not logged in') def get(self): """Get the groups of which you are a member.""" curr_tid = api.user.get_user()['tid'] return jsonify(api.team.get_groups(curr_tid)) @ns.route('/<string:group_id>') class Group(Resource): """Get a specific group.""" pass
"""Group manangement.""" from flask import jsonify from flask_restplus import Namespace, Resource import api.group import api.team import api.user from api.common import PicoException ns = Namespace('groups', description='Group management') @ns.route('/') class GroupList(Resource): """Get the list of groups, or add a new group.""" # @TODO allow admins to see all groups with querystring parameter # @require_login @ns.response(200, 'Success') @ns.response(401, 'Not logged in') def get(self): """Get the groups of which you are a member.""" curr_tid = api.user.get_user()['tid'] return jsonify(api.team.get_groups(curr_tid)) @ns.response(200, 'Success') @ns.response(403, 'You do not have permission to view this group.') @ns.response(404, 'Group not found') # @require_login @ns.route('/<string:group_id>') class Group(Resource): """Get a specific group.""" def get(self, group_id): """Get a specific group.""" group = api.group.get_group(gid=group_id) if not group: raise PicoException('Group not found', 404) group_members = [group['owner']] + group['members'] + group['teachers'] curr_user = api.user.get_user() if curr_user['tid'] not in group_members and not curr_user['admin']: raise PicoException( 'You do not have permission to view this group.', 403 ) return jsonify(group)
Add route to get specific group
Add route to get specific group
Python
mit
royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF
"""Group manangement.""" from flask import jsonify from flask_restplus import Namespace, Resource import api.team import api.user ns = Namespace('groups', description='Group management') @ns.route('/') class GroupList(Resource): """Get the list of groups, or add a new group.""" # @TODO allow admins to see all groups with querystring parameter # @require_login @ns.response(200, 'Success') @ns.response(401, 'Not logged in') def get(self): """Get the groups of which you are a member.""" curr_tid = api.user.get_user()['tid'] return jsonify(api.team.get_groups(curr_tid)) @ns.route('/<string:group_id>') class Group(Resource): """Get a specific group.""" pass Add route to get specific group
"""Group manangement.""" from flask import jsonify from flask_restplus import Namespace, Resource import api.group import api.team import api.user from api.common import PicoException ns = Namespace('groups', description='Group management') @ns.route('/') class GroupList(Resource): """Get the list of groups, or add a new group.""" # @TODO allow admins to see all groups with querystring parameter # @require_login @ns.response(200, 'Success') @ns.response(401, 'Not logged in') def get(self): """Get the groups of which you are a member.""" curr_tid = api.user.get_user()['tid'] return jsonify(api.team.get_groups(curr_tid)) @ns.response(200, 'Success') @ns.response(403, 'You do not have permission to view this group.') @ns.response(404, 'Group not found') # @require_login @ns.route('/<string:group_id>') class Group(Resource): """Get a specific group.""" def get(self, group_id): """Get a specific group.""" group = api.group.get_group(gid=group_id) if not group: raise PicoException('Group not found', 404) group_members = [group['owner']] + group['members'] + group['teachers'] curr_user = api.user.get_user() if curr_user['tid'] not in group_members and not curr_user['admin']: raise PicoException( 'You do not have permission to view this group.', 403 ) return jsonify(group)
<commit_before>"""Group manangement.""" from flask import jsonify from flask_restplus import Namespace, Resource import api.team import api.user ns = Namespace('groups', description='Group management') @ns.route('/') class GroupList(Resource): """Get the list of groups, or add a new group.""" # @TODO allow admins to see all groups with querystring parameter # @require_login @ns.response(200, 'Success') @ns.response(401, 'Not logged in') def get(self): """Get the groups of which you are a member.""" curr_tid = api.user.get_user()['tid'] return jsonify(api.team.get_groups(curr_tid)) @ns.route('/<string:group_id>') class Group(Resource): """Get a specific group.""" pass <commit_msg>Add route to get specific group<commit_after>
"""Group manangement.""" from flask import jsonify from flask_restplus import Namespace, Resource import api.group import api.team import api.user from api.common import PicoException ns = Namespace('groups', description='Group management') @ns.route('/') class GroupList(Resource): """Get the list of groups, or add a new group.""" # @TODO allow admins to see all groups with querystring parameter # @require_login @ns.response(200, 'Success') @ns.response(401, 'Not logged in') def get(self): """Get the groups of which you are a member.""" curr_tid = api.user.get_user()['tid'] return jsonify(api.team.get_groups(curr_tid)) @ns.response(200, 'Success') @ns.response(403, 'You do not have permission to view this group.') @ns.response(404, 'Group not found') # @require_login @ns.route('/<string:group_id>') class Group(Resource): """Get a specific group.""" def get(self, group_id): """Get a specific group.""" group = api.group.get_group(gid=group_id) if not group: raise PicoException('Group not found', 404) group_members = [group['owner']] + group['members'] + group['teachers'] curr_user = api.user.get_user() if curr_user['tid'] not in group_members and not curr_user['admin']: raise PicoException( 'You do not have permission to view this group.', 403 ) return jsonify(group)
"""Group manangement.""" from flask import jsonify from flask_restplus import Namespace, Resource import api.team import api.user ns = Namespace('groups', description='Group management') @ns.route('/') class GroupList(Resource): """Get the list of groups, or add a new group.""" # @TODO allow admins to see all groups with querystring parameter # @require_login @ns.response(200, 'Success') @ns.response(401, 'Not logged in') def get(self): """Get the groups of which you are a member.""" curr_tid = api.user.get_user()['tid'] return jsonify(api.team.get_groups(curr_tid)) @ns.route('/<string:group_id>') class Group(Resource): """Get a specific group.""" pass Add route to get specific group"""Group manangement.""" from flask import jsonify from flask_restplus import Namespace, Resource import api.group import api.team import api.user from api.common import PicoException ns = Namespace('groups', description='Group management') @ns.route('/') class GroupList(Resource): """Get the list of groups, or add a new group.""" # @TODO allow admins to see all groups with querystring parameter # @require_login @ns.response(200, 'Success') @ns.response(401, 'Not logged in') def get(self): """Get the groups of which you are a member.""" curr_tid = api.user.get_user()['tid'] return jsonify(api.team.get_groups(curr_tid)) @ns.response(200, 'Success') @ns.response(403, 'You do not have permission to view this group.') @ns.response(404, 'Group not found') # @require_login @ns.route('/<string:group_id>') class Group(Resource): """Get a specific group.""" def get(self, group_id): """Get a specific group.""" group = api.group.get_group(gid=group_id) if not group: raise PicoException('Group not found', 404) group_members = [group['owner']] + group['members'] + group['teachers'] curr_user = api.user.get_user() if curr_user['tid'] not in group_members and not curr_user['admin']: raise PicoException( 'You do not have permission to view this group.', 403 ) return jsonify(group)
<commit_before>"""Group manangement.""" from flask import jsonify from flask_restplus import Namespace, Resource import api.team import api.user ns = Namespace('groups', description='Group management') @ns.route('/') class GroupList(Resource): """Get the list of groups, or add a new group.""" # @TODO allow admins to see all groups with querystring parameter # @require_login @ns.response(200, 'Success') @ns.response(401, 'Not logged in') def get(self): """Get the groups of which you are a member.""" curr_tid = api.user.get_user()['tid'] return jsonify(api.team.get_groups(curr_tid)) @ns.route('/<string:group_id>') class Group(Resource): """Get a specific group.""" pass <commit_msg>Add route to get specific group<commit_after>"""Group manangement.""" from flask import jsonify from flask_restplus import Namespace, Resource import api.group import api.team import api.user from api.common import PicoException ns = Namespace('groups', description='Group management') @ns.route('/') class GroupList(Resource): """Get the list of groups, or add a new group.""" # @TODO allow admins to see all groups with querystring parameter # @require_login @ns.response(200, 'Success') @ns.response(401, 'Not logged in') def get(self): """Get the groups of which you are a member.""" curr_tid = api.user.get_user()['tid'] return jsonify(api.team.get_groups(curr_tid)) @ns.response(200, 'Success') @ns.response(403, 'You do not have permission to view this group.') @ns.response(404, 'Group not found') # @require_login @ns.route('/<string:group_id>') class Group(Resource): """Get a specific group.""" def get(self, group_id): """Get a specific group.""" group = api.group.get_group(gid=group_id) if not group: raise PicoException('Group not found', 404) group_members = [group['owner']] + group['members'] + group['teachers'] curr_user = api.user.get_user() if curr_user['tid'] not in group_members and not curr_user['admin']: raise PicoException( 'You do not have permission to view this group.', 403 ) return jsonify(group)
18fa5009d78f8f22af0d7e4902918e7c6020699d
tests/models.py
tests/models.py
from django.db import models class NonAsciiRepr: def __repr__(self): return "nôt åscíì" class Binary(models.Model): field = models.BinaryField() try: from django.db.models import JSONField except ImportError: # Django<3.1 try: from django.contrib.postgres.fields import JSONField except ImportError: # psycopg2 not installed JSONField = None if JSONField: class PostgresJSON(models.Model): field = JSONField()
from django.db import models class NonAsciiRepr: def __repr__(self): return "nôt åscíì" class Binary(models.Model): field = models.BinaryField() try: from django.db.models import JSONField except ImportError: # Django<3.1 try: from django.contrib.postgres.fields import JSONField except ImportError: # psycopg2 not installed JSONField = None if JSONField: class PostgresJSON(models.Model): field = JSONField()
Fix one coding style problem
Fix one coding style problem
Python
bsd-3-clause
django-debug-toolbar/django-debug-toolbar,tim-schilling/django-debug-toolbar,tim-schilling/django-debug-toolbar,spookylukey/django-debug-toolbar,spookylukey/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,tim-schilling/django-debug-toolbar,jazzband/django-debug-toolbar,jazzband/django-debug-toolbar,spookylukey/django-debug-toolbar,django-debug-toolbar/django-debug-toolbar,jazzband/django-debug-toolbar
from django.db import models class NonAsciiRepr: def __repr__(self): return "nôt åscíì" class Binary(models.Model): field = models.BinaryField() try: from django.db.models import JSONField except ImportError: # Django<3.1 try: from django.contrib.postgres.fields import JSONField except ImportError: # psycopg2 not installed JSONField = None if JSONField: class PostgresJSON(models.Model): field = JSONField() Fix one coding style problem
from django.db import models class NonAsciiRepr: def __repr__(self): return "nôt åscíì" class Binary(models.Model): field = models.BinaryField() try: from django.db.models import JSONField except ImportError: # Django<3.1 try: from django.contrib.postgres.fields import JSONField except ImportError: # psycopg2 not installed JSONField = None if JSONField: class PostgresJSON(models.Model): field = JSONField()
<commit_before>from django.db import models class NonAsciiRepr: def __repr__(self): return "nôt åscíì" class Binary(models.Model): field = models.BinaryField() try: from django.db.models import JSONField except ImportError: # Django<3.1 try: from django.contrib.postgres.fields import JSONField except ImportError: # psycopg2 not installed JSONField = None if JSONField: class PostgresJSON(models.Model): field = JSONField() <commit_msg>Fix one coding style problem<commit_after>
from django.db import models class NonAsciiRepr: def __repr__(self): return "nôt åscíì" class Binary(models.Model): field = models.BinaryField() try: from django.db.models import JSONField except ImportError: # Django<3.1 try: from django.contrib.postgres.fields import JSONField except ImportError: # psycopg2 not installed JSONField = None if JSONField: class PostgresJSON(models.Model): field = JSONField()
from django.db import models class NonAsciiRepr: def __repr__(self): return "nôt åscíì" class Binary(models.Model): field = models.BinaryField() try: from django.db.models import JSONField except ImportError: # Django<3.1 try: from django.contrib.postgres.fields import JSONField except ImportError: # psycopg2 not installed JSONField = None if JSONField: class PostgresJSON(models.Model): field = JSONField() Fix one coding style problemfrom django.db import models class NonAsciiRepr: def __repr__(self): return "nôt åscíì" class Binary(models.Model): field = models.BinaryField() try: from django.db.models import JSONField except ImportError: # Django<3.1 try: from django.contrib.postgres.fields import JSONField except ImportError: # psycopg2 not installed JSONField = None if JSONField: class PostgresJSON(models.Model): field = JSONField()
<commit_before>from django.db import models class NonAsciiRepr: def __repr__(self): return "nôt åscíì" class Binary(models.Model): field = models.BinaryField() try: from django.db.models import JSONField except ImportError: # Django<3.1 try: from django.contrib.postgres.fields import JSONField except ImportError: # psycopg2 not installed JSONField = None if JSONField: class PostgresJSON(models.Model): field = JSONField() <commit_msg>Fix one coding style problem<commit_after>from django.db import models class NonAsciiRepr: def __repr__(self): return "nôt åscíì" class Binary(models.Model): field = models.BinaryField() try: from django.db.models import JSONField except ImportError: # Django<3.1 try: from django.contrib.postgres.fields import JSONField except ImportError: # psycopg2 not installed JSONField = None if JSONField: class PostgresJSON(models.Model): field = JSONField()
f5885a2644a21def7340e0d34b809a98472b366c
heufybot/modules/commands/nick.py
heufybot/modules/commands/nick.py
from twisted.plugin import IPlugin from heufybot.moduleinterface import IBotModule from heufybot.modules.commandinterface import BotCommand from zope.interface import implements class NickCommand(BotCommand): implements(IPlugin, IBotModule) name = "Nick" def triggers(self): return ["nick"] def load(self): self.help = "Commands: nick | Change the nickname of the bot." self.commandHelp = {} def checkPermissions(self, server, source, user, command): return not self.bot.moduleHandler.runActionUntilFalse("checkadminpermission", server, source, user, "connection-control") def execute(self, server, source, command, params, data): if len(params) < 1: self.bot.servers[server].outputHandler.cmdPRIVMSG(source, "Change my nick to what?") else: self.bot.servers[server].outputHandler.cmdNICK(params[0]) nickCommand = NickCommand()
from twisted.plugin import IPlugin from heufybot.moduleinterface import IBotModule from heufybot.modules.commandinterface import BotCommand from zope.interface import implements class NickCommand(BotCommand): implements(IPlugin, IBotModule) name = "Nick" def triggers(self): return ["nick"] def load(self): self.help = "Commands: nick <newnick> | Change the nickname of the bot." self.commandHelp = {} def checkPermissions(self, server, source, user, command): return not self.bot.moduleHandler.runActionUntilFalse("checkadminpermission", server, source, user, "connection-control") def execute(self, server, source, command, params, data): if len(params) < 1: self.bot.servers[server].outputHandler.cmdPRIVMSG(source, "Change my nick to what?") else: self.bot.servers[server].outputHandler.cmdNICK(params[0]) nickCommand = NickCommand()
Fix the Nick command help text
Fix the Nick command help text
Python
mit
Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot
from twisted.plugin import IPlugin from heufybot.moduleinterface import IBotModule from heufybot.modules.commandinterface import BotCommand from zope.interface import implements class NickCommand(BotCommand): implements(IPlugin, IBotModule) name = "Nick" def triggers(self): return ["nick"] def load(self): self.help = "Commands: nick | Change the nickname of the bot." self.commandHelp = {} def checkPermissions(self, server, source, user, command): return not self.bot.moduleHandler.runActionUntilFalse("checkadminpermission", server, source, user, "connection-control") def execute(self, server, source, command, params, data): if len(params) < 1: self.bot.servers[server].outputHandler.cmdPRIVMSG(source, "Change my nick to what?") else: self.bot.servers[server].outputHandler.cmdNICK(params[0]) nickCommand = NickCommand() Fix the Nick command help text
from twisted.plugin import IPlugin from heufybot.moduleinterface import IBotModule from heufybot.modules.commandinterface import BotCommand from zope.interface import implements class NickCommand(BotCommand): implements(IPlugin, IBotModule) name = "Nick" def triggers(self): return ["nick"] def load(self): self.help = "Commands: nick <newnick> | Change the nickname of the bot." self.commandHelp = {} def checkPermissions(self, server, source, user, command): return not self.bot.moduleHandler.runActionUntilFalse("checkadminpermission", server, source, user, "connection-control") def execute(self, server, source, command, params, data): if len(params) < 1: self.bot.servers[server].outputHandler.cmdPRIVMSG(source, "Change my nick to what?") else: self.bot.servers[server].outputHandler.cmdNICK(params[0]) nickCommand = NickCommand()
<commit_before>from twisted.plugin import IPlugin from heufybot.moduleinterface import IBotModule from heufybot.modules.commandinterface import BotCommand from zope.interface import implements class NickCommand(BotCommand): implements(IPlugin, IBotModule) name = "Nick" def triggers(self): return ["nick"] def load(self): self.help = "Commands: nick | Change the nickname of the bot." self.commandHelp = {} def checkPermissions(self, server, source, user, command): return not self.bot.moduleHandler.runActionUntilFalse("checkadminpermission", server, source, user, "connection-control") def execute(self, server, source, command, params, data): if len(params) < 1: self.bot.servers[server].outputHandler.cmdPRIVMSG(source, "Change my nick to what?") else: self.bot.servers[server].outputHandler.cmdNICK(params[0]) nickCommand = NickCommand() <commit_msg>Fix the Nick command help text<commit_after>
from twisted.plugin import IPlugin from heufybot.moduleinterface import IBotModule from heufybot.modules.commandinterface import BotCommand from zope.interface import implements class NickCommand(BotCommand): implements(IPlugin, IBotModule) name = "Nick" def triggers(self): return ["nick"] def load(self): self.help = "Commands: nick <newnick> | Change the nickname of the bot." self.commandHelp = {} def checkPermissions(self, server, source, user, command): return not self.bot.moduleHandler.runActionUntilFalse("checkadminpermission", server, source, user, "connection-control") def execute(self, server, source, command, params, data): if len(params) < 1: self.bot.servers[server].outputHandler.cmdPRIVMSG(source, "Change my nick to what?") else: self.bot.servers[server].outputHandler.cmdNICK(params[0]) nickCommand = NickCommand()
from twisted.plugin import IPlugin from heufybot.moduleinterface import IBotModule from heufybot.modules.commandinterface import BotCommand from zope.interface import implements class NickCommand(BotCommand): implements(IPlugin, IBotModule) name = "Nick" def triggers(self): return ["nick"] def load(self): self.help = "Commands: nick | Change the nickname of the bot." self.commandHelp = {} def checkPermissions(self, server, source, user, command): return not self.bot.moduleHandler.runActionUntilFalse("checkadminpermission", server, source, user, "connection-control") def execute(self, server, source, command, params, data): if len(params) < 1: self.bot.servers[server].outputHandler.cmdPRIVMSG(source, "Change my nick to what?") else: self.bot.servers[server].outputHandler.cmdNICK(params[0]) nickCommand = NickCommand() Fix the Nick command help textfrom twisted.plugin import IPlugin from heufybot.moduleinterface import IBotModule from heufybot.modules.commandinterface import BotCommand from zope.interface import implements class NickCommand(BotCommand): implements(IPlugin, IBotModule) name = "Nick" def triggers(self): return ["nick"] def load(self): self.help = "Commands: nick <newnick> | Change the nickname of the bot." self.commandHelp = {} def checkPermissions(self, server, source, user, command): return not self.bot.moduleHandler.runActionUntilFalse("checkadminpermission", server, source, user, "connection-control") def execute(self, server, source, command, params, data): if len(params) < 1: self.bot.servers[server].outputHandler.cmdPRIVMSG(source, "Change my nick to what?") else: self.bot.servers[server].outputHandler.cmdNICK(params[0]) nickCommand = NickCommand()
<commit_before>from twisted.plugin import IPlugin from heufybot.moduleinterface import IBotModule from heufybot.modules.commandinterface import BotCommand from zope.interface import implements class NickCommand(BotCommand): implements(IPlugin, IBotModule) name = "Nick" def triggers(self): return ["nick"] def load(self): self.help = "Commands: nick | Change the nickname of the bot." self.commandHelp = {} def checkPermissions(self, server, source, user, command): return not self.bot.moduleHandler.runActionUntilFalse("checkadminpermission", server, source, user, "connection-control") def execute(self, server, source, command, params, data): if len(params) < 1: self.bot.servers[server].outputHandler.cmdPRIVMSG(source, "Change my nick to what?") else: self.bot.servers[server].outputHandler.cmdNICK(params[0]) nickCommand = NickCommand() <commit_msg>Fix the Nick command help text<commit_after>from twisted.plugin import IPlugin from heufybot.moduleinterface import IBotModule from heufybot.modules.commandinterface import BotCommand from zope.interface import implements class NickCommand(BotCommand): implements(IPlugin, IBotModule) name = "Nick" def triggers(self): return ["nick"] def load(self): self.help = "Commands: nick <newnick> | Change the nickname of the bot." self.commandHelp = {} def checkPermissions(self, server, source, user, command): return not self.bot.moduleHandler.runActionUntilFalse("checkadminpermission", server, source, user, "connection-control") def execute(self, server, source, command, params, data): if len(params) < 1: self.bot.servers[server].outputHandler.cmdPRIVMSG(source, "Change my nick to what?") else: self.bot.servers[server].outputHandler.cmdNICK(params[0]) nickCommand = NickCommand()
f11c489f6b28edc1ec9b399bbff1f1d0831d23bb
grab.py
grab.py
#!/usr/bin/env python # Grab runs from S3 and do analysis # # Daniel Klein, 2015-08-14 import sys import subprocess import glob import argparse parser = argparse.ArgumentParser() parser.add_argument('remote_dir', help = 'S3 directory with completed runs') parser.add_argument('run_ids', help = 'IDs of runs to analyze', nargs = '+') parser.add_argument('--leave', help = 'don\'t delete downloaded files', action = 'store_true') args = parser.parse_args() for run_id in args.run_ids: print run_id match_run = '%s_*__completed.json' % run_id subprocess.call(['aws', 's3', 'sync', args.remote_dir, 'runs/', '--exclude', '*', '--include', match_run]) runs = glob.glob('runs/' + match_run) print runs run_stems = [run.split('completed')[0] for run in runs] subprocess.call(['python', 'test.py'] + \ [run_stem + 'load.json' for run_stem in run_stems]) subprocess.call(['mv', 'out.pdf', 'runs/%s_figs.pdf' % run_id]) if not args.leave: for run in runs: subprocess.call(['rm', run])
#!/usr/bin/env python # Grab runs from S3 and do analysis # # Daniel Klein, 2015-08-14 import sys import subprocess import glob import argparse parser = argparse.ArgumentParser() parser.add_argument('remote_dir', help = 'S3 directory with completed runs') parser.add_argument('output_dir', help = 'Local destination for output') parser.add_argument('run_ids', help = 'IDs of runs to analyze', nargs = '+') parser.add_argument('--leave', help = 'don\'t delete downloaded files', action = 'store_true') args = parser.parse_args() for run_id in args.run_ids: print run_id match_run = '%s_*__completed.json' % run_id subprocess.call(['aws', 's3', 'sync', args.remote_dir, args.output_dir, '--exclude', '*', '--include', match_run]) runs = glob.glob(args.output_dir + match_run) print runs run_stems = [run.split('completed')[0] for run in runs] subprocess.call(['python', 'test.py'] + \ [run_stem + 'load.json' for run_stem in run_stems]) subprocess.call(['mv', 'out.pdf', '%s/%s_figs.pdf' % (args.output_dir, run_id)]) if not args.leave: for run in runs: subprocess.call(['rm', run])
Add specification of output directory from command line
Add specification of output directory from command line
Python
mit
othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel
#!/usr/bin/env python # Grab runs from S3 and do analysis # # Daniel Klein, 2015-08-14 import sys import subprocess import glob import argparse parser = argparse.ArgumentParser() parser.add_argument('remote_dir', help = 'S3 directory with completed runs') parser.add_argument('run_ids', help = 'IDs of runs to analyze', nargs = '+') parser.add_argument('--leave', help = 'don\'t delete downloaded files', action = 'store_true') args = parser.parse_args() for run_id in args.run_ids: print run_id match_run = '%s_*__completed.json' % run_id subprocess.call(['aws', 's3', 'sync', args.remote_dir, 'runs/', '--exclude', '*', '--include', match_run]) runs = glob.glob('runs/' + match_run) print runs run_stems = [run.split('completed')[0] for run in runs] subprocess.call(['python', 'test.py'] + \ [run_stem + 'load.json' for run_stem in run_stems]) subprocess.call(['mv', 'out.pdf', 'runs/%s_figs.pdf' % run_id]) if not args.leave: for run in runs: subprocess.call(['rm', run]) Add specification of output directory from command line
#!/usr/bin/env python # Grab runs from S3 and do analysis # # Daniel Klein, 2015-08-14 import sys import subprocess import glob import argparse parser = argparse.ArgumentParser() parser.add_argument('remote_dir', help = 'S3 directory with completed runs') parser.add_argument('output_dir', help = 'Local destination for output') parser.add_argument('run_ids', help = 'IDs of runs to analyze', nargs = '+') parser.add_argument('--leave', help = 'don\'t delete downloaded files', action = 'store_true') args = parser.parse_args() for run_id in args.run_ids: print run_id match_run = '%s_*__completed.json' % run_id subprocess.call(['aws', 's3', 'sync', args.remote_dir, args.output_dir, '--exclude', '*', '--include', match_run]) runs = glob.glob(args.output_dir + match_run) print runs run_stems = [run.split('completed')[0] for run in runs] subprocess.call(['python', 'test.py'] + \ [run_stem + 'load.json' for run_stem in run_stems]) subprocess.call(['mv', 'out.pdf', '%s/%s_figs.pdf' % (args.output_dir, run_id)]) if not args.leave: for run in runs: subprocess.call(['rm', run])
<commit_before>#!/usr/bin/env python # Grab runs from S3 and do analysis # # Daniel Klein, 2015-08-14 import sys import subprocess import glob import argparse parser = argparse.ArgumentParser() parser.add_argument('remote_dir', help = 'S3 directory with completed runs') parser.add_argument('run_ids', help = 'IDs of runs to analyze', nargs = '+') parser.add_argument('--leave', help = 'don\'t delete downloaded files', action = 'store_true') args = parser.parse_args() for run_id in args.run_ids: print run_id match_run = '%s_*__completed.json' % run_id subprocess.call(['aws', 's3', 'sync', args.remote_dir, 'runs/', '--exclude', '*', '--include', match_run]) runs = glob.glob('runs/' + match_run) print runs run_stems = [run.split('completed')[0] for run in runs] subprocess.call(['python', 'test.py'] + \ [run_stem + 'load.json' for run_stem in run_stems]) subprocess.call(['mv', 'out.pdf', 'runs/%s_figs.pdf' % run_id]) if not args.leave: for run in runs: subprocess.call(['rm', run]) <commit_msg>Add specification of output directory from command line<commit_after>
#!/usr/bin/env python # Grab runs from S3 and do analysis # # Daniel Klein, 2015-08-14 import sys import subprocess import glob import argparse parser = argparse.ArgumentParser() parser.add_argument('remote_dir', help = 'S3 directory with completed runs') parser.add_argument('output_dir', help = 'Local destination for output') parser.add_argument('run_ids', help = 'IDs of runs to analyze', nargs = '+') parser.add_argument('--leave', help = 'don\'t delete downloaded files', action = 'store_true') args = parser.parse_args() for run_id in args.run_ids: print run_id match_run = '%s_*__completed.json' % run_id subprocess.call(['aws', 's3', 'sync', args.remote_dir, args.output_dir, '--exclude', '*', '--include', match_run]) runs = glob.glob(args.output_dir + match_run) print runs run_stems = [run.split('completed')[0] for run in runs] subprocess.call(['python', 'test.py'] + \ [run_stem + 'load.json' for run_stem in run_stems]) subprocess.call(['mv', 'out.pdf', '%s/%s_figs.pdf' % (args.output_dir, run_id)]) if not args.leave: for run in runs: subprocess.call(['rm', run])
#!/usr/bin/env python # Grab runs from S3 and do analysis # # Daniel Klein, 2015-08-14 import sys import subprocess import glob import argparse parser = argparse.ArgumentParser() parser.add_argument('remote_dir', help = 'S3 directory with completed runs') parser.add_argument('run_ids', help = 'IDs of runs to analyze', nargs = '+') parser.add_argument('--leave', help = 'don\'t delete downloaded files', action = 'store_true') args = parser.parse_args() for run_id in args.run_ids: print run_id match_run = '%s_*__completed.json' % run_id subprocess.call(['aws', 's3', 'sync', args.remote_dir, 'runs/', '--exclude', '*', '--include', match_run]) runs = glob.glob('runs/' + match_run) print runs run_stems = [run.split('completed')[0] for run in runs] subprocess.call(['python', 'test.py'] + \ [run_stem + 'load.json' for run_stem in run_stems]) subprocess.call(['mv', 'out.pdf', 'runs/%s_figs.pdf' % run_id]) if not args.leave: for run in runs: subprocess.call(['rm', run]) Add specification of output directory from command line#!/usr/bin/env python # Grab runs from S3 and do analysis # # Daniel Klein, 2015-08-14 import sys import subprocess import glob import argparse parser = argparse.ArgumentParser() parser.add_argument('remote_dir', help = 'S3 directory with completed runs') parser.add_argument('output_dir', help = 'Local destination for output') parser.add_argument('run_ids', help = 'IDs of runs to analyze', nargs = '+') parser.add_argument('--leave', help = 'don\'t delete downloaded files', action = 'store_true') args = parser.parse_args() for run_id in args.run_ids: print run_id match_run = '%s_*__completed.json' % run_id subprocess.call(['aws', 's3', 'sync', args.remote_dir, args.output_dir, '--exclude', '*', '--include', match_run]) runs = glob.glob(args.output_dir + match_run) print runs run_stems = [run.split('completed')[0] for run in runs] subprocess.call(['python', 'test.py'] + \ [run_stem + 'load.json' for run_stem in run_stems]) subprocess.call(['mv', 'out.pdf', '%s/%s_figs.pdf' % (args.output_dir, run_id)]) if not args.leave: for run in runs: subprocess.call(['rm', run])
<commit_before>#!/usr/bin/env python # Grab runs from S3 and do analysis # # Daniel Klein, 2015-08-14 import sys import subprocess import glob import argparse parser = argparse.ArgumentParser() parser.add_argument('remote_dir', help = 'S3 directory with completed runs') parser.add_argument('run_ids', help = 'IDs of runs to analyze', nargs = '+') parser.add_argument('--leave', help = 'don\'t delete downloaded files', action = 'store_true') args = parser.parse_args() for run_id in args.run_ids: print run_id match_run = '%s_*__completed.json' % run_id subprocess.call(['aws', 's3', 'sync', args.remote_dir, 'runs/', '--exclude', '*', '--include', match_run]) runs = glob.glob('runs/' + match_run) print runs run_stems = [run.split('completed')[0] for run in runs] subprocess.call(['python', 'test.py'] + \ [run_stem + 'load.json' for run_stem in run_stems]) subprocess.call(['mv', 'out.pdf', 'runs/%s_figs.pdf' % run_id]) if not args.leave: for run in runs: subprocess.call(['rm', run]) <commit_msg>Add specification of output directory from command line<commit_after>#!/usr/bin/env python # Grab runs from S3 and do analysis # # Daniel Klein, 2015-08-14 import sys import subprocess import glob import argparse parser = argparse.ArgumentParser() parser.add_argument('remote_dir', help = 'S3 directory with completed runs') parser.add_argument('output_dir', help = 'Local destination for output') parser.add_argument('run_ids', help = 'IDs of runs to analyze', nargs = '+') parser.add_argument('--leave', help = 'don\'t delete downloaded files', action = 'store_true') args = parser.parse_args() for run_id in args.run_ids: print run_id match_run = '%s_*__completed.json' % run_id subprocess.call(['aws', 's3', 'sync', args.remote_dir, args.output_dir, '--exclude', '*', '--include', match_run]) runs = glob.glob(args.output_dir + match_run) print runs run_stems = [run.split('completed')[0] for run in runs] subprocess.call(['python', 'test.py'] + \ [run_stem + 'load.json' for run_stem in run_stems]) subprocess.call(['mv', 'out.pdf', '%s/%s_figs.pdf' % (args.output_dir, run_id)]) if not args.leave: for run in runs: subprocess.call(['rm', run])
682805bfa7ea77276dd20e02732eaaec48d84e2b
server/main.py
server/main.py
import base64 import json import struct from flask import Flask, request from scarab import EncryptedArray, PublicKey from .store import Store from common.utils import binary app = Flask(__name__) store = Store() @app.route('/db_size') def get_db_size(): data = {'num_records': store.record_count, 'record_size': store.record_size} return json.dumps(data), 200, {'Content-Type': 'text/json'} @app.route('/retrieve', methods=['POST']) def retrieve(): print("Starting retrieve call...") public_key = PublicKey(request.form['PUBLIC_KEY']) enc_index = EncryptedArray(store.record_size, public_key, request.form['ENC_INDEX']) enc_data = store.retrieve(enc_index, public_key) s_bits = [str(b) for b in enc_data] obj = json.dumps(s_bits) return obj @app.route('/set', methods=['POST']) def set(): try: index = int(request.form['INDEX']) data = int.from_bytes(base64.b64decode(request.form['DATA']), 'big') store.set(index, binary(data, store.record_size)) return '', 200 except Exception as e: #import traceback #traceback.print_last() print(e)
import base64 import json import struct from flask import Flask, request from scarab import EncryptedArray, PublicKey from .store import Store from common.utils import binary app = Flask(__name__) store = Store() @app.route('/db_size') def get_db_size(): data = {'num_records': store.record_count, 'record_size': store.record_size} return json.dumps(data), 200, {'Content-Type': 'text/json'} @app.route('/retrieve', methods=['POST']) def retrieve(): print("Starting retrieve call...") public_key = PublicKey(str(request.form['PUBLIC_KEY'])) enc_index = EncryptedArray(store.record_size, public_key, request.form['ENC_INDEX']) enc_data = store.retrieve(enc_index, public_key) s_bits = [str(b) for b in enc_data] obj = json.dumps(s_bits) return obj @app.route('/set', methods=['POST']) def set(): try: index = int(request.form['INDEX']) data = int.from_bytes(base64.b64decode(request.form['DATA']), 'big') store.set(index, binary(data, store.record_size)) return '', 200 except Exception as e: #import traceback #traceback.print_last() print(e)
Convert public key string type in server
Convert public key string type in server This fixes a segmentation fault caused by an incorrect string encoding when run in Python 2.7.
Python
mit
blindstore/blindstore-old-scarab
import base64 import json import struct from flask import Flask, request from scarab import EncryptedArray, PublicKey from .store import Store from common.utils import binary app = Flask(__name__) store = Store() @app.route('/db_size') def get_db_size(): data = {'num_records': store.record_count, 'record_size': store.record_size} return json.dumps(data), 200, {'Content-Type': 'text/json'} @app.route('/retrieve', methods=['POST']) def retrieve(): print("Starting retrieve call...") public_key = PublicKey(request.form['PUBLIC_KEY']) enc_index = EncryptedArray(store.record_size, public_key, request.form['ENC_INDEX']) enc_data = store.retrieve(enc_index, public_key) s_bits = [str(b) for b in enc_data] obj = json.dumps(s_bits) return obj @app.route('/set', methods=['POST']) def set(): try: index = int(request.form['INDEX']) data = int.from_bytes(base64.b64decode(request.form['DATA']), 'big') store.set(index, binary(data, store.record_size)) return '', 200 except Exception as e: #import traceback #traceback.print_last() print(e) Convert public key string type in server This fixes a segmentation fault caused by an incorrect string encoding when run in Python 2.7.
import base64 import json import struct from flask import Flask, request from scarab import EncryptedArray, PublicKey from .store import Store from common.utils import binary app = Flask(__name__) store = Store() @app.route('/db_size') def get_db_size(): data = {'num_records': store.record_count, 'record_size': store.record_size} return json.dumps(data), 200, {'Content-Type': 'text/json'} @app.route('/retrieve', methods=['POST']) def retrieve(): print("Starting retrieve call...") public_key = PublicKey(str(request.form['PUBLIC_KEY'])) enc_index = EncryptedArray(store.record_size, public_key, request.form['ENC_INDEX']) enc_data = store.retrieve(enc_index, public_key) s_bits = [str(b) for b in enc_data] obj = json.dumps(s_bits) return obj @app.route('/set', methods=['POST']) def set(): try: index = int(request.form['INDEX']) data = int.from_bytes(base64.b64decode(request.form['DATA']), 'big') store.set(index, binary(data, store.record_size)) return '', 200 except Exception as e: #import traceback #traceback.print_last() print(e)
<commit_before>import base64 import json import struct from flask import Flask, request from scarab import EncryptedArray, PublicKey from .store import Store from common.utils import binary app = Flask(__name__) store = Store() @app.route('/db_size') def get_db_size(): data = {'num_records': store.record_count, 'record_size': store.record_size} return json.dumps(data), 200, {'Content-Type': 'text/json'} @app.route('/retrieve', methods=['POST']) def retrieve(): print("Starting retrieve call...") public_key = PublicKey(request.form['PUBLIC_KEY']) enc_index = EncryptedArray(store.record_size, public_key, request.form['ENC_INDEX']) enc_data = store.retrieve(enc_index, public_key) s_bits = [str(b) for b in enc_data] obj = json.dumps(s_bits) return obj @app.route('/set', methods=['POST']) def set(): try: index = int(request.form['INDEX']) data = int.from_bytes(base64.b64decode(request.form['DATA']), 'big') store.set(index, binary(data, store.record_size)) return '', 200 except Exception as e: #import traceback #traceback.print_last() print(e) <commit_msg>Convert public key string type in server This fixes a segmentation fault caused by an incorrect string encoding when run in Python 2.7.<commit_after>
import base64 import json import struct from flask import Flask, request from scarab import EncryptedArray, PublicKey from .store import Store from common.utils import binary app = Flask(__name__) store = Store() @app.route('/db_size') def get_db_size(): data = {'num_records': store.record_count, 'record_size': store.record_size} return json.dumps(data), 200, {'Content-Type': 'text/json'} @app.route('/retrieve', methods=['POST']) def retrieve(): print("Starting retrieve call...") public_key = PublicKey(str(request.form['PUBLIC_KEY'])) enc_index = EncryptedArray(store.record_size, public_key, request.form['ENC_INDEX']) enc_data = store.retrieve(enc_index, public_key) s_bits = [str(b) for b in enc_data] obj = json.dumps(s_bits) return obj @app.route('/set', methods=['POST']) def set(): try: index = int(request.form['INDEX']) data = int.from_bytes(base64.b64decode(request.form['DATA']), 'big') store.set(index, binary(data, store.record_size)) return '', 200 except Exception as e: #import traceback #traceback.print_last() print(e)
import base64 import json import struct from flask import Flask, request from scarab import EncryptedArray, PublicKey from .store import Store from common.utils import binary app = Flask(__name__) store = Store() @app.route('/db_size') def get_db_size(): data = {'num_records': store.record_count, 'record_size': store.record_size} return json.dumps(data), 200, {'Content-Type': 'text/json'} @app.route('/retrieve', methods=['POST']) def retrieve(): print("Starting retrieve call...") public_key = PublicKey(request.form['PUBLIC_KEY']) enc_index = EncryptedArray(store.record_size, public_key, request.form['ENC_INDEX']) enc_data = store.retrieve(enc_index, public_key) s_bits = [str(b) for b in enc_data] obj = json.dumps(s_bits) return obj @app.route('/set', methods=['POST']) def set(): try: index = int(request.form['INDEX']) data = int.from_bytes(base64.b64decode(request.form['DATA']), 'big') store.set(index, binary(data, store.record_size)) return '', 200 except Exception as e: #import traceback #traceback.print_last() print(e) Convert public key string type in server This fixes a segmentation fault caused by an incorrect string encoding when run in Python 2.7.import base64 import json import struct from flask import Flask, request from scarab import EncryptedArray, PublicKey from .store import Store from common.utils import binary app = Flask(__name__) store = Store() @app.route('/db_size') def get_db_size(): data = {'num_records': store.record_count, 'record_size': store.record_size} return json.dumps(data), 200, {'Content-Type': 'text/json'} @app.route('/retrieve', methods=['POST']) def retrieve(): print("Starting retrieve call...") public_key = PublicKey(str(request.form['PUBLIC_KEY'])) enc_index = EncryptedArray(store.record_size, public_key, request.form['ENC_INDEX']) enc_data = store.retrieve(enc_index, public_key) s_bits = [str(b) for b in enc_data] obj = json.dumps(s_bits) return obj @app.route('/set', methods=['POST']) def set(): try: index = int(request.form['INDEX']) data = int.from_bytes(base64.b64decode(request.form['DATA']), 'big') store.set(index, binary(data, store.record_size)) return '', 200 except Exception as e: #import traceback #traceback.print_last() print(e)
<commit_before>import base64 import json import struct from flask import Flask, request from scarab import EncryptedArray, PublicKey from .store import Store from common.utils import binary app = Flask(__name__) store = Store() @app.route('/db_size') def get_db_size(): data = {'num_records': store.record_count, 'record_size': store.record_size} return json.dumps(data), 200, {'Content-Type': 'text/json'} @app.route('/retrieve', methods=['POST']) def retrieve(): print("Starting retrieve call...") public_key = PublicKey(request.form['PUBLIC_KEY']) enc_index = EncryptedArray(store.record_size, public_key, request.form['ENC_INDEX']) enc_data = store.retrieve(enc_index, public_key) s_bits = [str(b) for b in enc_data] obj = json.dumps(s_bits) return obj @app.route('/set', methods=['POST']) def set(): try: index = int(request.form['INDEX']) data = int.from_bytes(base64.b64decode(request.form['DATA']), 'big') store.set(index, binary(data, store.record_size)) return '', 200 except Exception as e: #import traceback #traceback.print_last() print(e) <commit_msg>Convert public key string type in server This fixes a segmentation fault caused by an incorrect string encoding when run in Python 2.7.<commit_after>import base64 import json import struct from flask import Flask, request from scarab import EncryptedArray, PublicKey from .store import Store from common.utils import binary app = Flask(__name__) store = Store() @app.route('/db_size') def get_db_size(): data = {'num_records': store.record_count, 'record_size': store.record_size} return json.dumps(data), 200, {'Content-Type': 'text/json'} @app.route('/retrieve', methods=['POST']) def retrieve(): print("Starting retrieve call...") public_key = PublicKey(str(request.form['PUBLIC_KEY'])) enc_index = EncryptedArray(store.record_size, public_key, request.form['ENC_INDEX']) enc_data = store.retrieve(enc_index, public_key) s_bits = [str(b) for b in enc_data] obj = json.dumps(s_bits) return obj @app.route('/set', methods=['POST']) def set(): try: index = int(request.form['INDEX']) data = int.from_bytes(base64.b64decode(request.form['DATA']), 'big') store.set(index, binary(data, store.record_size)) return '', 200 except Exception as e: #import traceback #traceback.print_last() print(e)
b5fc62d022cd773a0333560f30d8c8c0d6dbd25e
txircd/utils.py
txircd/utils.py
def unescapeEndpointDescription(desc): result = [] escape = [] depth = 0 desc = iter(desc) for char in desc: if char == "\\": try: char = desc.next() except StopIteration: raise ValueError ("Endpoint description not valid: escaped end of string") if char not in "{}": char = "\\{}".format(char) if depth == 0: result.extend(char) else: escape.extend(char) elif char == "{": if depth > 0: escape.append("{") depth += 1 elif char == "}": depth -= 1 if depth < 0: raise ValueError ("Endpoint description not valid: mismatched end brace") if depth == 0: result.extend(unescapeEndpointDescription("".join(escape)).replace("\\", "\\\\").replace(":", "\\:").replace("=", "\\=")) else: escape.append("}") else: if depth == 0: result.append(char) else: escape.append(char) if depth != 0: raise ValueError ("Endpoint description not valid: mismatched opening brace") return "".join(result)
def _enum(**enums): return type('Enum', (), enums) ModeType = _enum(List=0, ParamOnUnset=1, Param=2, NoParam=3, Status=4) def unescapeEndpointDescription(desc): result = [] escape = [] depth = 0 desc = iter(desc) for char in desc: if char == "\\": try: char = desc.next() except StopIteration: raise ValueError ("Endpoint description not valid: escaped end of string") if char not in "{}": char = "\\{}".format(char) if depth == 0: result.extend(char) else: escape.extend(char) elif char == "{": if depth > 0: escape.append("{") depth += 1 elif char == "}": depth -= 1 if depth < 0: raise ValueError ("Endpoint description not valid: mismatched end brace") if depth == 0: result.extend(unescapeEndpointDescription("".join(escape)).replace("\\", "\\\\").replace(":", "\\:").replace("=", "\\=")) else: escape.append("}") else: if depth == 0: result.append(char) else: escape.append(char) if depth != 0: raise ValueError ("Endpoint description not valid: mismatched opening brace") return "".join(result)
Add a ModeType enum for later benefit
Add a ModeType enum for later benefit
Python
bsd-3-clause
ElementalAlchemist/txircd,Heufneutje/txircd
def unescapeEndpointDescription(desc): result = [] escape = [] depth = 0 desc = iter(desc) for char in desc: if char == "\\": try: char = desc.next() except StopIteration: raise ValueError ("Endpoint description not valid: escaped end of string") if char not in "{}": char = "\\{}".format(char) if depth == 0: result.extend(char) else: escape.extend(char) elif char == "{": if depth > 0: escape.append("{") depth += 1 elif char == "}": depth -= 1 if depth < 0: raise ValueError ("Endpoint description not valid: mismatched end brace") if depth == 0: result.extend(unescapeEndpointDescription("".join(escape)).replace("\\", "\\\\").replace(":", "\\:").replace("=", "\\=")) else: escape.append("}") else: if depth == 0: result.append(char) else: escape.append(char) if depth != 0: raise ValueError ("Endpoint description not valid: mismatched opening brace") return "".join(result)Add a ModeType enum for later benefit
def _enum(**enums): return type('Enum', (), enums) ModeType = _enum(List=0, ParamOnUnset=1, Param=2, NoParam=3, Status=4) def unescapeEndpointDescription(desc): result = [] escape = [] depth = 0 desc = iter(desc) for char in desc: if char == "\\": try: char = desc.next() except StopIteration: raise ValueError ("Endpoint description not valid: escaped end of string") if char not in "{}": char = "\\{}".format(char) if depth == 0: result.extend(char) else: escape.extend(char) elif char == "{": if depth > 0: escape.append("{") depth += 1 elif char == "}": depth -= 1 if depth < 0: raise ValueError ("Endpoint description not valid: mismatched end brace") if depth == 0: result.extend(unescapeEndpointDescription("".join(escape)).replace("\\", "\\\\").replace(":", "\\:").replace("=", "\\=")) else: escape.append("}") else: if depth == 0: result.append(char) else: escape.append(char) if depth != 0: raise ValueError ("Endpoint description not valid: mismatched opening brace") return "".join(result)
<commit_before>def unescapeEndpointDescription(desc): result = [] escape = [] depth = 0 desc = iter(desc) for char in desc: if char == "\\": try: char = desc.next() except StopIteration: raise ValueError ("Endpoint description not valid: escaped end of string") if char not in "{}": char = "\\{}".format(char) if depth == 0: result.extend(char) else: escape.extend(char) elif char == "{": if depth > 0: escape.append("{") depth += 1 elif char == "}": depth -= 1 if depth < 0: raise ValueError ("Endpoint description not valid: mismatched end brace") if depth == 0: result.extend(unescapeEndpointDescription("".join(escape)).replace("\\", "\\\\").replace(":", "\\:").replace("=", "\\=")) else: escape.append("}") else: if depth == 0: result.append(char) else: escape.append(char) if depth != 0: raise ValueError ("Endpoint description not valid: mismatched opening brace") return "".join(result)<commit_msg>Add a ModeType enum for later benefit<commit_after>
def _enum(**enums): return type('Enum', (), enums) ModeType = _enum(List=0, ParamOnUnset=1, Param=2, NoParam=3, Status=4) def unescapeEndpointDescription(desc): result = [] escape = [] depth = 0 desc = iter(desc) for char in desc: if char == "\\": try: char = desc.next() except StopIteration: raise ValueError ("Endpoint description not valid: escaped end of string") if char not in "{}": char = "\\{}".format(char) if depth == 0: result.extend(char) else: escape.extend(char) elif char == "{": if depth > 0: escape.append("{") depth += 1 elif char == "}": depth -= 1 if depth < 0: raise ValueError ("Endpoint description not valid: mismatched end brace") if depth == 0: result.extend(unescapeEndpointDescription("".join(escape)).replace("\\", "\\\\").replace(":", "\\:").replace("=", "\\=")) else: escape.append("}") else: if depth == 0: result.append(char) else: escape.append(char) if depth != 0: raise ValueError ("Endpoint description not valid: mismatched opening brace") return "".join(result)
def unescapeEndpointDescription(desc): result = [] escape = [] depth = 0 desc = iter(desc) for char in desc: if char == "\\": try: char = desc.next() except StopIteration: raise ValueError ("Endpoint description not valid: escaped end of string") if char not in "{}": char = "\\{}".format(char) if depth == 0: result.extend(char) else: escape.extend(char) elif char == "{": if depth > 0: escape.append("{") depth += 1 elif char == "}": depth -= 1 if depth < 0: raise ValueError ("Endpoint description not valid: mismatched end brace") if depth == 0: result.extend(unescapeEndpointDescription("".join(escape)).replace("\\", "\\\\").replace(":", "\\:").replace("=", "\\=")) else: escape.append("}") else: if depth == 0: result.append(char) else: escape.append(char) if depth != 0: raise ValueError ("Endpoint description not valid: mismatched opening brace") return "".join(result)Add a ModeType enum for later benefitdef _enum(**enums): return type('Enum', (), enums) ModeType = _enum(List=0, ParamOnUnset=1, Param=2, NoParam=3, Status=4) def unescapeEndpointDescription(desc): result = [] escape = [] depth = 0 desc = iter(desc) for char in desc: if char == "\\": try: char = desc.next() except StopIteration: raise ValueError ("Endpoint description not valid: escaped end of string") if char not in "{}": char = "\\{}".format(char) if depth == 0: result.extend(char) else: escape.extend(char) elif char == "{": if depth > 0: escape.append("{") depth += 1 elif char == "}": depth -= 1 if depth < 0: raise ValueError ("Endpoint description not valid: mismatched end brace") if depth == 0: result.extend(unescapeEndpointDescription("".join(escape)).replace("\\", "\\\\").replace(":", "\\:").replace("=", "\\=")) else: escape.append("}") else: if depth == 0: result.append(char) else: escape.append(char) if depth != 0: raise ValueError ("Endpoint description not valid: mismatched opening brace") return "".join(result)
<commit_before>def unescapeEndpointDescription(desc): result = [] escape = [] depth = 0 desc = iter(desc) for char in desc: if char == "\\": try: char = desc.next() except StopIteration: raise ValueError ("Endpoint description not valid: escaped end of string") if char not in "{}": char = "\\{}".format(char) if depth == 0: result.extend(char) else: escape.extend(char) elif char == "{": if depth > 0: escape.append("{") depth += 1 elif char == "}": depth -= 1 if depth < 0: raise ValueError ("Endpoint description not valid: mismatched end brace") if depth == 0: result.extend(unescapeEndpointDescription("".join(escape)).replace("\\", "\\\\").replace(":", "\\:").replace("=", "\\=")) else: escape.append("}") else: if depth == 0: result.append(char) else: escape.append(char) if depth != 0: raise ValueError ("Endpoint description not valid: mismatched opening brace") return "".join(result)<commit_msg>Add a ModeType enum for later benefit<commit_after>def _enum(**enums): return type('Enum', (), enums) ModeType = _enum(List=0, ParamOnUnset=1, Param=2, NoParam=3, Status=4) def unescapeEndpointDescription(desc): result = [] escape = [] depth = 0 desc = iter(desc) for char in desc: if char == "\\": try: char = desc.next() except StopIteration: raise ValueError ("Endpoint description not valid: escaped end of string") if char not in "{}": char = "\\{}".format(char) if depth == 0: result.extend(char) else: escape.extend(char) elif char == "{": if depth > 0: escape.append("{") depth += 1 elif char == "}": depth -= 1 if depth < 0: raise ValueError ("Endpoint description not valid: mismatched end brace") if depth == 0: result.extend(unescapeEndpointDescription("".join(escape)).replace("\\", "\\\\").replace(":", "\\:").replace("=", "\\=")) else: escape.append("}") else: if depth == 0: result.append(char) else: escape.append(char) if depth != 0: raise ValueError ("Endpoint description not valid: mismatched opening brace") return "".join(result)
8687087daec7b116f51eac3d3653f0a0d3756eeb
apnsclient/__init__.py
apnsclient/__init__.py
# Copyright 2013 Getlogic BV, Sardar Yumatov # # 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. __title__ = 'APNS client' __version__ = "0.1.1" __author__ = "Sardar Yumatov" __contact__ = "ja.doma@gmail.com" __license__ = "Apache 2.0" __homepage__ = "https://bitbucket.org/sardarnl/apns-client/" __copyright__ = 'Copyright 2013 Getlogic BV, Sardar Yumatov' from apnsclient.apns import *
# Copyright 2013 Getlogic BV, Sardar Yumatov # # 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. __title__ = 'APNS client' __version__ = "0.1.5" __author__ = "Sardar Yumatov" __contact__ = "ja.doma@gmail.com" __license__ = "Apache 2.0" __homepage__ = "https://bitbucket.org/sardarnl/apns-client/" __copyright__ = 'Copyright 2013 Getlogic BV, Sardar Yumatov' from apnsclient.apns import *
Adjust the module __version__ to match the version advertised in PyPI.
Adjust the module __version__ to match the version advertised in PyPI.
Python
apache-2.0
vine/apns-client,simon-liu/apns-client,baverman/apns-client,GoodRx/apns-client,mobify/apns-client,GMcD/apns-client,MichiganLabs/apns-client,mahall/apns-client,lostdragon/apns-client,sttts/apns-client,ChatSecure/apns-client,quatanium/apns-client
# Copyright 2013 Getlogic BV, Sardar Yumatov # # 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. __title__ = 'APNS client' __version__ = "0.1.1" __author__ = "Sardar Yumatov" __contact__ = "ja.doma@gmail.com" __license__ = "Apache 2.0" __homepage__ = "https://bitbucket.org/sardarnl/apns-client/" __copyright__ = 'Copyright 2013 Getlogic BV, Sardar Yumatov' from apnsclient.apns import * Adjust the module __version__ to match the version advertised in PyPI.
# Copyright 2013 Getlogic BV, Sardar Yumatov # # 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. __title__ = 'APNS client' __version__ = "0.1.5" __author__ = "Sardar Yumatov" __contact__ = "ja.doma@gmail.com" __license__ = "Apache 2.0" __homepage__ = "https://bitbucket.org/sardarnl/apns-client/" __copyright__ = 'Copyright 2013 Getlogic BV, Sardar Yumatov' from apnsclient.apns import *
<commit_before># Copyright 2013 Getlogic BV, Sardar Yumatov # # 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. __title__ = 'APNS client' __version__ = "0.1.1" __author__ = "Sardar Yumatov" __contact__ = "ja.doma@gmail.com" __license__ = "Apache 2.0" __homepage__ = "https://bitbucket.org/sardarnl/apns-client/" __copyright__ = 'Copyright 2013 Getlogic BV, Sardar Yumatov' from apnsclient.apns import * <commit_msg>Adjust the module __version__ to match the version advertised in PyPI.<commit_after>
# Copyright 2013 Getlogic BV, Sardar Yumatov # # 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. __title__ = 'APNS client' __version__ = "0.1.5" __author__ = "Sardar Yumatov" __contact__ = "ja.doma@gmail.com" __license__ = "Apache 2.0" __homepage__ = "https://bitbucket.org/sardarnl/apns-client/" __copyright__ = 'Copyright 2013 Getlogic BV, Sardar Yumatov' from apnsclient.apns import *
# Copyright 2013 Getlogic BV, Sardar Yumatov # # 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. __title__ = 'APNS client' __version__ = "0.1.1" __author__ = "Sardar Yumatov" __contact__ = "ja.doma@gmail.com" __license__ = "Apache 2.0" __homepage__ = "https://bitbucket.org/sardarnl/apns-client/" __copyright__ = 'Copyright 2013 Getlogic BV, Sardar Yumatov' from apnsclient.apns import * Adjust the module __version__ to match the version advertised in PyPI.# Copyright 2013 Getlogic BV, Sardar Yumatov # # 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. __title__ = 'APNS client' __version__ = "0.1.5" __author__ = "Sardar Yumatov" __contact__ = "ja.doma@gmail.com" __license__ = "Apache 2.0" __homepage__ = "https://bitbucket.org/sardarnl/apns-client/" __copyright__ = 'Copyright 2013 Getlogic BV, Sardar Yumatov' from apnsclient.apns import *
<commit_before># Copyright 2013 Getlogic BV, Sardar Yumatov # # 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. __title__ = 'APNS client' __version__ = "0.1.1" __author__ = "Sardar Yumatov" __contact__ = "ja.doma@gmail.com" __license__ = "Apache 2.0" __homepage__ = "https://bitbucket.org/sardarnl/apns-client/" __copyright__ = 'Copyright 2013 Getlogic BV, Sardar Yumatov' from apnsclient.apns import * <commit_msg>Adjust the module __version__ to match the version advertised in PyPI.<commit_after># Copyright 2013 Getlogic BV, Sardar Yumatov # # 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. __title__ = 'APNS client' __version__ = "0.1.5" __author__ = "Sardar Yumatov" __contact__ = "ja.doma@gmail.com" __license__ = "Apache 2.0" __homepage__ = "https://bitbucket.org/sardarnl/apns-client/" __copyright__ = 'Copyright 2013 Getlogic BV, Sardar Yumatov' from apnsclient.apns import *
ef37001c97f83d39e8e9998a8f7d1d6db75b1e0b
examples/graph/degree_sequence.py
examples/graph/degree_sequence.py
#!/usr/bin/env python """ Random graph from given degree sequence. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $" __credits__ = """""" __revision__ = "$Revision: 503 $" # Copyright (C) 2004 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. from networkx import * z=[5,3,3,3,3,2,2,2,1,1,1] print is_valid_degree_sequence(z) print("Configuration model") G=configuration_model(z) # configuration model degree_sequence=list(degree(G).values()) # degree sequence print("Degree sequence %s" % degree_sequence) print("Degree histogram") hist={} for d in degree_sequence: if d in hist: hist[d]+=1 else: hist[d]=1 print("degree #nodes") for d in hist: print('%d %d' % (d,hist[d]))
#!/usr/bin/env python """ Random graph from given degree sequence. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $" __credits__ = """""" __revision__ = "$Revision: 503 $" # Copyright (C) 2004 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. from networkx import * z=[5,3,3,3,3,2,2,2,1,1,1] print(is_valid_degree_sequence(z)) print("Configuration model") G=configuration_model(z) # configuration model degree_sequence=list(degree(G).values()) # degree sequence print("Degree sequence %s" % degree_sequence) print("Degree histogram") hist={} for d in degree_sequence: if d in hist: hist[d]+=1 else: hist[d]=1 print("degree #nodes") for d in hist: print('%d %d' % (d,hist[d]))
Remove Python 3 incompatible print statement
Remove Python 3 incompatible print statement
Python
bsd-3-clause
goulu/networkx,harlowja/networkx,sharifulgeo/networkx,bzero/networkx,RMKD/networkx,ionanrozenfeld/networkx,bzero/networkx,blublud/networkx,SanketDG/networkx,jakevdp/networkx,farhaanbukhsh/networkx,nathania/networkx,RMKD/networkx,cmtm/networkx,aureooms/networkx,JamesClough/networkx,chrisnatali/networkx,beni55/networkx,farhaanbukhsh/networkx,jakevdp/networkx,ghdk/networkx,tmilicic/networkx,andnovar/networkx,jcurbelo/networkx,yashu-seth/networkx,kernc/networkx,jfinkels/networkx,nathania/networkx,dmoliveira/networkx,chrisnatali/networkx,harlowja/networkx,aureooms/networkx,ghdk/networkx,michaelpacer/networkx,dmoliveira/networkx,ionanrozenfeld/networkx,NvanAdrichem/networkx,ionanrozenfeld/networkx,kernc/networkx,ghdk/networkx,ltiao/networkx,aureooms/networkx,blublud/networkx,sharifulgeo/networkx,dhimmel/networkx,chrisnatali/networkx,RMKD/networkx,sharifulgeo/networkx,debsankha/networkx,OrkoHunter/networkx,blublud/networkx,jakevdp/networkx,nathania/networkx,farhaanbukhsh/networkx,debsankha/networkx,jni/networkx,bzero/networkx,jni/networkx,Sixshaman/networkx,harlowja/networkx,jni/networkx,dhimmel/networkx,kernc/networkx,dmoliveira/networkx,debsankha/networkx,wasade/networkx,dhimmel/networkx
#!/usr/bin/env python """ Random graph from given degree sequence. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $" __credits__ = """""" __revision__ = "$Revision: 503 $" # Copyright (C) 2004 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. from networkx import * z=[5,3,3,3,3,2,2,2,1,1,1] print is_valid_degree_sequence(z) print("Configuration model") G=configuration_model(z) # configuration model degree_sequence=list(degree(G).values()) # degree sequence print("Degree sequence %s" % degree_sequence) print("Degree histogram") hist={} for d in degree_sequence: if d in hist: hist[d]+=1 else: hist[d]=1 print("degree #nodes") for d in hist: print('%d %d' % (d,hist[d])) Remove Python 3 incompatible print statement
#!/usr/bin/env python """ Random graph from given degree sequence. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $" __credits__ = """""" __revision__ = "$Revision: 503 $" # Copyright (C) 2004 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. from networkx import * z=[5,3,3,3,3,2,2,2,1,1,1] print(is_valid_degree_sequence(z)) print("Configuration model") G=configuration_model(z) # configuration model degree_sequence=list(degree(G).values()) # degree sequence print("Degree sequence %s" % degree_sequence) print("Degree histogram") hist={} for d in degree_sequence: if d in hist: hist[d]+=1 else: hist[d]=1 print("degree #nodes") for d in hist: print('%d %d' % (d,hist[d]))
<commit_before>#!/usr/bin/env python """ Random graph from given degree sequence. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $" __credits__ = """""" __revision__ = "$Revision: 503 $" # Copyright (C) 2004 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. from networkx import * z=[5,3,3,3,3,2,2,2,1,1,1] print is_valid_degree_sequence(z) print("Configuration model") G=configuration_model(z) # configuration model degree_sequence=list(degree(G).values()) # degree sequence print("Degree sequence %s" % degree_sequence) print("Degree histogram") hist={} for d in degree_sequence: if d in hist: hist[d]+=1 else: hist[d]=1 print("degree #nodes") for d in hist: print('%d %d' % (d,hist[d])) <commit_msg>Remove Python 3 incompatible print statement<commit_after>
#!/usr/bin/env python """ Random graph from given degree sequence. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $" __credits__ = """""" __revision__ = "$Revision: 503 $" # Copyright (C) 2004 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. from networkx import * z=[5,3,3,3,3,2,2,2,1,1,1] print(is_valid_degree_sequence(z)) print("Configuration model") G=configuration_model(z) # configuration model degree_sequence=list(degree(G).values()) # degree sequence print("Degree sequence %s" % degree_sequence) print("Degree histogram") hist={} for d in degree_sequence: if d in hist: hist[d]+=1 else: hist[d]=1 print("degree #nodes") for d in hist: print('%d %d' % (d,hist[d]))
#!/usr/bin/env python """ Random graph from given degree sequence. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $" __credits__ = """""" __revision__ = "$Revision: 503 $" # Copyright (C) 2004 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. from networkx import * z=[5,3,3,3,3,2,2,2,1,1,1] print is_valid_degree_sequence(z) print("Configuration model") G=configuration_model(z) # configuration model degree_sequence=list(degree(G).values()) # degree sequence print("Degree sequence %s" % degree_sequence) print("Degree histogram") hist={} for d in degree_sequence: if d in hist: hist[d]+=1 else: hist[d]=1 print("degree #nodes") for d in hist: print('%d %d' % (d,hist[d])) Remove Python 3 incompatible print statement#!/usr/bin/env python """ Random graph from given degree sequence. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $" __credits__ = """""" __revision__ = "$Revision: 503 $" # Copyright (C) 2004 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. from networkx import * z=[5,3,3,3,3,2,2,2,1,1,1] print(is_valid_degree_sequence(z)) print("Configuration model") G=configuration_model(z) # configuration model degree_sequence=list(degree(G).values()) # degree sequence print("Degree sequence %s" % degree_sequence) print("Degree histogram") hist={} for d in degree_sequence: if d in hist: hist[d]+=1 else: hist[d]=1 print("degree #nodes") for d in hist: print('%d %d' % (d,hist[d]))
<commit_before>#!/usr/bin/env python """ Random graph from given degree sequence. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $" __credits__ = """""" __revision__ = "$Revision: 503 $" # Copyright (C) 2004 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. from networkx import * z=[5,3,3,3,3,2,2,2,1,1,1] print is_valid_degree_sequence(z) print("Configuration model") G=configuration_model(z) # configuration model degree_sequence=list(degree(G).values()) # degree sequence print("Degree sequence %s" % degree_sequence) print("Degree histogram") hist={} for d in degree_sequence: if d in hist: hist[d]+=1 else: hist[d]=1 print("degree #nodes") for d in hist: print('%d %d' % (d,hist[d])) <commit_msg>Remove Python 3 incompatible print statement<commit_after>#!/usr/bin/env python """ Random graph from given degree sequence. """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" __date__ = "$Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004) $" __credits__ = """""" __revision__ = "$Revision: 503 $" # Copyright (C) 2004 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. from networkx import * z=[5,3,3,3,3,2,2,2,1,1,1] print(is_valid_degree_sequence(z)) print("Configuration model") G=configuration_model(z) # configuration model degree_sequence=list(degree(G).values()) # degree sequence print("Degree sequence %s" % degree_sequence) print("Degree histogram") hist={} for d in degree_sequence: if d in hist: hist[d]+=1 else: hist[d]=1 print("degree #nodes") for d in hist: print('%d %d' % (d,hist[d]))
c79a3d368b1727b02e97600b17ac3da28a2107b4
project/apps/forum/serializers.py
project/apps/forum/serializers.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from machina.core.db.models import get_model from rest_framework import serializers Forum = get_model('forum', 'Forum') class ForumSerializer(serializers.ModelSerializer): description = serializers.SerializerMethodField() previous_sibling = serializers.SerializerMethodField() next_sibling = serializers.SerializerMethodField() class Meta: model = Forum fields = [ 'id', 'name', 'slug', 'type', 'description', 'image', 'link', 'link_redirects', 'posts_count', 'topics_count', 'link_redirects_count', 'last_post_on', 'display_sub_forum_list', 'lft', 'rght', 'tree_id', 'level', 'parent', 'previous_sibling', 'next_sibling', ] def get_description(self, obj): return obj.description.rendered def get_previous_sibling(self, obj): sibling = obj.get_previous_sibling() return sibling.pk if sibling else None def get_next_sibling(self, obj): sibling = obj.get_next_sibling() return sibling.pk if sibling else None
# -*- coding: utf-8 -*- from __future__ import unicode_literals from machina.core.db.models import get_model from rest_framework import serializers Forum = get_model('forum', 'Forum') class ForumSerializer(serializers.ModelSerializer): description = serializers.SerializerMethodField() class Meta: model = Forum fields = [ 'id', 'name', 'slug', 'type', 'description', 'image', 'link', 'link_redirects', 'posts_count', 'topics_count', 'link_redirects_count', 'last_post_on', 'display_sub_forum_list', 'lft', 'rght', 'tree_id', 'level', 'parent', ] def get_description(self, obj): return obj.description.rendered
Remove forum siblings from forum serializer
Remove forum siblings from forum serializer
Python
mit
ellmetha/machina-singlepageapp,ellmetha/machina-singlepageapp
# -*- coding: utf-8 -*- from __future__ import unicode_literals from machina.core.db.models import get_model from rest_framework import serializers Forum = get_model('forum', 'Forum') class ForumSerializer(serializers.ModelSerializer): description = serializers.SerializerMethodField() previous_sibling = serializers.SerializerMethodField() next_sibling = serializers.SerializerMethodField() class Meta: model = Forum fields = [ 'id', 'name', 'slug', 'type', 'description', 'image', 'link', 'link_redirects', 'posts_count', 'topics_count', 'link_redirects_count', 'last_post_on', 'display_sub_forum_list', 'lft', 'rght', 'tree_id', 'level', 'parent', 'previous_sibling', 'next_sibling', ] def get_description(self, obj): return obj.description.rendered def get_previous_sibling(self, obj): sibling = obj.get_previous_sibling() return sibling.pk if sibling else None def get_next_sibling(self, obj): sibling = obj.get_next_sibling() return sibling.pk if sibling else None Remove forum siblings from forum serializer
# -*- coding: utf-8 -*- from __future__ import unicode_literals from machina.core.db.models import get_model from rest_framework import serializers Forum = get_model('forum', 'Forum') class ForumSerializer(serializers.ModelSerializer): description = serializers.SerializerMethodField() class Meta: model = Forum fields = [ 'id', 'name', 'slug', 'type', 'description', 'image', 'link', 'link_redirects', 'posts_count', 'topics_count', 'link_redirects_count', 'last_post_on', 'display_sub_forum_list', 'lft', 'rght', 'tree_id', 'level', 'parent', ] def get_description(self, obj): return obj.description.rendered
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from machina.core.db.models import get_model from rest_framework import serializers Forum = get_model('forum', 'Forum') class ForumSerializer(serializers.ModelSerializer): description = serializers.SerializerMethodField() previous_sibling = serializers.SerializerMethodField() next_sibling = serializers.SerializerMethodField() class Meta: model = Forum fields = [ 'id', 'name', 'slug', 'type', 'description', 'image', 'link', 'link_redirects', 'posts_count', 'topics_count', 'link_redirects_count', 'last_post_on', 'display_sub_forum_list', 'lft', 'rght', 'tree_id', 'level', 'parent', 'previous_sibling', 'next_sibling', ] def get_description(self, obj): return obj.description.rendered def get_previous_sibling(self, obj): sibling = obj.get_previous_sibling() return sibling.pk if sibling else None def get_next_sibling(self, obj): sibling = obj.get_next_sibling() return sibling.pk if sibling else None <commit_msg>Remove forum siblings from forum serializer<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from machina.core.db.models import get_model from rest_framework import serializers Forum = get_model('forum', 'Forum') class ForumSerializer(serializers.ModelSerializer): description = serializers.SerializerMethodField() class Meta: model = Forum fields = [ 'id', 'name', 'slug', 'type', 'description', 'image', 'link', 'link_redirects', 'posts_count', 'topics_count', 'link_redirects_count', 'last_post_on', 'display_sub_forum_list', 'lft', 'rght', 'tree_id', 'level', 'parent', ] def get_description(self, obj): return obj.description.rendered
# -*- coding: utf-8 -*- from __future__ import unicode_literals from machina.core.db.models import get_model from rest_framework import serializers Forum = get_model('forum', 'Forum') class ForumSerializer(serializers.ModelSerializer): description = serializers.SerializerMethodField() previous_sibling = serializers.SerializerMethodField() next_sibling = serializers.SerializerMethodField() class Meta: model = Forum fields = [ 'id', 'name', 'slug', 'type', 'description', 'image', 'link', 'link_redirects', 'posts_count', 'topics_count', 'link_redirects_count', 'last_post_on', 'display_sub_forum_list', 'lft', 'rght', 'tree_id', 'level', 'parent', 'previous_sibling', 'next_sibling', ] def get_description(self, obj): return obj.description.rendered def get_previous_sibling(self, obj): sibling = obj.get_previous_sibling() return sibling.pk if sibling else None def get_next_sibling(self, obj): sibling = obj.get_next_sibling() return sibling.pk if sibling else None Remove forum siblings from forum serializer# -*- coding: utf-8 -*- from __future__ import unicode_literals from machina.core.db.models import get_model from rest_framework import serializers Forum = get_model('forum', 'Forum') class ForumSerializer(serializers.ModelSerializer): description = serializers.SerializerMethodField() class Meta: model = Forum fields = [ 'id', 'name', 'slug', 'type', 'description', 'image', 'link', 'link_redirects', 'posts_count', 'topics_count', 'link_redirects_count', 'last_post_on', 'display_sub_forum_list', 'lft', 'rght', 'tree_id', 'level', 'parent', ] def get_description(self, obj): return obj.description.rendered
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from machina.core.db.models import get_model from rest_framework import serializers Forum = get_model('forum', 'Forum') class ForumSerializer(serializers.ModelSerializer): description = serializers.SerializerMethodField() previous_sibling = serializers.SerializerMethodField() next_sibling = serializers.SerializerMethodField() class Meta: model = Forum fields = [ 'id', 'name', 'slug', 'type', 'description', 'image', 'link', 'link_redirects', 'posts_count', 'topics_count', 'link_redirects_count', 'last_post_on', 'display_sub_forum_list', 'lft', 'rght', 'tree_id', 'level', 'parent', 'previous_sibling', 'next_sibling', ] def get_description(self, obj): return obj.description.rendered def get_previous_sibling(self, obj): sibling = obj.get_previous_sibling() return sibling.pk if sibling else None def get_next_sibling(self, obj): sibling = obj.get_next_sibling() return sibling.pk if sibling else None <commit_msg>Remove forum siblings from forum serializer<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from machina.core.db.models import get_model from rest_framework import serializers Forum = get_model('forum', 'Forum') class ForumSerializer(serializers.ModelSerializer): description = serializers.SerializerMethodField() class Meta: model = Forum fields = [ 'id', 'name', 'slug', 'type', 'description', 'image', 'link', 'link_redirects', 'posts_count', 'topics_count', 'link_redirects_count', 'last_post_on', 'display_sub_forum_list', 'lft', 'rght', 'tree_id', 'level', 'parent', ] def get_description(self, obj): return obj.description.rendered
0242e64799ebd992b5bec715da956b00e1bddccd
examples/load_ui_base_instance.py
examples/load_ui_base_instance.py
import sys import os os.environ["QT_PREFERRED_BINDING"] = "PySide" from Qt import QtWidgets, load_ui def setup_ui(uifile, base_instance=None): ui = load_ui(uifile) if not base_instance: return ui else: for member in dir(ui): if not member.startswith('__') and \ member is not 'staticMetaObject': setattr(base_instance, member, getattr(ui, member)) return ui class MainWindow(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) setup_ui('examples/load_ui_qwidget.ui', self) def test_load_ui_setup_ui_wrapper(): """Example: load_ui with setup_ui wrapper """ app = QtWidgets.QApplication(sys.argv) window = MainWindow() # Tests assert isinstance(window.__class__, type(QtWidgets.QWidget)) assert isinstance(window.parent(), type(None)) assert isinstance(window.lineEdit.__class__, type(QtWidgets.QWidget)) assert window.lineEdit.text() == '' window.lineEdit.setText('Hello') assert window.lineEdit.text() == 'Hello' app.exit()
import sys import os # Set preferred binding # os.environ["QT_PREFERRED_BINDING"] = "PySide" from Qt import QtWidgets, load_ui def setup_ui(uifile, base_instance=None): ui = load_ui(uifile) if not base_instance: return ui else: for member in dir(ui): if not member.startswith('__') and \ member is not 'staticMetaObject': setattr(base_instance, member, getattr(ui, member)) return ui class MainWindow(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) setup_ui('examples/load_ui_qwidget.ui', self) def test_load_ui_setup_ui_wrapper(): """Example: load_ui with setup_ui wrapper """ app = QtWidgets.QApplication(sys.argv) window = MainWindow() # Tests assert isinstance(window.__class__, QtWidgets.QWidget.__class__) assert isinstance(window.parent(), type(None)) assert isinstance(window.lineEdit.__class__, QtWidgets.QWidget.__class__) assert window.lineEdit.text() == '' window.lineEdit.setText('Hello') assert window.lineEdit.text() == 'Hello' app.exit()
Remove preffered binding, use obj.__class__ instead of type()
Remove preffered binding, use obj.__class__ instead of type()
Python
mit
mottosso/Qt.py,mottosso/Qt.py,fredrikaverpil/Qt.py,fredrikaverpil/Qt.py
import sys import os os.environ["QT_PREFERRED_BINDING"] = "PySide" from Qt import QtWidgets, load_ui def setup_ui(uifile, base_instance=None): ui = load_ui(uifile) if not base_instance: return ui else: for member in dir(ui): if not member.startswith('__') and \ member is not 'staticMetaObject': setattr(base_instance, member, getattr(ui, member)) return ui class MainWindow(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) setup_ui('examples/load_ui_qwidget.ui', self) def test_load_ui_setup_ui_wrapper(): """Example: load_ui with setup_ui wrapper """ app = QtWidgets.QApplication(sys.argv) window = MainWindow() # Tests assert isinstance(window.__class__, type(QtWidgets.QWidget)) assert isinstance(window.parent(), type(None)) assert isinstance(window.lineEdit.__class__, type(QtWidgets.QWidget)) assert window.lineEdit.text() == '' window.lineEdit.setText('Hello') assert window.lineEdit.text() == 'Hello' app.exit() Remove preffered binding, use obj.__class__ instead of type()
import sys import os # Set preferred binding # os.environ["QT_PREFERRED_BINDING"] = "PySide" from Qt import QtWidgets, load_ui def setup_ui(uifile, base_instance=None): ui = load_ui(uifile) if not base_instance: return ui else: for member in dir(ui): if not member.startswith('__') and \ member is not 'staticMetaObject': setattr(base_instance, member, getattr(ui, member)) return ui class MainWindow(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) setup_ui('examples/load_ui_qwidget.ui', self) def test_load_ui_setup_ui_wrapper(): """Example: load_ui with setup_ui wrapper """ app = QtWidgets.QApplication(sys.argv) window = MainWindow() # Tests assert isinstance(window.__class__, QtWidgets.QWidget.__class__) assert isinstance(window.parent(), type(None)) assert isinstance(window.lineEdit.__class__, QtWidgets.QWidget.__class__) assert window.lineEdit.text() == '' window.lineEdit.setText('Hello') assert window.lineEdit.text() == 'Hello' app.exit()
<commit_before>import sys import os os.environ["QT_PREFERRED_BINDING"] = "PySide" from Qt import QtWidgets, load_ui def setup_ui(uifile, base_instance=None): ui = load_ui(uifile) if not base_instance: return ui else: for member in dir(ui): if not member.startswith('__') and \ member is not 'staticMetaObject': setattr(base_instance, member, getattr(ui, member)) return ui class MainWindow(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) setup_ui('examples/load_ui_qwidget.ui', self) def test_load_ui_setup_ui_wrapper(): """Example: load_ui with setup_ui wrapper """ app = QtWidgets.QApplication(sys.argv) window = MainWindow() # Tests assert isinstance(window.__class__, type(QtWidgets.QWidget)) assert isinstance(window.parent(), type(None)) assert isinstance(window.lineEdit.__class__, type(QtWidgets.QWidget)) assert window.lineEdit.text() == '' window.lineEdit.setText('Hello') assert window.lineEdit.text() == 'Hello' app.exit() <commit_msg>Remove preffered binding, use obj.__class__ instead of type()<commit_after>
import sys import os # Set preferred binding # os.environ["QT_PREFERRED_BINDING"] = "PySide" from Qt import QtWidgets, load_ui def setup_ui(uifile, base_instance=None): ui = load_ui(uifile) if not base_instance: return ui else: for member in dir(ui): if not member.startswith('__') and \ member is not 'staticMetaObject': setattr(base_instance, member, getattr(ui, member)) return ui class MainWindow(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) setup_ui('examples/load_ui_qwidget.ui', self) def test_load_ui_setup_ui_wrapper(): """Example: load_ui with setup_ui wrapper """ app = QtWidgets.QApplication(sys.argv) window = MainWindow() # Tests assert isinstance(window.__class__, QtWidgets.QWidget.__class__) assert isinstance(window.parent(), type(None)) assert isinstance(window.lineEdit.__class__, QtWidgets.QWidget.__class__) assert window.lineEdit.text() == '' window.lineEdit.setText('Hello') assert window.lineEdit.text() == 'Hello' app.exit()
import sys import os os.environ["QT_PREFERRED_BINDING"] = "PySide" from Qt import QtWidgets, load_ui def setup_ui(uifile, base_instance=None): ui = load_ui(uifile) if not base_instance: return ui else: for member in dir(ui): if not member.startswith('__') and \ member is not 'staticMetaObject': setattr(base_instance, member, getattr(ui, member)) return ui class MainWindow(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) setup_ui('examples/load_ui_qwidget.ui', self) def test_load_ui_setup_ui_wrapper(): """Example: load_ui with setup_ui wrapper """ app = QtWidgets.QApplication(sys.argv) window = MainWindow() # Tests assert isinstance(window.__class__, type(QtWidgets.QWidget)) assert isinstance(window.parent(), type(None)) assert isinstance(window.lineEdit.__class__, type(QtWidgets.QWidget)) assert window.lineEdit.text() == '' window.lineEdit.setText('Hello') assert window.lineEdit.text() == 'Hello' app.exit() Remove preffered binding, use obj.__class__ instead of type()import sys import os # Set preferred binding # os.environ["QT_PREFERRED_BINDING"] = "PySide" from Qt import QtWidgets, load_ui def setup_ui(uifile, base_instance=None): ui = load_ui(uifile) if not base_instance: return ui else: for member in dir(ui): if not member.startswith('__') and \ member is not 'staticMetaObject': setattr(base_instance, member, getattr(ui, member)) return ui class MainWindow(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) setup_ui('examples/load_ui_qwidget.ui', self) def test_load_ui_setup_ui_wrapper(): """Example: load_ui with setup_ui wrapper """ app = QtWidgets.QApplication(sys.argv) window = MainWindow() # Tests assert isinstance(window.__class__, QtWidgets.QWidget.__class__) assert isinstance(window.parent(), type(None)) assert isinstance(window.lineEdit.__class__, QtWidgets.QWidget.__class__) assert window.lineEdit.text() == '' window.lineEdit.setText('Hello') assert window.lineEdit.text() == 'Hello' app.exit()
<commit_before>import sys import os os.environ["QT_PREFERRED_BINDING"] = "PySide" from Qt import QtWidgets, load_ui def setup_ui(uifile, base_instance=None): ui = load_ui(uifile) if not base_instance: return ui else: for member in dir(ui): if not member.startswith('__') and \ member is not 'staticMetaObject': setattr(base_instance, member, getattr(ui, member)) return ui class MainWindow(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) setup_ui('examples/load_ui_qwidget.ui', self) def test_load_ui_setup_ui_wrapper(): """Example: load_ui with setup_ui wrapper """ app = QtWidgets.QApplication(sys.argv) window = MainWindow() # Tests assert isinstance(window.__class__, type(QtWidgets.QWidget)) assert isinstance(window.parent(), type(None)) assert isinstance(window.lineEdit.__class__, type(QtWidgets.QWidget)) assert window.lineEdit.text() == '' window.lineEdit.setText('Hello') assert window.lineEdit.text() == 'Hello' app.exit() <commit_msg>Remove preffered binding, use obj.__class__ instead of type()<commit_after>import sys import os # Set preferred binding # os.environ["QT_PREFERRED_BINDING"] = "PySide" from Qt import QtWidgets, load_ui def setup_ui(uifile, base_instance=None): ui = load_ui(uifile) if not base_instance: return ui else: for member in dir(ui): if not member.startswith('__') and \ member is not 'staticMetaObject': setattr(base_instance, member, getattr(ui, member)) return ui class MainWindow(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) setup_ui('examples/load_ui_qwidget.ui', self) def test_load_ui_setup_ui_wrapper(): """Example: load_ui with setup_ui wrapper """ app = QtWidgets.QApplication(sys.argv) window = MainWindow() # Tests assert isinstance(window.__class__, QtWidgets.QWidget.__class__) assert isinstance(window.parent(), type(None)) assert isinstance(window.lineEdit.__class__, QtWidgets.QWidget.__class__) assert window.lineEdit.text() == '' window.lineEdit.setText('Hello') assert window.lineEdit.text() == 'Hello' app.exit()
8258848f42142a9b539e3674e3cdaae2ffac09a1
app/main/views/root.py
app/main/views/root.py
import os import markdown import yaml from flask import render_template, render_template_string, session from .. import main from application import application @main.route('/', methods=['GET']) def root(): return render_template('index.html') @main.route('/patterns/') @main.route('/patterns/<pattern>') def patterns(pattern = 'index'): sections = [] pattern_name = 'grid-system' if (pattern == 'index') else pattern for root, dirs, files in os.walk('app/templates/patterns/components'): for file in files: if file.endswith('.html'): with open(os.path.join(root, file), 'r') as f: title = file.replace('.html', '') sections.append({ 'title': title, 'current': True if (title == pattern) else False }) return render_template('patterns/index.html', sections=sections, pattern_include='patterns/components/' + pattern_name + '.html', title=pattern)
import os import markdown import yaml from flask import render_template, render_template_string, session from .. import main from application import application @main.route('/', methods=['GET']) def root(): return render_template('index.html') @main.route('/patterns/') @main.route('/patterns/<pattern>') def patterns(pattern='index'): sections = [] pattern_name = 'grid-system' if (pattern == 'index') else pattern for root, dirs, files in os.walk('app/templates/patterns/components'): for file in files: if file.endswith('.html'): with open(os.path.join(root, file), 'r') as f: title = file.replace('.html', '') sections.append({ 'title': title, 'current': True if (title == pattern) else False }) return render_template('patterns/index.html', sections=sections, pattern_include='patterns/components/' + pattern_name + '.html', title=pattern)
Fix to pass python linter, this slipped through as the master branch wasnt protected
Fix to pass python linter, this slipped through as the master branch wasnt protected
Python
mit
ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner
import os import markdown import yaml from flask import render_template, render_template_string, session from .. import main from application import application @main.route('/', methods=['GET']) def root(): return render_template('index.html') @main.route('/patterns/') @main.route('/patterns/<pattern>') def patterns(pattern = 'index'): sections = [] pattern_name = 'grid-system' if (pattern == 'index') else pattern for root, dirs, files in os.walk('app/templates/patterns/components'): for file in files: if file.endswith('.html'): with open(os.path.join(root, file), 'r') as f: title = file.replace('.html', '') sections.append({ 'title': title, 'current': True if (title == pattern) else False }) return render_template('patterns/index.html', sections=sections, pattern_include='patterns/components/' + pattern_name + '.html', title=pattern) Fix to pass python linter, this slipped through as the master branch wasnt protected
import os import markdown import yaml from flask import render_template, render_template_string, session from .. import main from application import application @main.route('/', methods=['GET']) def root(): return render_template('index.html') @main.route('/patterns/') @main.route('/patterns/<pattern>') def patterns(pattern='index'): sections = [] pattern_name = 'grid-system' if (pattern == 'index') else pattern for root, dirs, files in os.walk('app/templates/patterns/components'): for file in files: if file.endswith('.html'): with open(os.path.join(root, file), 'r') as f: title = file.replace('.html', '') sections.append({ 'title': title, 'current': True if (title == pattern) else False }) return render_template('patterns/index.html', sections=sections, pattern_include='patterns/components/' + pattern_name + '.html', title=pattern)
<commit_before>import os import markdown import yaml from flask import render_template, render_template_string, session from .. import main from application import application @main.route('/', methods=['GET']) def root(): return render_template('index.html') @main.route('/patterns/') @main.route('/patterns/<pattern>') def patterns(pattern = 'index'): sections = [] pattern_name = 'grid-system' if (pattern == 'index') else pattern for root, dirs, files in os.walk('app/templates/patterns/components'): for file in files: if file.endswith('.html'): with open(os.path.join(root, file), 'r') as f: title = file.replace('.html', '') sections.append({ 'title': title, 'current': True if (title == pattern) else False }) return render_template('patterns/index.html', sections=sections, pattern_include='patterns/components/' + pattern_name + '.html', title=pattern) <commit_msg>Fix to pass python linter, this slipped through as the master branch wasnt protected<commit_after>
import os import markdown import yaml from flask import render_template, render_template_string, session from .. import main from application import application @main.route('/', methods=['GET']) def root(): return render_template('index.html') @main.route('/patterns/') @main.route('/patterns/<pattern>') def patterns(pattern='index'): sections = [] pattern_name = 'grid-system' if (pattern == 'index') else pattern for root, dirs, files in os.walk('app/templates/patterns/components'): for file in files: if file.endswith('.html'): with open(os.path.join(root, file), 'r') as f: title = file.replace('.html', '') sections.append({ 'title': title, 'current': True if (title == pattern) else False }) return render_template('patterns/index.html', sections=sections, pattern_include='patterns/components/' + pattern_name + '.html', title=pattern)
import os import markdown import yaml from flask import render_template, render_template_string, session from .. import main from application import application @main.route('/', methods=['GET']) def root(): return render_template('index.html') @main.route('/patterns/') @main.route('/patterns/<pattern>') def patterns(pattern = 'index'): sections = [] pattern_name = 'grid-system' if (pattern == 'index') else pattern for root, dirs, files in os.walk('app/templates/patterns/components'): for file in files: if file.endswith('.html'): with open(os.path.join(root, file), 'r') as f: title = file.replace('.html', '') sections.append({ 'title': title, 'current': True if (title == pattern) else False }) return render_template('patterns/index.html', sections=sections, pattern_include='patterns/components/' + pattern_name + '.html', title=pattern) Fix to pass python linter, this slipped through as the master branch wasnt protectedimport os import markdown import yaml from flask import render_template, render_template_string, session from .. import main from application import application @main.route('/', methods=['GET']) def root(): return render_template('index.html') @main.route('/patterns/') @main.route('/patterns/<pattern>') def patterns(pattern='index'): sections = [] pattern_name = 'grid-system' if (pattern == 'index') else pattern for root, dirs, files in os.walk('app/templates/patterns/components'): for file in files: if file.endswith('.html'): with open(os.path.join(root, file), 'r') as f: title = file.replace('.html', '') sections.append({ 'title': title, 'current': True if (title == pattern) else False }) return render_template('patterns/index.html', sections=sections, pattern_include='patterns/components/' + pattern_name + '.html', title=pattern)
<commit_before>import os import markdown import yaml from flask import render_template, render_template_string, session from .. import main from application import application @main.route('/', methods=['GET']) def root(): return render_template('index.html') @main.route('/patterns/') @main.route('/patterns/<pattern>') def patterns(pattern = 'index'): sections = [] pattern_name = 'grid-system' if (pattern == 'index') else pattern for root, dirs, files in os.walk('app/templates/patterns/components'): for file in files: if file.endswith('.html'): with open(os.path.join(root, file), 'r') as f: title = file.replace('.html', '') sections.append({ 'title': title, 'current': True if (title == pattern) else False }) return render_template('patterns/index.html', sections=sections, pattern_include='patterns/components/' + pattern_name + '.html', title=pattern) <commit_msg>Fix to pass python linter, this slipped through as the master branch wasnt protected<commit_after>import os import markdown import yaml from flask import render_template, render_template_string, session from .. import main from application import application @main.route('/', methods=['GET']) def root(): return render_template('index.html') @main.route('/patterns/') @main.route('/patterns/<pattern>') def patterns(pattern='index'): sections = [] pattern_name = 'grid-system' if (pattern == 'index') else pattern for root, dirs, files in os.walk('app/templates/patterns/components'): for file in files: if file.endswith('.html'): with open(os.path.join(root, file), 'r') as f: title = file.replace('.html', '') sections.append({ 'title': title, 'current': True if (title == pattern) else False }) return render_template('patterns/index.html', sections=sections, pattern_include='patterns/components/' + pattern_name + '.html', title=pattern)
7447d0df2034d0113582ba1aae09cf7388430432
sqlitebiter/_enum.py
sqlitebiter/_enum.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from enum import Enum class Context(Enum): DUP_DATABASE = 1 CONVERT_CONFIG = 5 INDEX_LIST = 10 ADD_PRIMARY_KEY_NAME = 15 TYPE_INFERENCE = 19 TYPE_HINT_HEADER = 20 LOG_LEVEL = 30 OUTPUT_PATH = 40 VERBOSITY_LEVEL = 50 SYMBOL_REPLACE_VALUE = 60 class ExitCode(object): SUCCESS = 0 FAILED_LOADER_NOT_FOUND = 1 FAILED_CONVERT = 2 FAILED_HTTP = 3 NO_INPUT = 10 class DupDatabase(Enum): OVERWRITE = 1 APPEND = 2 SKIP = 3 # TODO
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from enum import Enum, unique @unique class Context(Enum): DUP_DATABASE = 1 CONVERT_CONFIG = 5 INDEX_LIST = 10 ADD_PRIMARY_KEY_NAME = 15 TYPE_INFERENCE = 19 TYPE_HINT_HEADER = 20 LOG_LEVEL = 30 OUTPUT_PATH = 40 VERBOSITY_LEVEL = 50 SYMBOL_REPLACE_VALUE = 60 class ExitCode(object): SUCCESS = 0 FAILED_LOADER_NOT_FOUND = 1 FAILED_CONVERT = 2 FAILED_HTTP = 3 NO_INPUT = 10 @unique class DupDatabase(Enum): OVERWRITE = 1 APPEND = 2 SKIP = 3 # TODO
Add unique constraints to Enum definitions
Add unique constraints to Enum definitions
Python
mit
thombashi/sqlitebiter,thombashi/sqlitebiter
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from enum import Enum class Context(Enum): DUP_DATABASE = 1 CONVERT_CONFIG = 5 INDEX_LIST = 10 ADD_PRIMARY_KEY_NAME = 15 TYPE_INFERENCE = 19 TYPE_HINT_HEADER = 20 LOG_LEVEL = 30 OUTPUT_PATH = 40 VERBOSITY_LEVEL = 50 SYMBOL_REPLACE_VALUE = 60 class ExitCode(object): SUCCESS = 0 FAILED_LOADER_NOT_FOUND = 1 FAILED_CONVERT = 2 FAILED_HTTP = 3 NO_INPUT = 10 class DupDatabase(Enum): OVERWRITE = 1 APPEND = 2 SKIP = 3 # TODO Add unique constraints to Enum definitions
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from enum import Enum, unique @unique class Context(Enum): DUP_DATABASE = 1 CONVERT_CONFIG = 5 INDEX_LIST = 10 ADD_PRIMARY_KEY_NAME = 15 TYPE_INFERENCE = 19 TYPE_HINT_HEADER = 20 LOG_LEVEL = 30 OUTPUT_PATH = 40 VERBOSITY_LEVEL = 50 SYMBOL_REPLACE_VALUE = 60 class ExitCode(object): SUCCESS = 0 FAILED_LOADER_NOT_FOUND = 1 FAILED_CONVERT = 2 FAILED_HTTP = 3 NO_INPUT = 10 @unique class DupDatabase(Enum): OVERWRITE = 1 APPEND = 2 SKIP = 3 # TODO
<commit_before># encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from enum import Enum class Context(Enum): DUP_DATABASE = 1 CONVERT_CONFIG = 5 INDEX_LIST = 10 ADD_PRIMARY_KEY_NAME = 15 TYPE_INFERENCE = 19 TYPE_HINT_HEADER = 20 LOG_LEVEL = 30 OUTPUT_PATH = 40 VERBOSITY_LEVEL = 50 SYMBOL_REPLACE_VALUE = 60 class ExitCode(object): SUCCESS = 0 FAILED_LOADER_NOT_FOUND = 1 FAILED_CONVERT = 2 FAILED_HTTP = 3 NO_INPUT = 10 class DupDatabase(Enum): OVERWRITE = 1 APPEND = 2 SKIP = 3 # TODO <commit_msg>Add unique constraints to Enum definitions<commit_after>
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from enum import Enum, unique @unique class Context(Enum): DUP_DATABASE = 1 CONVERT_CONFIG = 5 INDEX_LIST = 10 ADD_PRIMARY_KEY_NAME = 15 TYPE_INFERENCE = 19 TYPE_HINT_HEADER = 20 LOG_LEVEL = 30 OUTPUT_PATH = 40 VERBOSITY_LEVEL = 50 SYMBOL_REPLACE_VALUE = 60 class ExitCode(object): SUCCESS = 0 FAILED_LOADER_NOT_FOUND = 1 FAILED_CONVERT = 2 FAILED_HTTP = 3 NO_INPUT = 10 @unique class DupDatabase(Enum): OVERWRITE = 1 APPEND = 2 SKIP = 3 # TODO
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from enum import Enum class Context(Enum): DUP_DATABASE = 1 CONVERT_CONFIG = 5 INDEX_LIST = 10 ADD_PRIMARY_KEY_NAME = 15 TYPE_INFERENCE = 19 TYPE_HINT_HEADER = 20 LOG_LEVEL = 30 OUTPUT_PATH = 40 VERBOSITY_LEVEL = 50 SYMBOL_REPLACE_VALUE = 60 class ExitCode(object): SUCCESS = 0 FAILED_LOADER_NOT_FOUND = 1 FAILED_CONVERT = 2 FAILED_HTTP = 3 NO_INPUT = 10 class DupDatabase(Enum): OVERWRITE = 1 APPEND = 2 SKIP = 3 # TODO Add unique constraints to Enum definitions# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from enum import Enum, unique @unique class Context(Enum): DUP_DATABASE = 1 CONVERT_CONFIG = 5 INDEX_LIST = 10 ADD_PRIMARY_KEY_NAME = 15 TYPE_INFERENCE = 19 TYPE_HINT_HEADER = 20 LOG_LEVEL = 30 OUTPUT_PATH = 40 VERBOSITY_LEVEL = 50 SYMBOL_REPLACE_VALUE = 60 class ExitCode(object): SUCCESS = 0 FAILED_LOADER_NOT_FOUND = 1 FAILED_CONVERT = 2 FAILED_HTTP = 3 NO_INPUT = 10 @unique class DupDatabase(Enum): OVERWRITE = 1 APPEND = 2 SKIP = 3 # TODO
<commit_before># encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from enum import Enum class Context(Enum): DUP_DATABASE = 1 CONVERT_CONFIG = 5 INDEX_LIST = 10 ADD_PRIMARY_KEY_NAME = 15 TYPE_INFERENCE = 19 TYPE_HINT_HEADER = 20 LOG_LEVEL = 30 OUTPUT_PATH = 40 VERBOSITY_LEVEL = 50 SYMBOL_REPLACE_VALUE = 60 class ExitCode(object): SUCCESS = 0 FAILED_LOADER_NOT_FOUND = 1 FAILED_CONVERT = 2 FAILED_HTTP = 3 NO_INPUT = 10 class DupDatabase(Enum): OVERWRITE = 1 APPEND = 2 SKIP = 3 # TODO <commit_msg>Add unique constraints to Enum definitions<commit_after># encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from enum import Enum, unique @unique class Context(Enum): DUP_DATABASE = 1 CONVERT_CONFIG = 5 INDEX_LIST = 10 ADD_PRIMARY_KEY_NAME = 15 TYPE_INFERENCE = 19 TYPE_HINT_HEADER = 20 LOG_LEVEL = 30 OUTPUT_PATH = 40 VERBOSITY_LEVEL = 50 SYMBOL_REPLACE_VALUE = 60 class ExitCode(object): SUCCESS = 0 FAILED_LOADER_NOT_FOUND = 1 FAILED_CONVERT = 2 FAILED_HTTP = 3 NO_INPUT = 10 @unique class DupDatabase(Enum): OVERWRITE = 1 APPEND = 2 SKIP = 3 # TODO
cda667a247ece3f389b8aef22bb7e348ad4cfba6
hp3parclient/__init__.py
hp3parclient/__init__.py
# Copyright 2012-2014 Hewlett Packard Development Company, L.P. # 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. """ HP 3PAR Client :Author: Walter A. Boring IV :Author: Kurt Martin :Copyright: Copyright 2012-2014, Hewlett Packard Development Company, L.P. :License: Apache v2.0 """ version_tuple = (2, 9, 0) def get_version_string(): if isinstance(version_tuple[-1], str): return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1] return '.'.join(map(str, version_tuple)) version = get_version_string() """Current version of HP3PARClient."""
# Copyright 2012-2014 Hewlett Packard Development Company, L.P. # 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. """ HP 3PAR Client :Author: Walter A. Boring IV :Author: Kurt Martin :Copyright: Copyright 2012-2014, Hewlett Packard Development Company, L.P. :License: Apache v2.0 """ version_tuple = (3, 0, 0) def get_version_string(): if isinstance(version_tuple[-1], str): return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1] return '.'.join(map(str, version_tuple)) version = get_version_string() """Current version of HP3PARClient."""
Update the version to 3.0.0
Update the version to 3.0.0
Python
apache-2.0
hpe-storage/python-3parclient,hp-storage/python-3parclient
# Copyright 2012-2014 Hewlett Packard Development Company, L.P. # 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. """ HP 3PAR Client :Author: Walter A. Boring IV :Author: Kurt Martin :Copyright: Copyright 2012-2014, Hewlett Packard Development Company, L.P. :License: Apache v2.0 """ version_tuple = (2, 9, 0) def get_version_string(): if isinstance(version_tuple[-1], str): return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1] return '.'.join(map(str, version_tuple)) version = get_version_string() """Current version of HP3PARClient.""" Update the version to 3.0.0
# Copyright 2012-2014 Hewlett Packard Development Company, L.P. # 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. """ HP 3PAR Client :Author: Walter A. Boring IV :Author: Kurt Martin :Copyright: Copyright 2012-2014, Hewlett Packard Development Company, L.P. :License: Apache v2.0 """ version_tuple = (3, 0, 0) def get_version_string(): if isinstance(version_tuple[-1], str): return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1] return '.'.join(map(str, version_tuple)) version = get_version_string() """Current version of HP3PARClient."""
<commit_before># Copyright 2012-2014 Hewlett Packard Development Company, L.P. # 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. """ HP 3PAR Client :Author: Walter A. Boring IV :Author: Kurt Martin :Copyright: Copyright 2012-2014, Hewlett Packard Development Company, L.P. :License: Apache v2.0 """ version_tuple = (2, 9, 0) def get_version_string(): if isinstance(version_tuple[-1], str): return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1] return '.'.join(map(str, version_tuple)) version = get_version_string() """Current version of HP3PARClient.""" <commit_msg>Update the version to 3.0.0<commit_after>
# Copyright 2012-2014 Hewlett Packard Development Company, L.P. # 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. """ HP 3PAR Client :Author: Walter A. Boring IV :Author: Kurt Martin :Copyright: Copyright 2012-2014, Hewlett Packard Development Company, L.P. :License: Apache v2.0 """ version_tuple = (3, 0, 0) def get_version_string(): if isinstance(version_tuple[-1], str): return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1] return '.'.join(map(str, version_tuple)) version = get_version_string() """Current version of HP3PARClient."""
# Copyright 2012-2014 Hewlett Packard Development Company, L.P. # 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. """ HP 3PAR Client :Author: Walter A. Boring IV :Author: Kurt Martin :Copyright: Copyright 2012-2014, Hewlett Packard Development Company, L.P. :License: Apache v2.0 """ version_tuple = (2, 9, 0) def get_version_string(): if isinstance(version_tuple[-1], str): return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1] return '.'.join(map(str, version_tuple)) version = get_version_string() """Current version of HP3PARClient.""" Update the version to 3.0.0# Copyright 2012-2014 Hewlett Packard Development Company, L.P. # 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. """ HP 3PAR Client :Author: Walter A. Boring IV :Author: Kurt Martin :Copyright: Copyright 2012-2014, Hewlett Packard Development Company, L.P. :License: Apache v2.0 """ version_tuple = (3, 0, 0) def get_version_string(): if isinstance(version_tuple[-1], str): return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1] return '.'.join(map(str, version_tuple)) version = get_version_string() """Current version of HP3PARClient."""
<commit_before># Copyright 2012-2014 Hewlett Packard Development Company, L.P. # 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. """ HP 3PAR Client :Author: Walter A. Boring IV :Author: Kurt Martin :Copyright: Copyright 2012-2014, Hewlett Packard Development Company, L.P. :License: Apache v2.0 """ version_tuple = (2, 9, 0) def get_version_string(): if isinstance(version_tuple[-1], str): return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1] return '.'.join(map(str, version_tuple)) version = get_version_string() """Current version of HP3PARClient.""" <commit_msg>Update the version to 3.0.0<commit_after># Copyright 2012-2014 Hewlett Packard Development Company, L.P. # 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. """ HP 3PAR Client :Author: Walter A. Boring IV :Author: Kurt Martin :Copyright: Copyright 2012-2014, Hewlett Packard Development Company, L.P. :License: Apache v2.0 """ version_tuple = (3, 0, 0) def get_version_string(): if isinstance(version_tuple[-1], str): return '.'.join(map(str, version_tuple[:-1])) + version_tuple[-1] return '.'.join(map(str, version_tuple)) version = get_version_string() """Current version of HP3PARClient."""
054c283d1cdccdf8277acc96435672480587f6b9
devicehive/api_subscribe_request.py
devicehive/api_subscribe_request.py
class ApiSubscribeRequest(object): """Api request class.""" def __init__(self): self._action = None self._request = {} self._params = {'method': 'GET', 'url': None, 'params': {}, 'headers': {}, 'response_key': None} def action(self, action): self._action = action def set(self, key, value): if not value: return self._request[key] = value def method(self, method): self._params['method'] = method def url(self, url, **args): for key in args: value = args[key] url = url.replace('{%s}' % key, str(value)) self._params['url'] = url def param(self, key, value): if not value: return self._params['params'][key] = value def header(self, name, value): self._params['headers'][name] = value def response_key(self, response_key): self._params['response_key'] = response_key def extract(self): return self._action, self._request, self._params
class ApiSubscribeRequest(object): """Api request class.""" def __init__(self): self._action = None self._request = {} self._params = {'method': 'GET', 'url': None, 'params': {}, 'headers': {}, 'response_key': None, 'params_timestamp_key': 'timestamp', 'response_timestamp_key': 'timestamp'} def action(self, action): self._action = action def set(self, key, value): if not value: return self._request[key] = value def method(self, method): self._params['method'] = method def url(self, url, **args): for key in args: value = args[key] url = url.replace('{%s}' % key, str(value)) self._params['url'] = url def param(self, key, value): if not value: return self._params['params'][key] = value def header(self, name, value): self._params['headers'][name] = value def response_key(self, response_key): self._params['response_key'] = response_key def params_timestamp_key(self, params_timestamp_key): self._params['params_timestamp_key'] = params_timestamp_key def response_timestamp_key(self, response_timestamp_key): self._params['response_timestamp_key'] = response_timestamp_key def extract(self): return self._action, self._request, self._params
Add params_timestamp_key and response_timestamp_key methods
Add params_timestamp_key and response_timestamp_key methods
Python
apache-2.0
devicehive/devicehive-python
class ApiSubscribeRequest(object): """Api request class.""" def __init__(self): self._action = None self._request = {} self._params = {'method': 'GET', 'url': None, 'params': {}, 'headers': {}, 'response_key': None} def action(self, action): self._action = action def set(self, key, value): if not value: return self._request[key] = value def method(self, method): self._params['method'] = method def url(self, url, **args): for key in args: value = args[key] url = url.replace('{%s}' % key, str(value)) self._params['url'] = url def param(self, key, value): if not value: return self._params['params'][key] = value def header(self, name, value): self._params['headers'][name] = value def response_key(self, response_key): self._params['response_key'] = response_key def extract(self): return self._action, self._request, self._params Add params_timestamp_key and response_timestamp_key methods
class ApiSubscribeRequest(object): """Api request class.""" def __init__(self): self._action = None self._request = {} self._params = {'method': 'GET', 'url': None, 'params': {}, 'headers': {}, 'response_key': None, 'params_timestamp_key': 'timestamp', 'response_timestamp_key': 'timestamp'} def action(self, action): self._action = action def set(self, key, value): if not value: return self._request[key] = value def method(self, method): self._params['method'] = method def url(self, url, **args): for key in args: value = args[key] url = url.replace('{%s}' % key, str(value)) self._params['url'] = url def param(self, key, value): if not value: return self._params['params'][key] = value def header(self, name, value): self._params['headers'][name] = value def response_key(self, response_key): self._params['response_key'] = response_key def params_timestamp_key(self, params_timestamp_key): self._params['params_timestamp_key'] = params_timestamp_key def response_timestamp_key(self, response_timestamp_key): self._params['response_timestamp_key'] = response_timestamp_key def extract(self): return self._action, self._request, self._params
<commit_before>class ApiSubscribeRequest(object): """Api request class.""" def __init__(self): self._action = None self._request = {} self._params = {'method': 'GET', 'url': None, 'params': {}, 'headers': {}, 'response_key': None} def action(self, action): self._action = action def set(self, key, value): if not value: return self._request[key] = value def method(self, method): self._params['method'] = method def url(self, url, **args): for key in args: value = args[key] url = url.replace('{%s}' % key, str(value)) self._params['url'] = url def param(self, key, value): if not value: return self._params['params'][key] = value def header(self, name, value): self._params['headers'][name] = value def response_key(self, response_key): self._params['response_key'] = response_key def extract(self): return self._action, self._request, self._params <commit_msg>Add params_timestamp_key and response_timestamp_key methods<commit_after>
class ApiSubscribeRequest(object): """Api request class.""" def __init__(self): self._action = None self._request = {} self._params = {'method': 'GET', 'url': None, 'params': {}, 'headers': {}, 'response_key': None, 'params_timestamp_key': 'timestamp', 'response_timestamp_key': 'timestamp'} def action(self, action): self._action = action def set(self, key, value): if not value: return self._request[key] = value def method(self, method): self._params['method'] = method def url(self, url, **args): for key in args: value = args[key] url = url.replace('{%s}' % key, str(value)) self._params['url'] = url def param(self, key, value): if not value: return self._params['params'][key] = value def header(self, name, value): self._params['headers'][name] = value def response_key(self, response_key): self._params['response_key'] = response_key def params_timestamp_key(self, params_timestamp_key): self._params['params_timestamp_key'] = params_timestamp_key def response_timestamp_key(self, response_timestamp_key): self._params['response_timestamp_key'] = response_timestamp_key def extract(self): return self._action, self._request, self._params
class ApiSubscribeRequest(object): """Api request class.""" def __init__(self): self._action = None self._request = {} self._params = {'method': 'GET', 'url': None, 'params': {}, 'headers': {}, 'response_key': None} def action(self, action): self._action = action def set(self, key, value): if not value: return self._request[key] = value def method(self, method): self._params['method'] = method def url(self, url, **args): for key in args: value = args[key] url = url.replace('{%s}' % key, str(value)) self._params['url'] = url def param(self, key, value): if not value: return self._params['params'][key] = value def header(self, name, value): self._params['headers'][name] = value def response_key(self, response_key): self._params['response_key'] = response_key def extract(self): return self._action, self._request, self._params Add params_timestamp_key and response_timestamp_key methodsclass ApiSubscribeRequest(object): """Api request class.""" def __init__(self): self._action = None self._request = {} self._params = {'method': 'GET', 'url': None, 'params': {}, 'headers': {}, 'response_key': None, 'params_timestamp_key': 'timestamp', 'response_timestamp_key': 'timestamp'} def action(self, action): self._action = action def set(self, key, value): if not value: return self._request[key] = value def method(self, method): self._params['method'] = method def url(self, url, **args): for key in args: value = args[key] url = url.replace('{%s}' % key, str(value)) self._params['url'] = url def param(self, key, value): if not value: return self._params['params'][key] = value def header(self, name, value): self._params['headers'][name] = value def response_key(self, response_key): self._params['response_key'] = response_key def params_timestamp_key(self, params_timestamp_key): self._params['params_timestamp_key'] = params_timestamp_key def response_timestamp_key(self, response_timestamp_key): self._params['response_timestamp_key'] = response_timestamp_key def extract(self): return self._action, self._request, self._params
<commit_before>class ApiSubscribeRequest(object): """Api request class.""" def __init__(self): self._action = None self._request = {} self._params = {'method': 'GET', 'url': None, 'params': {}, 'headers': {}, 'response_key': None} def action(self, action): self._action = action def set(self, key, value): if not value: return self._request[key] = value def method(self, method): self._params['method'] = method def url(self, url, **args): for key in args: value = args[key] url = url.replace('{%s}' % key, str(value)) self._params['url'] = url def param(self, key, value): if not value: return self._params['params'][key] = value def header(self, name, value): self._params['headers'][name] = value def response_key(self, response_key): self._params['response_key'] = response_key def extract(self): return self._action, self._request, self._params <commit_msg>Add params_timestamp_key and response_timestamp_key methods<commit_after>class ApiSubscribeRequest(object): """Api request class.""" def __init__(self): self._action = None self._request = {} self._params = {'method': 'GET', 'url': None, 'params': {}, 'headers': {}, 'response_key': None, 'params_timestamp_key': 'timestamp', 'response_timestamp_key': 'timestamp'} def action(self, action): self._action = action def set(self, key, value): if not value: return self._request[key] = value def method(self, method): self._params['method'] = method def url(self, url, **args): for key in args: value = args[key] url = url.replace('{%s}' % key, str(value)) self._params['url'] = url def param(self, key, value): if not value: return self._params['params'][key] = value def header(self, name, value): self._params['headers'][name] = value def response_key(self, response_key): self._params['response_key'] = response_key def params_timestamp_key(self, params_timestamp_key): self._params['params_timestamp_key'] = params_timestamp_key def response_timestamp_key(self, response_timestamp_key): self._params['response_timestamp_key'] = response_timestamp_key def extract(self): return self._action, self._request, self._params
c730184a6ec826f9773fa4130e59121c0fd06e4d
api_v3/misc/oauth2.py
api_v3/misc/oauth2.py
from urlparse import urljoin from django.conf import settings import jwt from social_core.backends.oauth import BaseOAuth2 class KeycloakOAuth2(BaseOAuth2): """Keycloak OAuth authentication backend""" name = 'keycloak' ID_KEY = 'email' BASE_URL = settings.SOCIAL_AUTH_KEYCLOAK_BASE USERINFO_URL = urljoin(BASE_URL, 'protocol/openid-connect/userinfo') AUTHORIZATION_URL = urljoin(BASE_URL, 'protocol/openid-connect/auth') ACCESS_TOKEN_URL = urljoin(BASE_URL, 'protocol/openid-connect/token') ACCESS_TOKEN_METHOD = 'POST' def get_user_details(self, response): clients = response.get('resource_access', {}) client = clients.get(settings.SOCIAL_AUTH_KEYCLOAK_KEY, {}) roles = set(client.get('roles', [])) return { 'username': response.get('preferred_username'), 'email': response.get('email'), 'first_name': response.get('given_name'), 'last_name': response.get('family_name'), 'is_staff': 'staff' in roles, 'is_superuser': 'superuser' in roles, } def user_data(self, access_token, *args, **kwargs): return jwt.decode(access_token, verify=False) def activate_user(backend, user, response, *args, **kwargs): user.is_active = True user.save()
from urlparse import urljoin from django.conf import settings import jwt from social_core.backends.oauth import BaseOAuth2 class KeycloakOAuth2(BaseOAuth2): """Keycloak OAuth authentication backend""" name = 'keycloak' ID_KEY = 'email' BASE_URL = settings.SOCIAL_AUTH_KEYCLOAK_BASE USERINFO_URL = urljoin(BASE_URL, 'protocol/openid-connect/userinfo') AUTHORIZATION_URL = urljoin(BASE_URL, 'protocol/openid-connect/auth') ACCESS_TOKEN_URL = urljoin(BASE_URL, 'protocol/openid-connect/token') ACCESS_TOKEN_METHOD = 'POST' def get_user_details(self, response): clients = response.get('resource_access', {}) client = clients.get(settings.SOCIAL_AUTH_KEYCLOAK_KEY, {}) roles = set(client.get('roles', [])) return { 'email': response.get('email'), 'first_name': response.get('given_name'), 'last_name': response.get('family_name'), 'is_staff': 'staff' in roles, 'is_superuser': 'superuser' in roles, } def user_data(self, access_token, *args, **kwargs): return jwt.decode(access_token, verify=False) def activate_user(backend, user, response, *args, **kwargs): user.is_active = True user.save()
Remove `username` from keycloack payload.
Remove `username` from keycloack payload.
Python
mit
occrp/id-backend
from urlparse import urljoin from django.conf import settings import jwt from social_core.backends.oauth import BaseOAuth2 class KeycloakOAuth2(BaseOAuth2): """Keycloak OAuth authentication backend""" name = 'keycloak' ID_KEY = 'email' BASE_URL = settings.SOCIAL_AUTH_KEYCLOAK_BASE USERINFO_URL = urljoin(BASE_URL, 'protocol/openid-connect/userinfo') AUTHORIZATION_URL = urljoin(BASE_URL, 'protocol/openid-connect/auth') ACCESS_TOKEN_URL = urljoin(BASE_URL, 'protocol/openid-connect/token') ACCESS_TOKEN_METHOD = 'POST' def get_user_details(self, response): clients = response.get('resource_access', {}) client = clients.get(settings.SOCIAL_AUTH_KEYCLOAK_KEY, {}) roles = set(client.get('roles', [])) return { 'username': response.get('preferred_username'), 'email': response.get('email'), 'first_name': response.get('given_name'), 'last_name': response.get('family_name'), 'is_staff': 'staff' in roles, 'is_superuser': 'superuser' in roles, } def user_data(self, access_token, *args, **kwargs): return jwt.decode(access_token, verify=False) def activate_user(backend, user, response, *args, **kwargs): user.is_active = True user.save() Remove `username` from keycloack payload.
from urlparse import urljoin from django.conf import settings import jwt from social_core.backends.oauth import BaseOAuth2 class KeycloakOAuth2(BaseOAuth2): """Keycloak OAuth authentication backend""" name = 'keycloak' ID_KEY = 'email' BASE_URL = settings.SOCIAL_AUTH_KEYCLOAK_BASE USERINFO_URL = urljoin(BASE_URL, 'protocol/openid-connect/userinfo') AUTHORIZATION_URL = urljoin(BASE_URL, 'protocol/openid-connect/auth') ACCESS_TOKEN_URL = urljoin(BASE_URL, 'protocol/openid-connect/token') ACCESS_TOKEN_METHOD = 'POST' def get_user_details(self, response): clients = response.get('resource_access', {}) client = clients.get(settings.SOCIAL_AUTH_KEYCLOAK_KEY, {}) roles = set(client.get('roles', [])) return { 'email': response.get('email'), 'first_name': response.get('given_name'), 'last_name': response.get('family_name'), 'is_staff': 'staff' in roles, 'is_superuser': 'superuser' in roles, } def user_data(self, access_token, *args, **kwargs): return jwt.decode(access_token, verify=False) def activate_user(backend, user, response, *args, **kwargs): user.is_active = True user.save()
<commit_before>from urlparse import urljoin from django.conf import settings import jwt from social_core.backends.oauth import BaseOAuth2 class KeycloakOAuth2(BaseOAuth2): """Keycloak OAuth authentication backend""" name = 'keycloak' ID_KEY = 'email' BASE_URL = settings.SOCIAL_AUTH_KEYCLOAK_BASE USERINFO_URL = urljoin(BASE_URL, 'protocol/openid-connect/userinfo') AUTHORIZATION_URL = urljoin(BASE_URL, 'protocol/openid-connect/auth') ACCESS_TOKEN_URL = urljoin(BASE_URL, 'protocol/openid-connect/token') ACCESS_TOKEN_METHOD = 'POST' def get_user_details(self, response): clients = response.get('resource_access', {}) client = clients.get(settings.SOCIAL_AUTH_KEYCLOAK_KEY, {}) roles = set(client.get('roles', [])) return { 'username': response.get('preferred_username'), 'email': response.get('email'), 'first_name': response.get('given_name'), 'last_name': response.get('family_name'), 'is_staff': 'staff' in roles, 'is_superuser': 'superuser' in roles, } def user_data(self, access_token, *args, **kwargs): return jwt.decode(access_token, verify=False) def activate_user(backend, user, response, *args, **kwargs): user.is_active = True user.save() <commit_msg>Remove `username` from keycloack payload.<commit_after>
from urlparse import urljoin from django.conf import settings import jwt from social_core.backends.oauth import BaseOAuth2 class KeycloakOAuth2(BaseOAuth2): """Keycloak OAuth authentication backend""" name = 'keycloak' ID_KEY = 'email' BASE_URL = settings.SOCIAL_AUTH_KEYCLOAK_BASE USERINFO_URL = urljoin(BASE_URL, 'protocol/openid-connect/userinfo') AUTHORIZATION_URL = urljoin(BASE_URL, 'protocol/openid-connect/auth') ACCESS_TOKEN_URL = urljoin(BASE_URL, 'protocol/openid-connect/token') ACCESS_TOKEN_METHOD = 'POST' def get_user_details(self, response): clients = response.get('resource_access', {}) client = clients.get(settings.SOCIAL_AUTH_KEYCLOAK_KEY, {}) roles = set(client.get('roles', [])) return { 'email': response.get('email'), 'first_name': response.get('given_name'), 'last_name': response.get('family_name'), 'is_staff': 'staff' in roles, 'is_superuser': 'superuser' in roles, } def user_data(self, access_token, *args, **kwargs): return jwt.decode(access_token, verify=False) def activate_user(backend, user, response, *args, **kwargs): user.is_active = True user.save()
from urlparse import urljoin from django.conf import settings import jwt from social_core.backends.oauth import BaseOAuth2 class KeycloakOAuth2(BaseOAuth2): """Keycloak OAuth authentication backend""" name = 'keycloak' ID_KEY = 'email' BASE_URL = settings.SOCIAL_AUTH_KEYCLOAK_BASE USERINFO_URL = urljoin(BASE_URL, 'protocol/openid-connect/userinfo') AUTHORIZATION_URL = urljoin(BASE_URL, 'protocol/openid-connect/auth') ACCESS_TOKEN_URL = urljoin(BASE_URL, 'protocol/openid-connect/token') ACCESS_TOKEN_METHOD = 'POST' def get_user_details(self, response): clients = response.get('resource_access', {}) client = clients.get(settings.SOCIAL_AUTH_KEYCLOAK_KEY, {}) roles = set(client.get('roles', [])) return { 'username': response.get('preferred_username'), 'email': response.get('email'), 'first_name': response.get('given_name'), 'last_name': response.get('family_name'), 'is_staff': 'staff' in roles, 'is_superuser': 'superuser' in roles, } def user_data(self, access_token, *args, **kwargs): return jwt.decode(access_token, verify=False) def activate_user(backend, user, response, *args, **kwargs): user.is_active = True user.save() Remove `username` from keycloack payload.from urlparse import urljoin from django.conf import settings import jwt from social_core.backends.oauth import BaseOAuth2 class KeycloakOAuth2(BaseOAuth2): """Keycloak OAuth authentication backend""" name = 'keycloak' ID_KEY = 'email' BASE_URL = settings.SOCIAL_AUTH_KEYCLOAK_BASE USERINFO_URL = urljoin(BASE_URL, 'protocol/openid-connect/userinfo') AUTHORIZATION_URL = urljoin(BASE_URL, 'protocol/openid-connect/auth') ACCESS_TOKEN_URL = urljoin(BASE_URL, 'protocol/openid-connect/token') ACCESS_TOKEN_METHOD = 'POST' def get_user_details(self, response): clients = response.get('resource_access', {}) client = clients.get(settings.SOCIAL_AUTH_KEYCLOAK_KEY, {}) roles = set(client.get('roles', [])) return { 'email': response.get('email'), 'first_name': response.get('given_name'), 'last_name': response.get('family_name'), 'is_staff': 'staff' in roles, 'is_superuser': 'superuser' in roles, } def user_data(self, access_token, *args, **kwargs): return jwt.decode(access_token, verify=False) def activate_user(backend, user, response, *args, **kwargs): user.is_active = True user.save()
<commit_before>from urlparse import urljoin from django.conf import settings import jwt from social_core.backends.oauth import BaseOAuth2 class KeycloakOAuth2(BaseOAuth2): """Keycloak OAuth authentication backend""" name = 'keycloak' ID_KEY = 'email' BASE_URL = settings.SOCIAL_AUTH_KEYCLOAK_BASE USERINFO_URL = urljoin(BASE_URL, 'protocol/openid-connect/userinfo') AUTHORIZATION_URL = urljoin(BASE_URL, 'protocol/openid-connect/auth') ACCESS_TOKEN_URL = urljoin(BASE_URL, 'protocol/openid-connect/token') ACCESS_TOKEN_METHOD = 'POST' def get_user_details(self, response): clients = response.get('resource_access', {}) client = clients.get(settings.SOCIAL_AUTH_KEYCLOAK_KEY, {}) roles = set(client.get('roles', [])) return { 'username': response.get('preferred_username'), 'email': response.get('email'), 'first_name': response.get('given_name'), 'last_name': response.get('family_name'), 'is_staff': 'staff' in roles, 'is_superuser': 'superuser' in roles, } def user_data(self, access_token, *args, **kwargs): return jwt.decode(access_token, verify=False) def activate_user(backend, user, response, *args, **kwargs): user.is_active = True user.save() <commit_msg>Remove `username` from keycloack payload.<commit_after>from urlparse import urljoin from django.conf import settings import jwt from social_core.backends.oauth import BaseOAuth2 class KeycloakOAuth2(BaseOAuth2): """Keycloak OAuth authentication backend""" name = 'keycloak' ID_KEY = 'email' BASE_URL = settings.SOCIAL_AUTH_KEYCLOAK_BASE USERINFO_URL = urljoin(BASE_URL, 'protocol/openid-connect/userinfo') AUTHORIZATION_URL = urljoin(BASE_URL, 'protocol/openid-connect/auth') ACCESS_TOKEN_URL = urljoin(BASE_URL, 'protocol/openid-connect/token') ACCESS_TOKEN_METHOD = 'POST' def get_user_details(self, response): clients = response.get('resource_access', {}) client = clients.get(settings.SOCIAL_AUTH_KEYCLOAK_KEY, {}) roles = set(client.get('roles', [])) return { 'email': response.get('email'), 'first_name': response.get('given_name'), 'last_name': response.get('family_name'), 'is_staff': 'staff' in roles, 'is_superuser': 'superuser' in roles, } def user_data(self, access_token, *args, **kwargs): return jwt.decode(access_token, verify=False) def activate_user(backend, user, response, *args, **kwargs): user.is_active = True user.save()
5208429f8e684d8604fe9a8a7eda3709ace0755c
bin/cros_repo_sync_all.py
bin/cros_repo_sync_all.py
#!/usr/bin/python # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Stop gap sync function until cbuildbot is integrated into all builders""" import cbuildbot import optparse import sys """Number of retries to retry repo sync before giving up""" _NUMBER_OF_RETRIES=3 def main(): parser = optparse.OptionParser() parser.add_option('-r', '--buildroot', help='root directory where sync occurs') parser.add_option('-c', '--clobber', action='store_true', default=False, help='clobber build directory and do a full checkout') (options, args) = parser.parse_args() if options.buildroot: if options.clobber: cbuildbot._FullCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: cbuildbot._IncrementalCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: print >>sys.stderr, 'ERROR: Must set buildroot' sys.exit(1) if __name__ == '__main__': main()
#!/usr/bin/python # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Stop gap sync function until cbuildbot is integrated into all builders""" import cbuildbot_comm import cbuildbot import optparse import sys """Number of retries to retry repo sync before giving up""" _NUMBER_OF_RETRIES=3 def main(): parser = optparse.OptionParser() parser.add_option('-r', '--buildroot', help='root directory where sync occurs') parser.add_option('-c', '--clobber', action='store_true', default=False, help='clobber build directory and do a full checkout') (options, args) = parser.parse_args() if options.buildroot: if options.clobber: cbuildbot._FullCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: cbuildbot._IncrementalCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: print >>sys.stderr, 'ERROR: Must set buildroot' sys.exit(1) if __name__ == '__main__': main()
Fix circ dep issue with cbuildbot
TBR: Fix circ dep issue with cbuildbot
Python
bsd-3-clause
sigma/coreos-scripts,smilart/scripts,nicescale/scripts,mjg59/scripts,crawford/scripts,coreos/scripts,bcwaldon/coreos-scripts,bcwaldon/coreos-scripts,endocode/scripts,zhang0137/scripts,zhang0137/scripts,mjg59/scripts,gtank/scripts,gtank/scripts,gtank/scripts,glevand/coreos--scripts,sigma/coreos-scripts,smilart/scripts,mischief/scripts,crawford/scripts,marineam/coreos-scripts,andrejro/coreos--scripts,mischief/scripts,marineam/coreos-scripts,trnubo/scripts,fivethreeo/scripts,smilart/scripts,vmware/coreos-scripts,nicescale/scripts,andrejro/coreos--scripts,BugRoger/scripts,endocode/scripts,BugRoger/scripts,vmware/coreos-scripts,vmware/coreos-scripts,trnubo/scripts,trnubo/scripts,coreos/scripts,bcwaldon/coreos-scripts,marineam/coreos-scripts,zhang0137/scripts,fivethreeo/scripts,BugRoger/scripts,mjg59/scripts,crawford/scripts,glevand/coreos--scripts,sigma/coreos-scripts,fivethreeo/scripts,andrejro/coreos--scripts,mischief/scripts,endocode/scripts,nicescale/scripts
#!/usr/bin/python # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Stop gap sync function until cbuildbot is integrated into all builders""" import cbuildbot import optparse import sys """Number of retries to retry repo sync before giving up""" _NUMBER_OF_RETRIES=3 def main(): parser = optparse.OptionParser() parser.add_option('-r', '--buildroot', help='root directory where sync occurs') parser.add_option('-c', '--clobber', action='store_true', default=False, help='clobber build directory and do a full checkout') (options, args) = parser.parse_args() if options.buildroot: if options.clobber: cbuildbot._FullCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: cbuildbot._IncrementalCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: print >>sys.stderr, 'ERROR: Must set buildroot' sys.exit(1) if __name__ == '__main__': main() TBR: Fix circ dep issue with cbuildbot
#!/usr/bin/python # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Stop gap sync function until cbuildbot is integrated into all builders""" import cbuildbot_comm import cbuildbot import optparse import sys """Number of retries to retry repo sync before giving up""" _NUMBER_OF_RETRIES=3 def main(): parser = optparse.OptionParser() parser.add_option('-r', '--buildroot', help='root directory where sync occurs') parser.add_option('-c', '--clobber', action='store_true', default=False, help='clobber build directory and do a full checkout') (options, args) = parser.parse_args() if options.buildroot: if options.clobber: cbuildbot._FullCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: cbuildbot._IncrementalCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: print >>sys.stderr, 'ERROR: Must set buildroot' sys.exit(1) if __name__ == '__main__': main()
<commit_before>#!/usr/bin/python # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Stop gap sync function until cbuildbot is integrated into all builders""" import cbuildbot import optparse import sys """Number of retries to retry repo sync before giving up""" _NUMBER_OF_RETRIES=3 def main(): parser = optparse.OptionParser() parser.add_option('-r', '--buildroot', help='root directory where sync occurs') parser.add_option('-c', '--clobber', action='store_true', default=False, help='clobber build directory and do a full checkout') (options, args) = parser.parse_args() if options.buildroot: if options.clobber: cbuildbot._FullCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: cbuildbot._IncrementalCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: print >>sys.stderr, 'ERROR: Must set buildroot' sys.exit(1) if __name__ == '__main__': main() <commit_msg>TBR: Fix circ dep issue with cbuildbot<commit_after>
#!/usr/bin/python # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Stop gap sync function until cbuildbot is integrated into all builders""" import cbuildbot_comm import cbuildbot import optparse import sys """Number of retries to retry repo sync before giving up""" _NUMBER_OF_RETRIES=3 def main(): parser = optparse.OptionParser() parser.add_option('-r', '--buildroot', help='root directory where sync occurs') parser.add_option('-c', '--clobber', action='store_true', default=False, help='clobber build directory and do a full checkout') (options, args) = parser.parse_args() if options.buildroot: if options.clobber: cbuildbot._FullCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: cbuildbot._IncrementalCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: print >>sys.stderr, 'ERROR: Must set buildroot' sys.exit(1) if __name__ == '__main__': main()
#!/usr/bin/python # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Stop gap sync function until cbuildbot is integrated into all builders""" import cbuildbot import optparse import sys """Number of retries to retry repo sync before giving up""" _NUMBER_OF_RETRIES=3 def main(): parser = optparse.OptionParser() parser.add_option('-r', '--buildroot', help='root directory where sync occurs') parser.add_option('-c', '--clobber', action='store_true', default=False, help='clobber build directory and do a full checkout') (options, args) = parser.parse_args() if options.buildroot: if options.clobber: cbuildbot._FullCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: cbuildbot._IncrementalCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: print >>sys.stderr, 'ERROR: Must set buildroot' sys.exit(1) if __name__ == '__main__': main() TBR: Fix circ dep issue with cbuildbot#!/usr/bin/python # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Stop gap sync function until cbuildbot is integrated into all builders""" import cbuildbot_comm import cbuildbot import optparse import sys """Number of retries to retry repo sync before giving up""" _NUMBER_OF_RETRIES=3 def main(): parser = optparse.OptionParser() parser.add_option('-r', '--buildroot', help='root directory where sync occurs') parser.add_option('-c', '--clobber', action='store_true', default=False, help='clobber build directory and do a full checkout') (options, args) = parser.parse_args() if options.buildroot: if options.clobber: cbuildbot._FullCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: cbuildbot._IncrementalCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: print >>sys.stderr, 'ERROR: Must set buildroot' sys.exit(1) if __name__ == '__main__': main()
<commit_before>#!/usr/bin/python # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Stop gap sync function until cbuildbot is integrated into all builders""" import cbuildbot import optparse import sys """Number of retries to retry repo sync before giving up""" _NUMBER_OF_RETRIES=3 def main(): parser = optparse.OptionParser() parser.add_option('-r', '--buildroot', help='root directory where sync occurs') parser.add_option('-c', '--clobber', action='store_true', default=False, help='clobber build directory and do a full checkout') (options, args) = parser.parse_args() if options.buildroot: if options.clobber: cbuildbot._FullCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: cbuildbot._IncrementalCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: print >>sys.stderr, 'ERROR: Must set buildroot' sys.exit(1) if __name__ == '__main__': main() <commit_msg>TBR: Fix circ dep issue with cbuildbot<commit_after>#!/usr/bin/python # Copyright (c) 2010 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Stop gap sync function until cbuildbot is integrated into all builders""" import cbuildbot_comm import cbuildbot import optparse import sys """Number of retries to retry repo sync before giving up""" _NUMBER_OF_RETRIES=3 def main(): parser = optparse.OptionParser() parser.add_option('-r', '--buildroot', help='root directory where sync occurs') parser.add_option('-c', '--clobber', action='store_true', default=False, help='clobber build directory and do a full checkout') (options, args) = parser.parse_args() if options.buildroot: if options.clobber: cbuildbot._FullCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: cbuildbot._IncrementalCheckout(options.buildroot, rw_checkout=False, retries=_NUMBER_OF_RETRIES) else: print >>sys.stderr, 'ERROR: Must set buildroot' sys.exit(1) if __name__ == '__main__': main()
1e7c53398e6a4a72d4027524622b32ee1819f154
zpr.py
zpr.py
#!bin/python import json import lib_zpr from flask import Flask, jsonify, make_response app = Flask(__name__) api_version = 'v1.0' api_base = str('/zpr/{v}'.format(v=api_version)) @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) # @app.route('/zpr/job') # def ls_test(): # return json.dumps(call('ls')) @app.route('{a}/job/<backup_host>'.format(a=api_base), methods=['GET']) def check_job(backup_host): job = str(lib_zpr.check_zpr_rsync_job(backup_host)) return json.dumps(job) @app.route('{a}/job/duplicity/<backup_host>'.format(a=api_base), methods=['GET']) def check_offsite_job(backup_host): lib_zpr.check_duplicity_job(backup_host, print_output=False) return json.dumps(str(lib_zpr.check_duplicity_out[0])) if __name__ == '__main__': app.run(debug=True)
#!bin/python import json import lib_zpr from flask import Flask, jsonify, make_response app = Flask(__name__) api_version = 'v1.0' api_base = str('/zpr/{v}'.format(v=api_version)) @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) # @app.route('/zpr/job') # def ls_test(): # return json.dumps(call('ls')) @app.route('{a}/job/<backup_host>'.format(a=api_base), methods=['GET']) def check_job(backup_host): job = str(lib_zpr.check_zpr_rsync_job(backup_host)) return json.dumps(job) @app.route('{a}/job/duplicity/<backup_host>'.format(a=api_base), methods=['GET']) def check_offsite_job(backup_host): lib_zpr.check_duplicity_job(backup_host, print_output=False) return json.dumps(str(lib_zpr.check_duplicity_out[0])) if __name__ == '__main__': app.run(host='127.0.0.1')
Add host and remove debug
Add host and remove debug
Python
apache-2.0
mattkirby/zpr-api
#!bin/python import json import lib_zpr from flask import Flask, jsonify, make_response app = Flask(__name__) api_version = 'v1.0' api_base = str('/zpr/{v}'.format(v=api_version)) @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) # @app.route('/zpr/job') # def ls_test(): # return json.dumps(call('ls')) @app.route('{a}/job/<backup_host>'.format(a=api_base), methods=['GET']) def check_job(backup_host): job = str(lib_zpr.check_zpr_rsync_job(backup_host)) return json.dumps(job) @app.route('{a}/job/duplicity/<backup_host>'.format(a=api_base), methods=['GET']) def check_offsite_job(backup_host): lib_zpr.check_duplicity_job(backup_host, print_output=False) return json.dumps(str(lib_zpr.check_duplicity_out[0])) if __name__ == '__main__': app.run(debug=True) Add host and remove debug
#!bin/python import json import lib_zpr from flask import Flask, jsonify, make_response app = Flask(__name__) api_version = 'v1.0' api_base = str('/zpr/{v}'.format(v=api_version)) @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) # @app.route('/zpr/job') # def ls_test(): # return json.dumps(call('ls')) @app.route('{a}/job/<backup_host>'.format(a=api_base), methods=['GET']) def check_job(backup_host): job = str(lib_zpr.check_zpr_rsync_job(backup_host)) return json.dumps(job) @app.route('{a}/job/duplicity/<backup_host>'.format(a=api_base), methods=['GET']) def check_offsite_job(backup_host): lib_zpr.check_duplicity_job(backup_host, print_output=False) return json.dumps(str(lib_zpr.check_duplicity_out[0])) if __name__ == '__main__': app.run(host='127.0.0.1')
<commit_before>#!bin/python import json import lib_zpr from flask import Flask, jsonify, make_response app = Flask(__name__) api_version = 'v1.0' api_base = str('/zpr/{v}'.format(v=api_version)) @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) # @app.route('/zpr/job') # def ls_test(): # return json.dumps(call('ls')) @app.route('{a}/job/<backup_host>'.format(a=api_base), methods=['GET']) def check_job(backup_host): job = str(lib_zpr.check_zpr_rsync_job(backup_host)) return json.dumps(job) @app.route('{a}/job/duplicity/<backup_host>'.format(a=api_base), methods=['GET']) def check_offsite_job(backup_host): lib_zpr.check_duplicity_job(backup_host, print_output=False) return json.dumps(str(lib_zpr.check_duplicity_out[0])) if __name__ == '__main__': app.run(debug=True) <commit_msg>Add host and remove debug<commit_after>
#!bin/python import json import lib_zpr from flask import Flask, jsonify, make_response app = Flask(__name__) api_version = 'v1.0' api_base = str('/zpr/{v}'.format(v=api_version)) @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) # @app.route('/zpr/job') # def ls_test(): # return json.dumps(call('ls')) @app.route('{a}/job/<backup_host>'.format(a=api_base), methods=['GET']) def check_job(backup_host): job = str(lib_zpr.check_zpr_rsync_job(backup_host)) return json.dumps(job) @app.route('{a}/job/duplicity/<backup_host>'.format(a=api_base), methods=['GET']) def check_offsite_job(backup_host): lib_zpr.check_duplicity_job(backup_host, print_output=False) return json.dumps(str(lib_zpr.check_duplicity_out[0])) if __name__ == '__main__': app.run(host='127.0.0.1')
#!bin/python import json import lib_zpr from flask import Flask, jsonify, make_response app = Flask(__name__) api_version = 'v1.0' api_base = str('/zpr/{v}'.format(v=api_version)) @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) # @app.route('/zpr/job') # def ls_test(): # return json.dumps(call('ls')) @app.route('{a}/job/<backup_host>'.format(a=api_base), methods=['GET']) def check_job(backup_host): job = str(lib_zpr.check_zpr_rsync_job(backup_host)) return json.dumps(job) @app.route('{a}/job/duplicity/<backup_host>'.format(a=api_base), methods=['GET']) def check_offsite_job(backup_host): lib_zpr.check_duplicity_job(backup_host, print_output=False) return json.dumps(str(lib_zpr.check_duplicity_out[0])) if __name__ == '__main__': app.run(debug=True) Add host and remove debug#!bin/python import json import lib_zpr from flask import Flask, jsonify, make_response app = Flask(__name__) api_version = 'v1.0' api_base = str('/zpr/{v}'.format(v=api_version)) @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) # @app.route('/zpr/job') # def ls_test(): # return json.dumps(call('ls')) @app.route('{a}/job/<backup_host>'.format(a=api_base), methods=['GET']) def check_job(backup_host): job = str(lib_zpr.check_zpr_rsync_job(backup_host)) return json.dumps(job) @app.route('{a}/job/duplicity/<backup_host>'.format(a=api_base), methods=['GET']) def check_offsite_job(backup_host): lib_zpr.check_duplicity_job(backup_host, print_output=False) return json.dumps(str(lib_zpr.check_duplicity_out[0])) if __name__ == '__main__': app.run(host='127.0.0.1')
<commit_before>#!bin/python import json import lib_zpr from flask import Flask, jsonify, make_response app = Flask(__name__) api_version = 'v1.0' api_base = str('/zpr/{v}'.format(v=api_version)) @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) # @app.route('/zpr/job') # def ls_test(): # return json.dumps(call('ls')) @app.route('{a}/job/<backup_host>'.format(a=api_base), methods=['GET']) def check_job(backup_host): job = str(lib_zpr.check_zpr_rsync_job(backup_host)) return json.dumps(job) @app.route('{a}/job/duplicity/<backup_host>'.format(a=api_base), methods=['GET']) def check_offsite_job(backup_host): lib_zpr.check_duplicity_job(backup_host, print_output=False) return json.dumps(str(lib_zpr.check_duplicity_out[0])) if __name__ == '__main__': app.run(debug=True) <commit_msg>Add host and remove debug<commit_after>#!bin/python import json import lib_zpr from flask import Flask, jsonify, make_response app = Flask(__name__) api_version = 'v1.0' api_base = str('/zpr/{v}'.format(v=api_version)) @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) # @app.route('/zpr/job') # def ls_test(): # return json.dumps(call('ls')) @app.route('{a}/job/<backup_host>'.format(a=api_base), methods=['GET']) def check_job(backup_host): job = str(lib_zpr.check_zpr_rsync_job(backup_host)) return json.dumps(job) @app.route('{a}/job/duplicity/<backup_host>'.format(a=api_base), methods=['GET']) def check_offsite_job(backup_host): lib_zpr.check_duplicity_job(backup_host, print_output=False) return json.dumps(str(lib_zpr.check_duplicity_out[0])) if __name__ == '__main__': app.run(host='127.0.0.1')
8605b07f2f5951f8a0b85d3d77baa1758723fb64
auth0/v2/authentication/users.py
auth0/v2/authentication/users.py
from .base import AuthenticationBase class Users(AuthenticationBase): def __init__(self, domain): self.domain = domain def userinfo(self, access_token): return self.get( url='https://%s/userinfo' % self.domain, headers={'Authorization': 'Bearer %s' % access_token} ) def tokeninfo(self, jwt): return self.post( url='https://%s/tokeninfo' % self.domain, data={'id_token': jwt}, headers={'Content-Type: application/json'} )
from .base import AuthenticationBase class Users(AuthenticationBase): """Userinfo related endpoints. Args: domain (str): Your auth0 domain (e.g: username.auth0.com) """ def __init__(self, domain): self.domain = domain def userinfo(self, access_token): """Returns the user information based on the Auth0 access token. Args: access_token (str): Auth0 access token (obtained during login). Returns: The user profile. """ return self.get( url='https://%s/userinfo' % self.domain, headers={'Authorization': 'Bearer %s' % access_token} ) def tokeninfo(self, jwt): """Returns user profile based on the user's jwt Validates a JSON Web Token (signature and expiration) and returns the user information associated with the user id (sub property) of the token. Args: jwt (str): User's jwt Returns: The user profile. """ return self.post( url='https://%s/tokeninfo' % self.domain, data={'id_token': jwt}, headers={'Content-Type: application/json'} )
Add docstrings to Users class
Add docstrings to Users class
Python
mit
auth0/auth0-python,auth0/auth0-python
from .base import AuthenticationBase class Users(AuthenticationBase): def __init__(self, domain): self.domain = domain def userinfo(self, access_token): return self.get( url='https://%s/userinfo' % self.domain, headers={'Authorization': 'Bearer %s' % access_token} ) def tokeninfo(self, jwt): return self.post( url='https://%s/tokeninfo' % self.domain, data={'id_token': jwt}, headers={'Content-Type: application/json'} ) Add docstrings to Users class
from .base import AuthenticationBase class Users(AuthenticationBase): """Userinfo related endpoints. Args: domain (str): Your auth0 domain (e.g: username.auth0.com) """ def __init__(self, domain): self.domain = domain def userinfo(self, access_token): """Returns the user information based on the Auth0 access token. Args: access_token (str): Auth0 access token (obtained during login). Returns: The user profile. """ return self.get( url='https://%s/userinfo' % self.domain, headers={'Authorization': 'Bearer %s' % access_token} ) def tokeninfo(self, jwt): """Returns user profile based on the user's jwt Validates a JSON Web Token (signature and expiration) and returns the user information associated with the user id (sub property) of the token. Args: jwt (str): User's jwt Returns: The user profile. """ return self.post( url='https://%s/tokeninfo' % self.domain, data={'id_token': jwt}, headers={'Content-Type: application/json'} )
<commit_before>from .base import AuthenticationBase class Users(AuthenticationBase): def __init__(self, domain): self.domain = domain def userinfo(self, access_token): return self.get( url='https://%s/userinfo' % self.domain, headers={'Authorization': 'Bearer %s' % access_token} ) def tokeninfo(self, jwt): return self.post( url='https://%s/tokeninfo' % self.domain, data={'id_token': jwt}, headers={'Content-Type: application/json'} ) <commit_msg>Add docstrings to Users class<commit_after>
from .base import AuthenticationBase class Users(AuthenticationBase): """Userinfo related endpoints. Args: domain (str): Your auth0 domain (e.g: username.auth0.com) """ def __init__(self, domain): self.domain = domain def userinfo(self, access_token): """Returns the user information based on the Auth0 access token. Args: access_token (str): Auth0 access token (obtained during login). Returns: The user profile. """ return self.get( url='https://%s/userinfo' % self.domain, headers={'Authorization': 'Bearer %s' % access_token} ) def tokeninfo(self, jwt): """Returns user profile based on the user's jwt Validates a JSON Web Token (signature and expiration) and returns the user information associated with the user id (sub property) of the token. Args: jwt (str): User's jwt Returns: The user profile. """ return self.post( url='https://%s/tokeninfo' % self.domain, data={'id_token': jwt}, headers={'Content-Type: application/json'} )
from .base import AuthenticationBase class Users(AuthenticationBase): def __init__(self, domain): self.domain = domain def userinfo(self, access_token): return self.get( url='https://%s/userinfo' % self.domain, headers={'Authorization': 'Bearer %s' % access_token} ) def tokeninfo(self, jwt): return self.post( url='https://%s/tokeninfo' % self.domain, data={'id_token': jwt}, headers={'Content-Type: application/json'} ) Add docstrings to Users classfrom .base import AuthenticationBase class Users(AuthenticationBase): """Userinfo related endpoints. Args: domain (str): Your auth0 domain (e.g: username.auth0.com) """ def __init__(self, domain): self.domain = domain def userinfo(self, access_token): """Returns the user information based on the Auth0 access token. Args: access_token (str): Auth0 access token (obtained during login). Returns: The user profile. """ return self.get( url='https://%s/userinfo' % self.domain, headers={'Authorization': 'Bearer %s' % access_token} ) def tokeninfo(self, jwt): """Returns user profile based on the user's jwt Validates a JSON Web Token (signature and expiration) and returns the user information associated with the user id (sub property) of the token. Args: jwt (str): User's jwt Returns: The user profile. """ return self.post( url='https://%s/tokeninfo' % self.domain, data={'id_token': jwt}, headers={'Content-Type: application/json'} )
<commit_before>from .base import AuthenticationBase class Users(AuthenticationBase): def __init__(self, domain): self.domain = domain def userinfo(self, access_token): return self.get( url='https://%s/userinfo' % self.domain, headers={'Authorization': 'Bearer %s' % access_token} ) def tokeninfo(self, jwt): return self.post( url='https://%s/tokeninfo' % self.domain, data={'id_token': jwt}, headers={'Content-Type: application/json'} ) <commit_msg>Add docstrings to Users class<commit_after>from .base import AuthenticationBase class Users(AuthenticationBase): """Userinfo related endpoints. Args: domain (str): Your auth0 domain (e.g: username.auth0.com) """ def __init__(self, domain): self.domain = domain def userinfo(self, access_token): """Returns the user information based on the Auth0 access token. Args: access_token (str): Auth0 access token (obtained during login). Returns: The user profile. """ return self.get( url='https://%s/userinfo' % self.domain, headers={'Authorization': 'Bearer %s' % access_token} ) def tokeninfo(self, jwt): """Returns user profile based on the user's jwt Validates a JSON Web Token (signature and expiration) and returns the user information associated with the user id (sub property) of the token. Args: jwt (str): User's jwt Returns: The user profile. """ return self.post( url='https://%s/tokeninfo' % self.domain, data={'id_token': jwt}, headers={'Content-Type: application/json'} )
67d08d61186f7d9bc0026c1d867039f58872fee7
main.py
main.py
import cmd import argparse from Interface import * class Lexeme(cmd.Cmd): intro = "Welcome to Lexeme! Input '?' for help and commands." prompt = "Enter command: " def do_list(self, arg): 'List word database.' listwords() def do_quit(self, arg): quit() def do_add(self, arg): add() def do_decline(self, arg): decline() def do_statistics(self, arg): statistics() def do_search(self, arg): search() def do_generate(self, arg): generate() def do_export(self, arg): export() def do_batch(self, arg): batchgenerate() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--database", help="set database file") parser.add_argument("--config", help="set configuration file") args = parser.parse_args() if args.database is not None: Library.loadDatabase(args.database) else: Library.loadDatabase() if args.config is not None: loadData(args.config) else: loadData() Lexeme().cmdloop()
import cmd import argparse from Interface import * class Lexeme(cmd.Cmd): intro = "Welcome to Lexeme! Input '?' for help and commands." prompt = "Enter command: " def do_list(self, arg): 'List word database.' listwords() def do_quit(self, arg): quit() def do_add(self, arg): add() def do_decline(self, arg): decline() def do_statistics(self, arg): statistics() def do_search(self, arg): search() def do_generate(self, arg): generate() def do_export(self, arg): export() def do_batch(self, arg): batchgenerate() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--database", help="set database file") parser.add_argument("--config", help="set configuration file") args = parser.parse_args() if args.database is not None: Library.loadDatabase(args.database) else: Library.loadDatabase() if args.config is not None: loadData(args.config) else: loadData() clearScreen() Lexeme().cmdloop()
Clear screen at start of program
Clear screen at start of program
Python
mit
kdelwat/Lexeme
import cmd import argparse from Interface import * class Lexeme(cmd.Cmd): intro = "Welcome to Lexeme! Input '?' for help and commands." prompt = "Enter command: " def do_list(self, arg): 'List word database.' listwords() def do_quit(self, arg): quit() def do_add(self, arg): add() def do_decline(self, arg): decline() def do_statistics(self, arg): statistics() def do_search(self, arg): search() def do_generate(self, arg): generate() def do_export(self, arg): export() def do_batch(self, arg): batchgenerate() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--database", help="set database file") parser.add_argument("--config", help="set configuration file") args = parser.parse_args() if args.database is not None: Library.loadDatabase(args.database) else: Library.loadDatabase() if args.config is not None: loadData(args.config) else: loadData() Lexeme().cmdloop() Clear screen at start of program
import cmd import argparse from Interface import * class Lexeme(cmd.Cmd): intro = "Welcome to Lexeme! Input '?' for help and commands." prompt = "Enter command: " def do_list(self, arg): 'List word database.' listwords() def do_quit(self, arg): quit() def do_add(self, arg): add() def do_decline(self, arg): decline() def do_statistics(self, arg): statistics() def do_search(self, arg): search() def do_generate(self, arg): generate() def do_export(self, arg): export() def do_batch(self, arg): batchgenerate() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--database", help="set database file") parser.add_argument("--config", help="set configuration file") args = parser.parse_args() if args.database is not None: Library.loadDatabase(args.database) else: Library.loadDatabase() if args.config is not None: loadData(args.config) else: loadData() clearScreen() Lexeme().cmdloop()
<commit_before>import cmd import argparse from Interface import * class Lexeme(cmd.Cmd): intro = "Welcome to Lexeme! Input '?' for help and commands." prompt = "Enter command: " def do_list(self, arg): 'List word database.' listwords() def do_quit(self, arg): quit() def do_add(self, arg): add() def do_decline(self, arg): decline() def do_statistics(self, arg): statistics() def do_search(self, arg): search() def do_generate(self, arg): generate() def do_export(self, arg): export() def do_batch(self, arg): batchgenerate() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--database", help="set database file") parser.add_argument("--config", help="set configuration file") args = parser.parse_args() if args.database is not None: Library.loadDatabase(args.database) else: Library.loadDatabase() if args.config is not None: loadData(args.config) else: loadData() Lexeme().cmdloop() <commit_msg>Clear screen at start of program<commit_after>
import cmd import argparse from Interface import * class Lexeme(cmd.Cmd): intro = "Welcome to Lexeme! Input '?' for help and commands." prompt = "Enter command: " def do_list(self, arg): 'List word database.' listwords() def do_quit(self, arg): quit() def do_add(self, arg): add() def do_decline(self, arg): decline() def do_statistics(self, arg): statistics() def do_search(self, arg): search() def do_generate(self, arg): generate() def do_export(self, arg): export() def do_batch(self, arg): batchgenerate() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--database", help="set database file") parser.add_argument("--config", help="set configuration file") args = parser.parse_args() if args.database is not None: Library.loadDatabase(args.database) else: Library.loadDatabase() if args.config is not None: loadData(args.config) else: loadData() clearScreen() Lexeme().cmdloop()
import cmd import argparse from Interface import * class Lexeme(cmd.Cmd): intro = "Welcome to Lexeme! Input '?' for help and commands." prompt = "Enter command: " def do_list(self, arg): 'List word database.' listwords() def do_quit(self, arg): quit() def do_add(self, arg): add() def do_decline(self, arg): decline() def do_statistics(self, arg): statistics() def do_search(self, arg): search() def do_generate(self, arg): generate() def do_export(self, arg): export() def do_batch(self, arg): batchgenerate() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--database", help="set database file") parser.add_argument("--config", help="set configuration file") args = parser.parse_args() if args.database is not None: Library.loadDatabase(args.database) else: Library.loadDatabase() if args.config is not None: loadData(args.config) else: loadData() Lexeme().cmdloop() Clear screen at start of programimport cmd import argparse from Interface import * class Lexeme(cmd.Cmd): intro = "Welcome to Lexeme! Input '?' for help and commands." prompt = "Enter command: " def do_list(self, arg): 'List word database.' listwords() def do_quit(self, arg): quit() def do_add(self, arg): add() def do_decline(self, arg): decline() def do_statistics(self, arg): statistics() def do_search(self, arg): search() def do_generate(self, arg): generate() def do_export(self, arg): export() def do_batch(self, arg): batchgenerate() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--database", help="set database file") parser.add_argument("--config", help="set configuration file") args = parser.parse_args() if args.database is not None: Library.loadDatabase(args.database) else: Library.loadDatabase() if args.config is not None: loadData(args.config) else: loadData() clearScreen() Lexeme().cmdloop()
<commit_before>import cmd import argparse from Interface import * class Lexeme(cmd.Cmd): intro = "Welcome to Lexeme! Input '?' for help and commands." prompt = "Enter command: " def do_list(self, arg): 'List word database.' listwords() def do_quit(self, arg): quit() def do_add(self, arg): add() def do_decline(self, arg): decline() def do_statistics(self, arg): statistics() def do_search(self, arg): search() def do_generate(self, arg): generate() def do_export(self, arg): export() def do_batch(self, arg): batchgenerate() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--database", help="set database file") parser.add_argument("--config", help="set configuration file") args = parser.parse_args() if args.database is not None: Library.loadDatabase(args.database) else: Library.loadDatabase() if args.config is not None: loadData(args.config) else: loadData() Lexeme().cmdloop() <commit_msg>Clear screen at start of program<commit_after>import cmd import argparse from Interface import * class Lexeme(cmd.Cmd): intro = "Welcome to Lexeme! Input '?' for help and commands." prompt = "Enter command: " def do_list(self, arg): 'List word database.' listwords() def do_quit(self, arg): quit() def do_add(self, arg): add() def do_decline(self, arg): decline() def do_statistics(self, arg): statistics() def do_search(self, arg): search() def do_generate(self, arg): generate() def do_export(self, arg): export() def do_batch(self, arg): batchgenerate() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--database", help="set database file") parser.add_argument("--config", help="set configuration file") args = parser.parse_args() if args.database is not None: Library.loadDatabase(args.database) else: Library.loadDatabase() if args.config is not None: loadData(args.config) else: loadData() clearScreen() Lexeme().cmdloop()
9e9b36836ab829c2bf8226e2836ec6f21b7905c3
main.py
main.py
# -*- coding: utf-8 -*- # flake8: noqa import views from flask import Flask from flask_themes2 import Themes import config from util.auth import is_admin from util.converter import RegexConverter from util.csrf import generate_csrf_token app = Flask(__name__.split('.')[0]) app.secret_key = config.SECRET_KEY app.url_map.converters['regex'] = RegexConverter app.jinja_env.globals['config'] = config app.jinja_env.globals['csrf_token'] = generate_csrf_token app.jinja_env.globals['is_admin'] = is_admin Themes(app, app_identifier='yelplove') # if debug property is present, let's use it try: app.debug = config.DEBUG except AttributeError: app.debug = False
# -*- coding: utf-8 -*- # flake8: noqa from flask import Flask from flask_themes2 import Themes import config from util.auth import is_admin from util.converter import RegexConverter from util.csrf import generate_csrf_token app = Flask(__name__.split('.')[0]) app.secret_key = config.SECRET_KEY app.url_map.converters['regex'] = RegexConverter app.jinja_env.globals['config'] = config app.jinja_env.globals['csrf_token'] = generate_csrf_token app.jinja_env.globals['is_admin'] = is_admin Themes(app, app_identifier='yelplove') # if debug property is present, let's use it try: app.debug = config.DEBUG except AttributeError: app.debug = False # This import needs to stay down here, otherwise we'll get ImportErrors when running tests import views # noqa
Fix ImportErrors when running tests, make sure pre-commit hooks still pass
Fix ImportErrors when running tests, make sure pre-commit hooks still pass
Python
mit
Yelp/love,Yelp/love,Yelp/love
# -*- coding: utf-8 -*- # flake8: noqa import views from flask import Flask from flask_themes2 import Themes import config from util.auth import is_admin from util.converter import RegexConverter from util.csrf import generate_csrf_token app = Flask(__name__.split('.')[0]) app.secret_key = config.SECRET_KEY app.url_map.converters['regex'] = RegexConverter app.jinja_env.globals['config'] = config app.jinja_env.globals['csrf_token'] = generate_csrf_token app.jinja_env.globals['is_admin'] = is_admin Themes(app, app_identifier='yelplove') # if debug property is present, let's use it try: app.debug = config.DEBUG except AttributeError: app.debug = False Fix ImportErrors when running tests, make sure pre-commit hooks still pass
# -*- coding: utf-8 -*- # flake8: noqa from flask import Flask from flask_themes2 import Themes import config from util.auth import is_admin from util.converter import RegexConverter from util.csrf import generate_csrf_token app = Flask(__name__.split('.')[0]) app.secret_key = config.SECRET_KEY app.url_map.converters['regex'] = RegexConverter app.jinja_env.globals['config'] = config app.jinja_env.globals['csrf_token'] = generate_csrf_token app.jinja_env.globals['is_admin'] = is_admin Themes(app, app_identifier='yelplove') # if debug property is present, let's use it try: app.debug = config.DEBUG except AttributeError: app.debug = False # This import needs to stay down here, otherwise we'll get ImportErrors when running tests import views # noqa
<commit_before># -*- coding: utf-8 -*- # flake8: noqa import views from flask import Flask from flask_themes2 import Themes import config from util.auth import is_admin from util.converter import RegexConverter from util.csrf import generate_csrf_token app = Flask(__name__.split('.')[0]) app.secret_key = config.SECRET_KEY app.url_map.converters['regex'] = RegexConverter app.jinja_env.globals['config'] = config app.jinja_env.globals['csrf_token'] = generate_csrf_token app.jinja_env.globals['is_admin'] = is_admin Themes(app, app_identifier='yelplove') # if debug property is present, let's use it try: app.debug = config.DEBUG except AttributeError: app.debug = False <commit_msg>Fix ImportErrors when running tests, make sure pre-commit hooks still pass<commit_after>
# -*- coding: utf-8 -*- # flake8: noqa from flask import Flask from flask_themes2 import Themes import config from util.auth import is_admin from util.converter import RegexConverter from util.csrf import generate_csrf_token app = Flask(__name__.split('.')[0]) app.secret_key = config.SECRET_KEY app.url_map.converters['regex'] = RegexConverter app.jinja_env.globals['config'] = config app.jinja_env.globals['csrf_token'] = generate_csrf_token app.jinja_env.globals['is_admin'] = is_admin Themes(app, app_identifier='yelplove') # if debug property is present, let's use it try: app.debug = config.DEBUG except AttributeError: app.debug = False # This import needs to stay down here, otherwise we'll get ImportErrors when running tests import views # noqa
# -*- coding: utf-8 -*- # flake8: noqa import views from flask import Flask from flask_themes2 import Themes import config from util.auth import is_admin from util.converter import RegexConverter from util.csrf import generate_csrf_token app = Flask(__name__.split('.')[0]) app.secret_key = config.SECRET_KEY app.url_map.converters['regex'] = RegexConverter app.jinja_env.globals['config'] = config app.jinja_env.globals['csrf_token'] = generate_csrf_token app.jinja_env.globals['is_admin'] = is_admin Themes(app, app_identifier='yelplove') # if debug property is present, let's use it try: app.debug = config.DEBUG except AttributeError: app.debug = False Fix ImportErrors when running tests, make sure pre-commit hooks still pass# -*- coding: utf-8 -*- # flake8: noqa from flask import Flask from flask_themes2 import Themes import config from util.auth import is_admin from util.converter import RegexConverter from util.csrf import generate_csrf_token app = Flask(__name__.split('.')[0]) app.secret_key = config.SECRET_KEY app.url_map.converters['regex'] = RegexConverter app.jinja_env.globals['config'] = config app.jinja_env.globals['csrf_token'] = generate_csrf_token app.jinja_env.globals['is_admin'] = is_admin Themes(app, app_identifier='yelplove') # if debug property is present, let's use it try: app.debug = config.DEBUG except AttributeError: app.debug = False # This import needs to stay down here, otherwise we'll get ImportErrors when running tests import views # noqa
<commit_before># -*- coding: utf-8 -*- # flake8: noqa import views from flask import Flask from flask_themes2 import Themes import config from util.auth import is_admin from util.converter import RegexConverter from util.csrf import generate_csrf_token app = Flask(__name__.split('.')[0]) app.secret_key = config.SECRET_KEY app.url_map.converters['regex'] = RegexConverter app.jinja_env.globals['config'] = config app.jinja_env.globals['csrf_token'] = generate_csrf_token app.jinja_env.globals['is_admin'] = is_admin Themes(app, app_identifier='yelplove') # if debug property is present, let's use it try: app.debug = config.DEBUG except AttributeError: app.debug = False <commit_msg>Fix ImportErrors when running tests, make sure pre-commit hooks still pass<commit_after># -*- coding: utf-8 -*- # flake8: noqa from flask import Flask from flask_themes2 import Themes import config from util.auth import is_admin from util.converter import RegexConverter from util.csrf import generate_csrf_token app = Flask(__name__.split('.')[0]) app.secret_key = config.SECRET_KEY app.url_map.converters['regex'] = RegexConverter app.jinja_env.globals['config'] = config app.jinja_env.globals['csrf_token'] = generate_csrf_token app.jinja_env.globals['is_admin'] = is_admin Themes(app, app_identifier='yelplove') # if debug property is present, let's use it try: app.debug = config.DEBUG except AttributeError: app.debug = False # This import needs to stay down here, otherwise we'll get ImportErrors when running tests import views # noqa
68e67cee8969dbf360ed685dd8e6e76562d085d3
examples/regression_marginals.py
examples/regression_marginals.py
""" Linear regression with marginal distributions ============================================= """ import seaborn as sns sns.set(style="darkgrid") tips = sns.load_dataset("tips") color = sns.color_palette()[2] g = sns.jointplot("total_bill", "tip", data=tips, kind="reg", color=color, size=7) g.ax_joint.set(xlim=(0, 70), ylim=(0, 12))
""" Linear regression with marginal distributions ============================================= """ import seaborn as sns sns.set(style="darkgrid") tips = sns.load_dataset("tips") color = sns.color_palette()[2] g = sns.jointplot("total_bill", "tip", data=tips, kind="reg", xlim=(0, 60), ylim=(0, 12), color=color, size=7)
Set jointplot example axis limits in main call
Set jointplot example axis limits in main call
Python
bsd-3-clause
uhjish/seaborn,anntzer/seaborn,lukauskas/seaborn,mwaskom/seaborn,sauliusl/seaborn,oesteban/seaborn,q1ang/seaborn,mia1rab/seaborn,aashish24/seaborn,parantapa/seaborn,cwu2011/seaborn,huongttlan/seaborn,lypzln/seaborn,dimarkov/seaborn,arokem/seaborn,clarkfitzg/seaborn,phobson/seaborn,mwaskom/seaborn,nileracecrew/seaborn,jakevdp/seaborn,ashhher3/seaborn,gef756/seaborn,kyleam/seaborn,drewokane/seaborn,phobson/seaborn,anntzer/seaborn,aashish24/seaborn,Guokr1991/seaborn,olgabot/seaborn,jat255/seaborn,sinhrks/seaborn,mclevey/seaborn,JWarmenhoven/seaborn,arokem/seaborn,tim777z/seaborn,lukauskas/seaborn,dotsdl/seaborn,ebothmann/seaborn,muku42/seaborn,Lx37/seaborn,dhimmel/seaborn,wrobstory/seaborn,bsipocz/seaborn,petebachant/seaborn,ischwabacher/seaborn
""" Linear regression with marginal distributions ============================================= """ import seaborn as sns sns.set(style="darkgrid") tips = sns.load_dataset("tips") color = sns.color_palette()[2] g = sns.jointplot("total_bill", "tip", data=tips, kind="reg", color=color, size=7) g.ax_joint.set(xlim=(0, 70), ylim=(0, 12)) Set jointplot example axis limits in main call
""" Linear regression with marginal distributions ============================================= """ import seaborn as sns sns.set(style="darkgrid") tips = sns.load_dataset("tips") color = sns.color_palette()[2] g = sns.jointplot("total_bill", "tip", data=tips, kind="reg", xlim=(0, 60), ylim=(0, 12), color=color, size=7)
<commit_before>""" Linear regression with marginal distributions ============================================= """ import seaborn as sns sns.set(style="darkgrid") tips = sns.load_dataset("tips") color = sns.color_palette()[2] g = sns.jointplot("total_bill", "tip", data=tips, kind="reg", color=color, size=7) g.ax_joint.set(xlim=(0, 70), ylim=(0, 12)) <commit_msg>Set jointplot example axis limits in main call<commit_after>
""" Linear regression with marginal distributions ============================================= """ import seaborn as sns sns.set(style="darkgrid") tips = sns.load_dataset("tips") color = sns.color_palette()[2] g = sns.jointplot("total_bill", "tip", data=tips, kind="reg", xlim=(0, 60), ylim=(0, 12), color=color, size=7)
""" Linear regression with marginal distributions ============================================= """ import seaborn as sns sns.set(style="darkgrid") tips = sns.load_dataset("tips") color = sns.color_palette()[2] g = sns.jointplot("total_bill", "tip", data=tips, kind="reg", color=color, size=7) g.ax_joint.set(xlim=(0, 70), ylim=(0, 12)) Set jointplot example axis limits in main call""" Linear regression with marginal distributions ============================================= """ import seaborn as sns sns.set(style="darkgrid") tips = sns.load_dataset("tips") color = sns.color_palette()[2] g = sns.jointplot("total_bill", "tip", data=tips, kind="reg", xlim=(0, 60), ylim=(0, 12), color=color, size=7)
<commit_before>""" Linear regression with marginal distributions ============================================= """ import seaborn as sns sns.set(style="darkgrid") tips = sns.load_dataset("tips") color = sns.color_palette()[2] g = sns.jointplot("total_bill", "tip", data=tips, kind="reg", color=color, size=7) g.ax_joint.set(xlim=(0, 70), ylim=(0, 12)) <commit_msg>Set jointplot example axis limits in main call<commit_after>""" Linear regression with marginal distributions ============================================= """ import seaborn as sns sns.set(style="darkgrid") tips = sns.load_dataset("tips") color = sns.color_palette()[2] g = sns.jointplot("total_bill", "tip", data=tips, kind="reg", xlim=(0, 60), ylim=(0, 12), color=color, size=7)
f4bf065dac9ee40e89f02115042e86c75ea3f22c
tests/basics/generator-args.py
tests/basics/generator-args.py
# Handling of "complicated" arg forms to generators # https://github.com/micropython/micropython/issues/397 def gen(v=5): for i in range(v): yield i print(list(gen())) # Still not supported, ditto for *args and **kwargs #print(list(gen(v=10)))
# Handling of "complicated" arg forms to generators # https://github.com/micropython/micropython/issues/397 def gen(v=5): for i in range(v): yield i print(list(gen())) print(list(gen(v=10))) def g(*args, **kwargs): for i in args: yield i for k, v in kwargs.items(): yield (k, v) print(list(g(1, 2, 3, foo="bar")))
Add testcases for "complicated" args to generator functions.
tests: Add testcases for "complicated" args to generator functions.
Python
mit
xhat/micropython,puuu/micropython,emfcamp/micropython,hosaka/micropython,torwag/micropython,selste/micropython,MrSurly/micropython,tuc-osg/micropython,ceramos/micropython,ahotam/micropython,jmarcelino/pycom-micropython,tralamazza/micropython,ganshun666/micropython,stonegithubs/micropython,lbattraw/micropython,ceramos/micropython,slzatz/micropython,chrisdearman/micropython,jlillest/micropython,xuxiaoxin/micropython,PappaPeppar/micropython,trezor/micropython,cloudformdesign/micropython,mgyenik/micropython,ericsnowcurrently/micropython,xhat/micropython,orionrobots/micropython,toolmacher/micropython,adafruit/circuitpython,praemdonck/micropython,warner83/micropython,lowRISC/micropython,ChuckM/micropython,jimkmc/micropython,danicampora/micropython,cnoviello/micropython,ryannathans/micropython,vriera/micropython,xuxiaoxin/micropython,tobbad/micropython,skybird6672/micropython,swegener/micropython,martinribelotta/micropython,rubencabrera/micropython,ceramos/micropython,ahotam/micropython,noahwilliamsson/micropython,paul-xxx/micropython,blazewicz/micropython,slzatz/micropython,jmarcelino/pycom-micropython,ceramos/micropython,blmorris/micropython,drrk/micropython,emfcamp/micropython,noahchense/micropython,lowRISC/micropython,ruffy91/micropython,xyb/micropython,dxxb/micropython,cloudformdesign/micropython,cwyark/micropython,jimkmc/micropython,PappaPeppar/micropython,lbattraw/micropython,dxxb/micropython,martinribelotta/micropython,hosaka/micropython,mhoffma/micropython,HenrikSolver/micropython,mgyenik/micropython,torwag/micropython,turbinenreiter/micropython,adafruit/micropython,noahchense/micropython,supergis/micropython,redbear/micropython,adamkh/micropython,trezor/micropython,adafruit/circuitpython,ahotam/micropython,EcmaXp/micropython,swegener/micropython,galenhz/micropython,TDAbboud/micropython,oopy/micropython,cloudformdesign/micropython,omtinez/micropython,tdautc19841202/micropython,tralamazza/micropython,cwyark/micropython,hiway/micropython,Timmenem/micropython,skybird6672/micropython,SHA2017-badge/micropython-esp32,hosaka/micropython,adafruit/micropython,paul-xxx/micropython,KISSMonX/micropython,pfalcon/micropython,rubencabrera/micropython,ChuckM/micropython,hiway/micropython,utopiaprince/micropython,AriZuu/micropython,dhylands/micropython,torwag/micropython,Timmenem/micropython,Timmenem/micropython,jmarcelino/pycom-micropython,pramasoul/micropython,warner83/micropython,oopy/micropython,dinau/micropython,feilongfl/micropython,micropython/micropython-esp32,ahotam/micropython,adafruit/micropython,SungEun-Steve-Kim/test-mp,danicampora/micropython,xuxiaoxin/micropython,mgyenik/micropython,alex-march/micropython,chrisdearman/micropython,vitiral/micropython,TDAbboud/micropython,kerneltask/micropython,vriera/micropython,mhoffma/micropython,vriera/micropython,jimkmc/micropython,stonegithubs/micropython,mianos/micropython,EcmaXp/micropython,cnoviello/micropython,Vogtinator/micropython,MrSurly/micropython-esp32,dmazzella/micropython,ruffy91/micropython,orionrobots/micropython,alex-robbins/micropython,matthewelse/micropython,jmarcelino/pycom-micropython,warner83/micropython,suda/micropython,redbear/micropython,alex-march/micropython,methoxid/micropystat,ceramos/micropython,toolmacher/micropython,misterdanb/micropython,ganshun666/micropython,oopy/micropython,ericsnowcurrently/micropython,adamkh/micropython,hiway/micropython,lbattraw/micropython,dinau/micropython,dhylands/micropython,praemdonck/micropython,cwyark/micropython,alex-robbins/micropython,drrk/micropython,redbear/micropython,adamkh/micropython,blazewicz/micropython,suda/micropython,adafruit/circuitpython,deshipu/micropython,HenrikSolver/micropython,swegener/micropython,omtinez/micropython,pramasoul/micropython,pozetroninc/micropython,jmarcelino/pycom-micropython,hiway/micropython,noahchense/micropython,ryannathans/micropython,xhat/micropython,heisewangluo/micropython,ericsnowcurrently/micropython,HenrikSolver/micropython,deshipu/micropython,utopiaprince/micropython,misterdanb/micropython,suda/micropython,tobbad/micropython,torwag/micropython,emfcamp/micropython,aethaniel/micropython,mpalomer/micropython,adafruit/circuitpython,ruffy91/micropython,toolmacher/micropython,firstval/micropython,tuc-osg/micropython,neilh10/micropython,trezor/micropython,pozetroninc/micropython,pfalcon/micropython,mianos/micropython,blmorris/micropython,methoxid/micropystat,kostyll/micropython,dhylands/micropython,tobbad/micropython,bvernoux/micropython,MrSurly/micropython,mpalomer/micropython,ahotam/micropython,orionrobots/micropython,TDAbboud/micropython,galenhz/micropython,martinribelotta/micropython,pfalcon/micropython,feilongfl/micropython,henriknelson/micropython,turbinenreiter/micropython,cnoviello/micropython,rubencabrera/micropython,mianos/micropython,slzatz/micropython,ganshun666/micropython,tobbad/micropython,mhoffma/micropython,Timmenem/micropython,xuxiaoxin/micropython,ernesto-g/micropython,mhoffma/micropython,puuu/micropython,xhat/micropython,martinribelotta/micropython,ernesto-g/micropython,alex-robbins/micropython,Vogtinator/micropython,infinnovation/micropython,paul-xxx/micropython,lbattraw/micropython,lowRISC/micropython,warner83/micropython,cnoviello/micropython,stonegithubs/micropython,vitiral/micropython,Vogtinator/micropython,hiway/micropython,SHA2017-badge/micropython-esp32,infinnovation/micropython,alex-march/micropython,xyb/micropython,selste/micropython,jlillest/micropython,methoxid/micropystat,mpalomer/micropython,henriknelson/micropython,redbear/micropython,puuu/micropython,alex-robbins/micropython,ganshun666/micropython,dhylands/micropython,deshipu/micropython,MrSurly/micropython,heisewangluo/micropython,tdautc19841202/micropython,ChuckM/micropython,micropython/micropython-esp32,danicampora/micropython,matthewelse/micropython,feilongfl/micropython,noahchense/micropython,ernesto-g/micropython,firstval/micropython,xyb/micropython,methoxid/micropystat,noahwilliamsson/micropython,danicampora/micropython,Peetz0r/micropython-esp32,ericsnowcurrently/micropython,tdautc19841202/micropython,ChuckM/micropython,dmazzella/micropython,kerneltask/micropython,SHA2017-badge/micropython-esp32,orionrobots/micropython,supergis/micropython,bvernoux/micropython,kerneltask/micropython,tuc-osg/micropython,vitiral/micropython,misterdanb/micropython,infinnovation/micropython,warner83/micropython,praemdonck/micropython,AriZuu/micropython,drrk/micropython,matthewelse/micropython,alex-robbins/micropython,selste/micropython,vitiral/micropython,galenhz/micropython,mgyenik/micropython,adafruit/micropython,trezor/micropython,slzatz/micropython,mhoffma/micropython,ganshun666/micropython,feilongfl/micropython,vriera/micropython,ChuckM/micropython,pfalcon/micropython,trezor/micropython,jlillest/micropython,ryannathans/micropython,Peetz0r/micropython-esp32,micropython/micropython-esp32,neilh10/micropython,jlillest/micropython,praemdonck/micropython,dinau/micropython,MrSurly/micropython,mpalomer/micropython,ryannathans/micropython,turbinenreiter/micropython,dhylands/micropython,emfcamp/micropython,pozetroninc/micropython,praemdonck/micropython,micropython/micropython-esp32,TDAbboud/micropython,supergis/micropython,SHA2017-badge/micropython-esp32,blazewicz/micropython,Peetz0r/micropython-esp32,vriera/micropython,heisewangluo/micropython,Peetz0r/micropython-esp32,drrk/micropython,danicampora/micropython,SungEun-Steve-Kim/test-mp,rubencabrera/micropython,tdautc19841202/micropython,oopy/micropython,dmazzella/micropython,kostyll/micropython,cwyark/micropython,MrSurly/micropython-esp32,SungEun-Steve-Kim/test-mp,bvernoux/micropython,AriZuu/micropython,firstval/micropython,dxxb/micropython,neilh10/micropython,mianos/micropython,neilh10/micropython,Vogtinator/micropython,redbear/micropython,SungEun-Steve-Kim/test-mp,pramasoul/micropython,methoxid/micropystat,xuxiaoxin/micropython,bvernoux/micropython,jlillest/micropython,emfcamp/micropython,skybird6672/micropython,xyb/micropython,kerneltask/micropython,vitiral/micropython,utopiaprince/micropython,suda/micropython,mgyenik/micropython,toolmacher/micropython,aethaniel/micropython,selste/micropython,cwyark/micropython,misterdanb/micropython,paul-xxx/micropython,misterdanb/micropython,chrisdearman/micropython,KISSMonX/micropython,omtinez/micropython,tuc-osg/micropython,adafruit/circuitpython,micropython/micropython-esp32,EcmaXp/micropython,PappaPeppar/micropython,chrisdearman/micropython,drrk/micropython,AriZuu/micropython,utopiaprince/micropython,martinribelotta/micropython,adafruit/micropython,hosaka/micropython,tuc-osg/micropython,stonegithubs/micropython,lowRISC/micropython,firstval/micropython,supergis/micropython,matthewelse/micropython,xyb/micropython,infinnovation/micropython,Peetz0r/micropython-esp32,lbattraw/micropython,dmazzella/micropython,HenrikSolver/micropython,firstval/micropython,EcmaXp/micropython,PappaPeppar/micropython,MrSurly/micropython-esp32,dxxb/micropython,matthewelse/micropython,deshipu/micropython,galenhz/micropython,orionrobots/micropython,hosaka/micropython,adafruit/circuitpython,kostyll/micropython,mpalomer/micropython,jimkmc/micropython,neilh10/micropython,HenrikSolver/micropython,adamkh/micropython,ryannathans/micropython,tralamazza/micropython,SHA2017-badge/micropython-esp32,ernesto-g/micropython,infinnovation/micropython,noahwilliamsson/micropython,cloudformdesign/micropython,skybird6672/micropython,henriknelson/micropython,KISSMonX/micropython,blmorris/micropython,stonegithubs/micropython,Vogtinator/micropython,suda/micropython,heisewangluo/micropython,ruffy91/micropython,heisewangluo/micropython,noahchense/micropython,oopy/micropython,adamkh/micropython,tdautc19841202/micropython,noahwilliamsson/micropython,tralamazza/micropython,aethaniel/micropython,tobbad/micropython,kostyll/micropython,KISSMonX/micropython,cnoviello/micropython,henriknelson/micropython,MrSurly/micropython,swegener/micropython,bvernoux/micropython,blazewicz/micropython,supergis/micropython,kerneltask/micropython,pramasoul/micropython,puuu/micropython,alex-march/micropython,dxxb/micropython,lowRISC/micropython,ernesto-g/micropython,ruffy91/micropython,pramasoul/micropython,omtinez/micropython,PappaPeppar/micropython,turbinenreiter/micropython,Timmenem/micropython,ericsnowcurrently/micropython,blazewicz/micropython,pozetroninc/micropython,jimkmc/micropython,skybird6672/micropython,TDAbboud/micropython,swegener/micropython,MrSurly/micropython-esp32,omtinez/micropython,MrSurly/micropython-esp32,henriknelson/micropython,rubencabrera/micropython,pfalcon/micropython,SungEun-Steve-Kim/test-mp,aethaniel/micropython,galenhz/micropython,pozetroninc/micropython,turbinenreiter/micropython,chrisdearman/micropython,cloudformdesign/micropython,utopiaprince/micropython,torwag/micropython,feilongfl/micropython,blmorris/micropython,matthewelse/micropython,EcmaXp/micropython,dinau/micropython,alex-march/micropython,puuu/micropython,xhat/micropython,aethaniel/micropython,AriZuu/micropython,toolmacher/micropython,deshipu/micropython,selste/micropython,blmorris/micropython,KISSMonX/micropython,paul-xxx/micropython,dinau/micropython,slzatz/micropython,noahwilliamsson/micropython,mianos/micropython,kostyll/micropython
# Handling of "complicated" arg forms to generators # https://github.com/micropython/micropython/issues/397 def gen(v=5): for i in range(v): yield i print(list(gen())) # Still not supported, ditto for *args and **kwargs #print(list(gen(v=10))) tests: Add testcases for "complicated" args to generator functions.
# Handling of "complicated" arg forms to generators # https://github.com/micropython/micropython/issues/397 def gen(v=5): for i in range(v): yield i print(list(gen())) print(list(gen(v=10))) def g(*args, **kwargs): for i in args: yield i for k, v in kwargs.items(): yield (k, v) print(list(g(1, 2, 3, foo="bar")))
<commit_before># Handling of "complicated" arg forms to generators # https://github.com/micropython/micropython/issues/397 def gen(v=5): for i in range(v): yield i print(list(gen())) # Still not supported, ditto for *args and **kwargs #print(list(gen(v=10))) <commit_msg>tests: Add testcases for "complicated" args to generator functions.<commit_after>
# Handling of "complicated" arg forms to generators # https://github.com/micropython/micropython/issues/397 def gen(v=5): for i in range(v): yield i print(list(gen())) print(list(gen(v=10))) def g(*args, **kwargs): for i in args: yield i for k, v in kwargs.items(): yield (k, v) print(list(g(1, 2, 3, foo="bar")))
# Handling of "complicated" arg forms to generators # https://github.com/micropython/micropython/issues/397 def gen(v=5): for i in range(v): yield i print(list(gen())) # Still not supported, ditto for *args and **kwargs #print(list(gen(v=10))) tests: Add testcases for "complicated" args to generator functions.# Handling of "complicated" arg forms to generators # https://github.com/micropython/micropython/issues/397 def gen(v=5): for i in range(v): yield i print(list(gen())) print(list(gen(v=10))) def g(*args, **kwargs): for i in args: yield i for k, v in kwargs.items(): yield (k, v) print(list(g(1, 2, 3, foo="bar")))
<commit_before># Handling of "complicated" arg forms to generators # https://github.com/micropython/micropython/issues/397 def gen(v=5): for i in range(v): yield i print(list(gen())) # Still not supported, ditto for *args and **kwargs #print(list(gen(v=10))) <commit_msg>tests: Add testcases for "complicated" args to generator functions.<commit_after># Handling of "complicated" arg forms to generators # https://github.com/micropython/micropython/issues/397 def gen(v=5): for i in range(v): yield i print(list(gen())) print(list(gen(v=10))) def g(*args, **kwargs): for i in args: yield i for k, v in kwargs.items(): yield (k, v) print(list(g(1, 2, 3, foo="bar")))
c1b8f935801ca8925c0f3b001a2582136cb861ad
nani.py
nani.py
#!/usr/bin/env python3 """Information overview for command line tools. Usage: nani <command> nani -h | --help nani --version Options: -h, --help Print this message and exit. --version Print version info and exit. """ from docopt import docopt import subprocess if __name__ == '__main__': arguments = docopt(__doc__, version='nani 0.2.0') subprocess.call(['which', arguments['<command>']])
#!/usr/bin/env python3 """Information overview for command line tools. Usage: nani <command> nani -h | --help nani --version Options: -h, --help Print this message and exit. --version Print version info and exit. """ from docopt import docopt import sys import subprocess if __name__ == '__main__': arguments = docopt(__doc__, version='nani 0.3.0') ret = subprocess.call(['type', arguments['<command>']]) sys.exit(ret)
Call type instead of which
Call type instead of which
Python
mit
fenhl/nani
#!/usr/bin/env python3 """Information overview for command line tools. Usage: nani <command> nani -h | --help nani --version Options: -h, --help Print this message and exit. --version Print version info and exit. """ from docopt import docopt import subprocess if __name__ == '__main__': arguments = docopt(__doc__, version='nani 0.2.0') subprocess.call(['which', arguments['<command>']]) Call type instead of which
#!/usr/bin/env python3 """Information overview for command line tools. Usage: nani <command> nani -h | --help nani --version Options: -h, --help Print this message and exit. --version Print version info and exit. """ from docopt import docopt import sys import subprocess if __name__ == '__main__': arguments = docopt(__doc__, version='nani 0.3.0') ret = subprocess.call(['type', arguments['<command>']]) sys.exit(ret)
<commit_before>#!/usr/bin/env python3 """Information overview for command line tools. Usage: nani <command> nani -h | --help nani --version Options: -h, --help Print this message and exit. --version Print version info and exit. """ from docopt import docopt import subprocess if __name__ == '__main__': arguments = docopt(__doc__, version='nani 0.2.0') subprocess.call(['which', arguments['<command>']]) <commit_msg>Call type instead of which<commit_after>
#!/usr/bin/env python3 """Information overview for command line tools. Usage: nani <command> nani -h | --help nani --version Options: -h, --help Print this message and exit. --version Print version info and exit. """ from docopt import docopt import sys import subprocess if __name__ == '__main__': arguments = docopt(__doc__, version='nani 0.3.0') ret = subprocess.call(['type', arguments['<command>']]) sys.exit(ret)
#!/usr/bin/env python3 """Information overview for command line tools. Usage: nani <command> nani -h | --help nani --version Options: -h, --help Print this message and exit. --version Print version info and exit. """ from docopt import docopt import subprocess if __name__ == '__main__': arguments = docopt(__doc__, version='nani 0.2.0') subprocess.call(['which', arguments['<command>']]) Call type instead of which#!/usr/bin/env python3 """Information overview for command line tools. Usage: nani <command> nani -h | --help nani --version Options: -h, --help Print this message and exit. --version Print version info and exit. """ from docopt import docopt import sys import subprocess if __name__ == '__main__': arguments = docopt(__doc__, version='nani 0.3.0') ret = subprocess.call(['type', arguments['<command>']]) sys.exit(ret)
<commit_before>#!/usr/bin/env python3 """Information overview for command line tools. Usage: nani <command> nani -h | --help nani --version Options: -h, --help Print this message and exit. --version Print version info and exit. """ from docopt import docopt import subprocess if __name__ == '__main__': arguments = docopt(__doc__, version='nani 0.2.0') subprocess.call(['which', arguments['<command>']]) <commit_msg>Call type instead of which<commit_after>#!/usr/bin/env python3 """Information overview for command line tools. Usage: nani <command> nani -h | --help nani --version Options: -h, --help Print this message and exit. --version Print version info and exit. """ from docopt import docopt import sys import subprocess if __name__ == '__main__': arguments = docopt(__doc__, version='nani 0.3.0') ret = subprocess.call(['type', arguments['<command>']]) sys.exit(ret)
001a50b236e60358cf1fbe371d6d20ea72003ceb
noms.py
noms.py
#!/usr/bin/env python3 from config import WOLFRAM_KEY import wolframalpha POD_TITLE = 'Average nutrition facts' QUERY = input() def get_macros(pod_text): items = pod_text.split("|") for t in items: chunks = t.split() if 'protein' in chunks: protein = tuple(chunks[-2::]) elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = tuple(chunks[-2::]) elif 'fat' in chunks: fat = tuple(chunks[-2::]) return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) print("Fat: " + macros[2][0] + macros[2][1]) print("Carbs: " + macros[1][0] + macros[1][1])
#!/usr/bin/env python3 from config import WOLFRAM_KEY import sys import wolframalpha POD_TITLE = 'Average nutrition facts' QUERY = input() def get_macros(pod_text): items = pod_text.split("|") for t in items: chunks = t.split() if 'protein' in chunks: protein = chunks[-2::] elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = chunks[-2::] elif 'fat' in chunks: fat = chunks[-2::] return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) try: macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) except IndexError: print(QUERY + '\'s macros not found on Wolfram.') sys.exit(1) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) print("Fat: " + macros[2][0] + macros[2][1]) print("Carbs: " + macros[1][0] + macros[1][1])
Add some basic error handling and remove tuples.
Add some basic error handling and remove tuples. No need for tuples when the lists are going to be so small. The speed difference between the two will be minimal.
Python
mit
brotatos/noms
#!/usr/bin/env python3 from config import WOLFRAM_KEY import wolframalpha POD_TITLE = 'Average nutrition facts' QUERY = input() def get_macros(pod_text): items = pod_text.split("|") for t in items: chunks = t.split() if 'protein' in chunks: protein = tuple(chunks[-2::]) elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = tuple(chunks[-2::]) elif 'fat' in chunks: fat = tuple(chunks[-2::]) return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) print("Fat: " + macros[2][0] + macros[2][1]) print("Carbs: " + macros[1][0] + macros[1][1]) Add some basic error handling and remove tuples. No need for tuples when the lists are going to be so small. The speed difference between the two will be minimal.
#!/usr/bin/env python3 from config import WOLFRAM_KEY import sys import wolframalpha POD_TITLE = 'Average nutrition facts' QUERY = input() def get_macros(pod_text): items = pod_text.split("|") for t in items: chunks = t.split() if 'protein' in chunks: protein = chunks[-2::] elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = chunks[-2::] elif 'fat' in chunks: fat = chunks[-2::] return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) try: macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) except IndexError: print(QUERY + '\'s macros not found on Wolfram.') sys.exit(1) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) print("Fat: " + macros[2][0] + macros[2][1]) print("Carbs: " + macros[1][0] + macros[1][1])
<commit_before>#!/usr/bin/env python3 from config import WOLFRAM_KEY import wolframalpha POD_TITLE = 'Average nutrition facts' QUERY = input() def get_macros(pod_text): items = pod_text.split("|") for t in items: chunks = t.split() if 'protein' in chunks: protein = tuple(chunks[-2::]) elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = tuple(chunks[-2::]) elif 'fat' in chunks: fat = tuple(chunks[-2::]) return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) print("Fat: " + macros[2][0] + macros[2][1]) print("Carbs: " + macros[1][0] + macros[1][1]) <commit_msg>Add some basic error handling and remove tuples. No need for tuples when the lists are going to be so small. The speed difference between the two will be minimal.<commit_after>
#!/usr/bin/env python3 from config import WOLFRAM_KEY import sys import wolframalpha POD_TITLE = 'Average nutrition facts' QUERY = input() def get_macros(pod_text): items = pod_text.split("|") for t in items: chunks = t.split() if 'protein' in chunks: protein = chunks[-2::] elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = chunks[-2::] elif 'fat' in chunks: fat = chunks[-2::] return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) try: macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) except IndexError: print(QUERY + '\'s macros not found on Wolfram.') sys.exit(1) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) print("Fat: " + macros[2][0] + macros[2][1]) print("Carbs: " + macros[1][0] + macros[1][1])
#!/usr/bin/env python3 from config import WOLFRAM_KEY import wolframalpha POD_TITLE = 'Average nutrition facts' QUERY = input() def get_macros(pod_text): items = pod_text.split("|") for t in items: chunks = t.split() if 'protein' in chunks: protein = tuple(chunks[-2::]) elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = tuple(chunks[-2::]) elif 'fat' in chunks: fat = tuple(chunks[-2::]) return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) print("Fat: " + macros[2][0] + macros[2][1]) print("Carbs: " + macros[1][0] + macros[1][1]) Add some basic error handling and remove tuples. No need for tuples when the lists are going to be so small. The speed difference between the two will be minimal.#!/usr/bin/env python3 from config import WOLFRAM_KEY import sys import wolframalpha POD_TITLE = 'Average nutrition facts' QUERY = input() def get_macros(pod_text): items = pod_text.split("|") for t in items: chunks = t.split() if 'protein' in chunks: protein = chunks[-2::] elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = chunks[-2::] elif 'fat' in chunks: fat = chunks[-2::] return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) try: macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) except IndexError: print(QUERY + '\'s macros not found on Wolfram.') sys.exit(1) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) print("Fat: " + macros[2][0] + macros[2][1]) print("Carbs: " + macros[1][0] + macros[1][1])
<commit_before>#!/usr/bin/env python3 from config import WOLFRAM_KEY import wolframalpha POD_TITLE = 'Average nutrition facts' QUERY = input() def get_macros(pod_text): items = pod_text.split("|") for t in items: chunks = t.split() if 'protein' in chunks: protein = tuple(chunks[-2::]) elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = tuple(chunks[-2::]) elif 'fat' in chunks: fat = tuple(chunks[-2::]) return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) print("Fat: " + macros[2][0] + macros[2][1]) print("Carbs: " + macros[1][0] + macros[1][1]) <commit_msg>Add some basic error handling and remove tuples. No need for tuples when the lists are going to be so small. The speed difference between the two will be minimal.<commit_after>#!/usr/bin/env python3 from config import WOLFRAM_KEY import sys import wolframalpha POD_TITLE = 'Average nutrition facts' QUERY = input() def get_macros(pod_text): items = pod_text.split("|") for t in items: chunks = t.split() if 'protein' in chunks: protein = chunks[-2::] elif 'total' in chunks: if 'carbohydrates' in chunks: carbs = chunks[-2::] elif 'fat' in chunks: fat = chunks[-2::] return protein, carbs, fat client = wolframalpha.Client(WOLFRAM_KEY) res = client.query(QUERY) try: macros = get_macros([p for p in res.pods if p.title == POD_TITLE][0].text) except IndexError: print(QUERY + '\'s macros not found on Wolfram.') sys.exit(1) print('-' * len(QUERY)) print("Protein: " + macros[0][0] + macros[0][1]) print("Fat: " + macros[2][0] + macros[2][1]) print("Carbs: " + macros[1][0] + macros[1][1])
c4765dc1d68e5a0f20fa94841c0d2ae4d1123918
maildump/web.py
maildump/web.py
from flask import Flask, render_template, jsonify from logbook import Logger from functools import wraps import maildump import maildump.db as db app = Flask(__name__) app._logger = log = Logger(__name__) def rest(f): """Decorator for simple REST endpoints. Functions must return one of these values: - a dict to jsonify - nothing for an empty 204 response - a tuple containing a status code and a dict to jsonify """ @wraps(f) def wrapper(*args, **kwargs): ret = f(*args, **kwargs) if ret is None: response = jsonify() response.status_code = 204 # no content elif isinstance(ret, tuple): # code, result_dict response = jsonify(**ret[1]) response.status_code = ret[0] else: response = jsonify(**ret) return response return wrapper @app.route('/') def home(): return render_template('index.html') @app.route('/', methods=('DELETE',)) @rest def terminate(): log.debug('Terminate request received') maildump.stop() @app.route('/messages', methods=('DELETE',)) @rest def delete_messages(): db.delete_messages()
import json from datetime import datetime from flask import Flask, render_template, jsonify from logbook import Logger from functools import wraps import maildump import maildump.db as db app = Flask(__name__) app._logger = log = Logger(__name__) def _json_default(obj): if isinstance(obj, datetime): return obj.isoformat() raise TypeError(repr(obj) + ' is not JSON serializable') def jsonify(*args, **kwargs): return app.response_class(json.dumps(dict(*args, **kwargs), default=_json_default, indent=4), mimetype='application/json') def rest(f): """Decorator for simple REST endpoints. Functions must return one of these values: - a dict to jsonify - nothing for an empty 204 response - a tuple containing a status code and a dict to jsonify """ @wraps(f) def wrapper(*args, **kwargs): ret = f(*args, **kwargs) if ret is None: response = jsonify() response.status_code = 204 # no content elif isinstance(ret, tuple): # code, result_dict response = jsonify(**ret[1]) response.status_code = ret[0] else: response = jsonify(**ret) return response return wrapper @app.route('/') def home(): return render_template('index.html') @app.route('/', methods=('DELETE',)) @rest def terminate(): log.debug('Terminate request received') maildump.stop() @app.route('/messages', methods=('DELETE',)) @rest def delete_messages(): db.delete_messages()
Support json encoding of datetime objects
Support json encoding of datetime objects
Python
mit
luzfcb/maildump,luzfcb/maildump,webpartners/maildump,luzfcb/maildump,webpartners/maildump,webpartners/maildump,ThiefMaster/maildump,ThiefMaster/maildump,ThiefMaster/maildump,webpartners/maildump,luzfcb/maildump,ThiefMaster/maildump
from flask import Flask, render_template, jsonify from logbook import Logger from functools import wraps import maildump import maildump.db as db app = Flask(__name__) app._logger = log = Logger(__name__) def rest(f): """Decorator for simple REST endpoints. Functions must return one of these values: - a dict to jsonify - nothing for an empty 204 response - a tuple containing a status code and a dict to jsonify """ @wraps(f) def wrapper(*args, **kwargs): ret = f(*args, **kwargs) if ret is None: response = jsonify() response.status_code = 204 # no content elif isinstance(ret, tuple): # code, result_dict response = jsonify(**ret[1]) response.status_code = ret[0] else: response = jsonify(**ret) return response return wrapper @app.route('/') def home(): return render_template('index.html') @app.route('/', methods=('DELETE',)) @rest def terminate(): log.debug('Terminate request received') maildump.stop() @app.route('/messages', methods=('DELETE',)) @rest def delete_messages(): db.delete_messages()Support json encoding of datetime objects
import json from datetime import datetime from flask import Flask, render_template, jsonify from logbook import Logger from functools import wraps import maildump import maildump.db as db app = Flask(__name__) app._logger = log = Logger(__name__) def _json_default(obj): if isinstance(obj, datetime): return obj.isoformat() raise TypeError(repr(obj) + ' is not JSON serializable') def jsonify(*args, **kwargs): return app.response_class(json.dumps(dict(*args, **kwargs), default=_json_default, indent=4), mimetype='application/json') def rest(f): """Decorator for simple REST endpoints. Functions must return one of these values: - a dict to jsonify - nothing for an empty 204 response - a tuple containing a status code and a dict to jsonify """ @wraps(f) def wrapper(*args, **kwargs): ret = f(*args, **kwargs) if ret is None: response = jsonify() response.status_code = 204 # no content elif isinstance(ret, tuple): # code, result_dict response = jsonify(**ret[1]) response.status_code = ret[0] else: response = jsonify(**ret) return response return wrapper @app.route('/') def home(): return render_template('index.html') @app.route('/', methods=('DELETE',)) @rest def terminate(): log.debug('Terminate request received') maildump.stop() @app.route('/messages', methods=('DELETE',)) @rest def delete_messages(): db.delete_messages()
<commit_before>from flask import Flask, render_template, jsonify from logbook import Logger from functools import wraps import maildump import maildump.db as db app = Flask(__name__) app._logger = log = Logger(__name__) def rest(f): """Decorator for simple REST endpoints. Functions must return one of these values: - a dict to jsonify - nothing for an empty 204 response - a tuple containing a status code and a dict to jsonify """ @wraps(f) def wrapper(*args, **kwargs): ret = f(*args, **kwargs) if ret is None: response = jsonify() response.status_code = 204 # no content elif isinstance(ret, tuple): # code, result_dict response = jsonify(**ret[1]) response.status_code = ret[0] else: response = jsonify(**ret) return response return wrapper @app.route('/') def home(): return render_template('index.html') @app.route('/', methods=('DELETE',)) @rest def terminate(): log.debug('Terminate request received') maildump.stop() @app.route('/messages', methods=('DELETE',)) @rest def delete_messages(): db.delete_messages()<commit_msg>Support json encoding of datetime objects<commit_after>
import json from datetime import datetime from flask import Flask, render_template, jsonify from logbook import Logger from functools import wraps import maildump import maildump.db as db app = Flask(__name__) app._logger = log = Logger(__name__) def _json_default(obj): if isinstance(obj, datetime): return obj.isoformat() raise TypeError(repr(obj) + ' is not JSON serializable') def jsonify(*args, **kwargs): return app.response_class(json.dumps(dict(*args, **kwargs), default=_json_default, indent=4), mimetype='application/json') def rest(f): """Decorator for simple REST endpoints. Functions must return one of these values: - a dict to jsonify - nothing for an empty 204 response - a tuple containing a status code and a dict to jsonify """ @wraps(f) def wrapper(*args, **kwargs): ret = f(*args, **kwargs) if ret is None: response = jsonify() response.status_code = 204 # no content elif isinstance(ret, tuple): # code, result_dict response = jsonify(**ret[1]) response.status_code = ret[0] else: response = jsonify(**ret) return response return wrapper @app.route('/') def home(): return render_template('index.html') @app.route('/', methods=('DELETE',)) @rest def terminate(): log.debug('Terminate request received') maildump.stop() @app.route('/messages', methods=('DELETE',)) @rest def delete_messages(): db.delete_messages()
from flask import Flask, render_template, jsonify from logbook import Logger from functools import wraps import maildump import maildump.db as db app = Flask(__name__) app._logger = log = Logger(__name__) def rest(f): """Decorator for simple REST endpoints. Functions must return one of these values: - a dict to jsonify - nothing for an empty 204 response - a tuple containing a status code and a dict to jsonify """ @wraps(f) def wrapper(*args, **kwargs): ret = f(*args, **kwargs) if ret is None: response = jsonify() response.status_code = 204 # no content elif isinstance(ret, tuple): # code, result_dict response = jsonify(**ret[1]) response.status_code = ret[0] else: response = jsonify(**ret) return response return wrapper @app.route('/') def home(): return render_template('index.html') @app.route('/', methods=('DELETE',)) @rest def terminate(): log.debug('Terminate request received') maildump.stop() @app.route('/messages', methods=('DELETE',)) @rest def delete_messages(): db.delete_messages()Support json encoding of datetime objectsimport json from datetime import datetime from flask import Flask, render_template, jsonify from logbook import Logger from functools import wraps import maildump import maildump.db as db app = Flask(__name__) app._logger = log = Logger(__name__) def _json_default(obj): if isinstance(obj, datetime): return obj.isoformat() raise TypeError(repr(obj) + ' is not JSON serializable') def jsonify(*args, **kwargs): return app.response_class(json.dumps(dict(*args, **kwargs), default=_json_default, indent=4), mimetype='application/json') def rest(f): """Decorator for simple REST endpoints. Functions must return one of these values: - a dict to jsonify - nothing for an empty 204 response - a tuple containing a status code and a dict to jsonify """ @wraps(f) def wrapper(*args, **kwargs): ret = f(*args, **kwargs) if ret is None: response = jsonify() response.status_code = 204 # no content elif isinstance(ret, tuple): # code, result_dict response = jsonify(**ret[1]) response.status_code = ret[0] else: response = jsonify(**ret) return response return wrapper @app.route('/') def home(): return render_template('index.html') @app.route('/', methods=('DELETE',)) @rest def terminate(): log.debug('Terminate request received') maildump.stop() @app.route('/messages', methods=('DELETE',)) @rest def delete_messages(): db.delete_messages()
<commit_before>from flask import Flask, render_template, jsonify from logbook import Logger from functools import wraps import maildump import maildump.db as db app = Flask(__name__) app._logger = log = Logger(__name__) def rest(f): """Decorator for simple REST endpoints. Functions must return one of these values: - a dict to jsonify - nothing for an empty 204 response - a tuple containing a status code and a dict to jsonify """ @wraps(f) def wrapper(*args, **kwargs): ret = f(*args, **kwargs) if ret is None: response = jsonify() response.status_code = 204 # no content elif isinstance(ret, tuple): # code, result_dict response = jsonify(**ret[1]) response.status_code = ret[0] else: response = jsonify(**ret) return response return wrapper @app.route('/') def home(): return render_template('index.html') @app.route('/', methods=('DELETE',)) @rest def terminate(): log.debug('Terminate request received') maildump.stop() @app.route('/messages', methods=('DELETE',)) @rest def delete_messages(): db.delete_messages()<commit_msg>Support json encoding of datetime objects<commit_after>import json from datetime import datetime from flask import Flask, render_template, jsonify from logbook import Logger from functools import wraps import maildump import maildump.db as db app = Flask(__name__) app._logger = log = Logger(__name__) def _json_default(obj): if isinstance(obj, datetime): return obj.isoformat() raise TypeError(repr(obj) + ' is not JSON serializable') def jsonify(*args, **kwargs): return app.response_class(json.dumps(dict(*args, **kwargs), default=_json_default, indent=4), mimetype='application/json') def rest(f): """Decorator for simple REST endpoints. Functions must return one of these values: - a dict to jsonify - nothing for an empty 204 response - a tuple containing a status code and a dict to jsonify """ @wraps(f) def wrapper(*args, **kwargs): ret = f(*args, **kwargs) if ret is None: response = jsonify() response.status_code = 204 # no content elif isinstance(ret, tuple): # code, result_dict response = jsonify(**ret[1]) response.status_code = ret[0] else: response = jsonify(**ret) return response return wrapper @app.route('/') def home(): return render_template('index.html') @app.route('/', methods=('DELETE',)) @rest def terminate(): log.debug('Terminate request received') maildump.stop() @app.route('/messages', methods=('DELETE',)) @rest def delete_messages(): db.delete_messages()